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