Skip to main content

devpage_core/folder/
sight.rs

1//! What of the served folder is in sight, and what a change to it means for
2//! open pages: the folders to watch (nothing out of sight is watched, so the
3//! platform never reports a build rewriting `target/` — not even to be
4//! dropped), whether a changed path can matter at all, judged from the path
5//! alone, and whether it refreshes open pages, by the `watch` list of the
6//! site that owns it.
7
8use std::collections::BTreeSet;
9use std::path::{Path, PathBuf};
10use std::sync::Arc;
11
12use super::Folder;
13use crate::document::{Document, KindName};
14
15/// The folders to watch: `deep` ones recursively, `shallow` ones for their
16/// entries and the files directly in them.
17#[derive(Debug, Default, Clone, PartialEq, Eq)]
18pub struct WatchSet {
19    /// The largest folders with nothing out of sight anywhere under them.
20    pub deep: BTreeSet<PathBuf>,
21    /// Folders in sight that hold something out of sight.
22    pub shallow: BTreeSet<PathBuf>,
23}
24
25impl WatchSet {
26    /// The watch set of `folder`, judged by its `.gitignore` rules and every
27    /// site's `watch` list. Walks only what is in sight: an out-of-sight
28    /// folder is never read.
29    pub(super) fn plan(folder: &Folder) -> Self {
30        let sight = Sight {
31            served: folder.served().path(),
32            folder,
33            roots: watch_roots(folder),
34        };
35        let mut set = Self::default();
36        if sight.walk(sight.served, &mut set) {
37            set.deep.insert(sight.served.to_path_buf());
38        }
39        set
40    }
41}
42
43/// What decides whether a folder is in sight.
44struct Sight<'a> {
45    /// The served folder's path: where the walk starts, and what nothing
46    /// outside is in sight of.
47    served: &'a Path,
48    /// The folder whose `.gitignore` rules say what is ignored.
49    folder: &'a Folder,
50    /// Where any site's `watch` list can name a file.
51    roots: Vec<PathBuf>,
52}
53
54impl Sight<'_> {
55    /// Records the watched folders under `folder`, which is in sight, and
56    /// says whether nothing out of sight is anywhere under it — so the
57    /// caller can watch it whole instead.
58    fn walk(&self, folder: &Path, set: &mut WatchSet) -> bool {
59        let Ok(entries) = std::fs::read_dir(folder) else {
60            return true;
61        };
62        // `.devpage` is out of sight itself; only its comment store is watched whole.
63        let mut clean = folder != self.served.join(".devpage");
64        let mut whole = Vec::new();
65        for entry in entries.flatten() {
66            // A symbolic link is not followed, by this walk or by the platform.
67            if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
68                continue;
69            }
70            let child = entry.path();
71            if !self.in_sight(&child) {
72                clean = false;
73            } else if self.walk(&child, set) {
74                whole.push(child);
75            } else {
76                clean = false;
77            }
78        }
79        if !clean {
80            set.shallow.insert(folder.to_path_buf());
81            set.deep.extend(whole);
82        }
83        clean
84    }
85
86    /// Whether `folder` is watched: in sight by the `.gitignore` rules, or one of
87    /// the two exceptions — `.devpage` and its comment store, and an ignored
88    /// folder a `watch` pattern reaches into: its literal prefix is in the
89    /// folder or is it, or is an ignored folder holding it. A prefix above
90    /// every ignored folder — `**/*.md` — reaches into none.
91    fn in_sight(&self, folder: &Path) -> bool {
92        let Ok(relative) = folder.strip_prefix(self.served) else {
93            return false;
94        };
95        if relative == Path::new(".devpage") || relative.starts_with(".devpage/comments") {
96            return true;
97        }
98        if relative.starts_with(".devpage")
99            || relative.components().any(|part| part.as_os_str() == ".git")
100        {
101            return false;
102        }
103        !self.folder.ignored(folder, true)
104            || self.roots.iter().any(|root| {
105                root.starts_with(folder)
106                    || (folder.starts_with(root) && self.folder.ignored(root, true))
107            })
108    }
109}
110
111/// The literal prefixes of every site's `watch` patterns: the entry's, and
112/// those of every indexed site.
113fn watch_roots(folder: &Folder) -> Vec<PathBuf> {
114    let mut roots = folder.entry().watch_roots().to_vec();
115    for site in folder.sites() {
116        roots.extend_from_slice(site.watch_roots());
117    }
118    roots.extend(crate::extensions::input_roots(folder.served()));
119    roots.extend(crate::code::input_roots(folder.served()));
120    roots
121}
122
123impl Folder {
124    /// Whether a change to `path` can matter to anyone: not under `.git`,
125    /// and either in sight or named by its site's `watch` list. A comment
126    /// thread always matters; nothing else under `.devpage/` does. Decided
127    /// from the path alone — no file system call — so a build rewriting an
128    /// ignored folder costs a lookup per path. A path not under the served
129    /// folder as given is kept, to be judged once canonical.
130    pub fn matters(&self, path: &Path, is_dir: bool) -> bool {
131        let Some(relative) = self.served().relative(path) else {
132            return true;
133        };
134        if relative.starts_with(".devpage/comments") {
135            return true;
136        }
137        if relative.starts_with(".devpage")
138            || relative.components().any(|part| part.as_os_str() == ".git")
139        {
140            return false;
141        }
142        crate::extensions::input_roots(self.served())
143            .iter()
144            .chain(&crate::code::input_roots(self.served()))
145            .any(|r| path.starts_with(r) || r.starts_with(path))
146            || !self.ignored(path, is_dir)
147            || self.named_by_watch(path)
148    }
149
150    /// Whether a change to `path`, which is in sight, refreshes open pages.
151    /// Document files and widget files always do; any other path is judged by
152    /// the `watch` list of its owner, and refreshes when there is no such list.
153    pub(super) fn refreshes(&self, path: &Path) -> bool {
154        if self.kind(path).is_some() || self.is_widget_file(path) {
155            return true;
156        }
157        match self.owning_site(path) {
158            Some(Some(site)) => site.watches(path),
159            // No site holds it, or its site's file is invalid.
160            Some(None) | None => true,
161        }
162    }
163
164    /// Whether the `watch` list of the site owning `path` names it.
165    fn named_by_watch(&self, path: &Path) -> bool {
166        self.owning_site(path)
167            .flatten()
168            .is_some_and(|site| site.names(path))
169    }
170
171    /// The site owning `path` as its `watch` list is judged: `None` when no
172    /// site holds it, `Some(None)` when its site's file is invalid. The
173    /// entry's site is the entry document as last read without error, so
174    /// sifting a path it owns reads no file.
175    fn owning_site(&self, path: &Path) -> Option<Option<Arc<Document>>> {
176        let site = self.index.site_for(path)?;
177        Some(if site == self.entry_file() {
178            Some(self.entry())
179        } else {
180            Document::load(&site, self.served()).ok().map(Arc::new)
181        })
182    }
183
184    /// Whether `path` is a widget or a helper in the widgets folder of some
185    /// document.
186    fn is_widget_file(&self, path: &Path) -> bool {
187        path.parent().is_some_and(|folder| {
188            crate::widgets::is_widget_file(path, folder) && self.widgets_owner(folder).is_some()
189        })
190    }
191
192    /// Every indexed site but the entry, loaded; an invalid one is passed over.
193    fn sites(&self) -> Vec<Document> {
194        self.documents()
195            .into_iter()
196            .filter(|file| file != self.entry_file() && self.kind(file) == Some(KindName::Site))
197            .filter_map(|file| Document::load(&file, self.served()).ok())
198            .collect()
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205    use crate::folder::ServedFolder;
206
207    /// A served folder holding `files` (empty ones, folders made as needed)
208    /// and a site in `docs/` with `site` as its document file.
209    fn served(name: &str, site: &str, files: &[&str]) -> PathBuf {
210        let dir =
211            std::env::temp_dir().join(format!("devpage-watch-set-{name}-{}", std::process::id()));
212        let _ = std::fs::remove_dir_all(&dir);
213        std::fs::create_dir_all(dir.join("docs")).unwrap();
214        std::fs::write(dir.join("docs/README.md"), "# Home").unwrap();
215        std::fs::write(dir.join("docs/devpage.yml"), site).unwrap();
216        for file in files {
217            let path = dir.join(file);
218            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
219            if file.ends_with('/') {
220                std::fs::create_dir_all(&path).unwrap();
221            } else {
222                std::fs::write(&path, "").unwrap();
223            }
224        }
225        dir.canonicalize().unwrap()
226    }
227
228    fn plan(dir: &Path) -> WatchSet {
229        let served = ServedFolder::new(dir).unwrap();
230        let document = Arc::new(Document::load(&dir.join("docs"), &served).unwrap());
231        Folder::new(document).watched()
232    }
233
234    fn set(dir: &Path, deep: &[&str], shallow: &[&str]) -> WatchSet {
235        let join = |folders: &[&str]| folders.iter().map(|f| dir.join(f)).collect();
236        WatchSet {
237            deep: join(deep),
238            shallow: join(shallow),
239        }
240    }
241
242    const SITE: &str = "kind: site\ntitle: T\nroot: README.md\n";
243
244    #[test]
245    fn a_folder_with_nothing_out_of_sight_is_watched_whole() {
246        let dir = served("whole", SITE, &["src/main.rs", "docs/guides/a.md"]);
247        assert_eq!(plan(&dir), set(&dir, &[""], &[]));
248    }
249
250    #[test]
251    fn ignored_folders_and_git_leave_their_parents_shallow() {
252        let dir = served(
253            "repo",
254            SITE,
255            &[
256                ".gitignore",
257                ".git/HEAD",
258                "target/debug/devpage",
259                "src/main.rs",
260                "crate/.gitignore",
261                "crate/src/lib.rs",
262                "crate/target/debug/x",
263                "crate/benches/b.rs",
264            ],
265        );
266        std::fs::write(dir.join(".gitignore"), "/target/\n").unwrap();
267        std::fs::write(dir.join("crate/.gitignore"), "target/\n").unwrap();
268        assert_eq!(
269            plan(&dir),
270            set(
271                &dir,
272                &["docs", "src", "crate/src", "crate/benches"],
273                &["", "crate"]
274            )
275        );
276    }
277
278    #[test]
279    fn the_comment_store_is_watched_and_nothing_else_in_devpage() {
280        let dir = served(
281            "devpage",
282            SITE,
283            &[".devpage/comments/docs/README.md/x.yml", ".devpage/cache/y"],
284        );
285        assert_eq!(
286            plan(&dir),
287            set(&dir, &["docs", ".devpage/comments"], &["", ".devpage"])
288        );
289    }
290
291    #[test]
292    fn an_ignored_folder_a_watch_pattern_reaches_into_is_watched() {
293        let dir = served(
294            "named",
295            "kind: site\ntitle: T\nroot: README.md\nwatch: [\"build/*.svg\"]\n",
296            &[
297                "docs/.gitignore",
298                "docs/build/chart.svg",
299                "docs/build/deep/x",
300                "docs/out/x",
301                ".gitignore",
302                "target/x",
303            ],
304        );
305        std::fs::write(dir.join("docs/.gitignore"), "build/\nout/\n").unwrap();
306        std::fs::write(dir.join(".gitignore"), "/target/\n").unwrap();
307        // `build/` is named; `out/` and `target/` are not.
308        assert_eq!(plan(&dir), set(&dir, &["docs/build"], &["", "docs"]));
309    }
310
311    #[test]
312    fn a_pattern_that_only_matches_into_an_ignored_folder_does_not_watch_it() {
313        let dir = served(
314            "glob",
315            "kind: site\ntitle: T\nroot: README.md\nwatch: [\"**/*.md\"]\n",
316            &[
317                "docs/.gitignore",
318                "docs/build/out.md",
319                "docs/guides/a.md",
320                ".gitignore",
321                "target/x",
322            ],
323        );
324        std::fs::write(dir.join("docs/.gitignore"), "build/\n").unwrap();
325        std::fs::write(dir.join(".gitignore"), "/target/\n").unwrap();
326        // `**/*.md` can match in `docs/build/`, but reaches into no ignored folder.
327        assert_eq!(plan(&dir), set(&dir, &["docs/guides"], &["", "docs"]));
328    }
329
330    #[test]
331    fn a_pattern_reaching_into_an_ignored_folder_watches_the_folders_under_it() {
332        let dir = served(
333            "under",
334            "kind: site\ntitle: T\nroot: README.md\nwatch: [\"build/**/*.svg\"]\n",
335            &["docs/.gitignore", "docs/build/deep/chart.svg"],
336        );
337        std::fs::write(dir.join("docs/.gitignore"), "build/\n").unwrap();
338        assert_eq!(plan(&dir), set(&dir, &[""], &[]));
339    }
340}