Skip to main content

devpage_core/folder/
mod.rs

1//! The served folder and what is in it: the boundary every path and URL is
2//! judged against, its document files by kind, its `.gitignore` rules, the
3//! entry document devpage was started with, which document owns a page or a
4//! widgets folder, and what a change to its files means — for open pages and
5//! for the folders to watch. Documents are loaded per call: the folder keeps
6//! the document index and the entry, and no other Document.
7
8mod index;
9mod served;
10mod sight;
11#[cfg(test)]
12mod tests;
13
14use std::path::{Path, PathBuf};
15use std::sync::{Arc, RwLock};
16
17use anyhow::Result;
18
19use crate::changes::Change;
20use crate::document::{Document, KindName};
21use index::Index;
22
23pub use served::ServedFolder;
24pub(crate) use served::lexical;
25pub use sight::WatchSet;
26
27/// A served folder opened on its entry document.
28pub struct Folder {
29    index: Index,
30    entry: Entry,
31}
32
33/// The document that owns a page: the nearest site whose folder holds it,
34/// as its file reads now — or why it can't be read.
35pub struct Owner {
36    /// The site's document file.
37    pub file: PathBuf,
38    pub document: Result<Document>,
39}
40
41/// What a burst of changed files means, once the folder has heard of them.
42#[derive(Debug, Default, PartialEq)]
43pub struct Changed {
44    /// What open pages should hear: at most one [`Change::Refresh`].
45    pub changes: Vec<Change>,
46    /// Whether the folders to watch may differ now — a `.gitignore`, the
47    /// entry's file or a site's document file changed, or a document file
48    /// went away — so [`Folder::watched`] should be asked again.
49    pub reshaped: bool,
50}
51
52impl Folder {
53    /// The served folder `entry` was loaded from, indexed, with `entry` as
54    /// its entry document.
55    pub fn new(entry: Arc<Document>) -> Self {
56        Self {
57            index: Index::build(&entry.served),
58            entry: Entry::new(entry),
59        }
60    }
61
62    /// The served folder.
63    pub fn served(&self) -> &ServedFolder {
64        self.index.served()
65    }
66
67    /// The entry document as last read without error.
68    pub fn entry(&self) -> Arc<Document> {
69        self.entry.document()
70    }
71
72    /// Why the entry's file can't be read as a document, if it can't now.
73    pub fn entry_error(&self) -> Option<String> {
74        self.entry.error()
75    }
76
77    /// The entry's file: a document file, or a Markdown file served as a doc.
78    pub fn entry_file(&self) -> &Path {
79        &self.entry.file
80    }
81
82    /// The document file of the nearest site whose folder holds `page`,
83    /// unloaded; `None` when no site does.
84    pub fn site(&self, page: &Path) -> Option<PathBuf> {
85        self.index.site_for(page)
86    }
87
88    /// The nearest site whose folder holds `page`, loaded now; `None` when
89    /// no site does.
90    pub fn owner(&self, page: &Path) -> Option<Owner> {
91        let file = self.site(page)?;
92        let document = Document::load(&file, self.served());
93        Some(Owner { file, document })
94    }
95
96    /// The document whose widgets folder is `folder`: the entry document
97    /// when it names it, or else the first indexed document that does.
98    pub fn widgets_owner(&self, folder: &Path) -> Option<Arc<Document>> {
99        let entry = self.entry();
100        if entry.widgets.as_deref() == Some(folder) {
101            return Some(entry);
102        }
103        self.documents()
104            .into_iter()
105            .filter_map(|file| Document::load(&file, self.served()).ok())
106            .find(|document| document.widgets.as_deref() == Some(folder))
107            .map(Arc::new)
108    }
109
110    /// The folders to watch, so that nothing out of sight is.
111    pub fn watched(&self) -> WatchSet {
112        WatchSet::plan(self)
113    }
114
115    /// `paths` — canonical, or as reported when gone — changed, appeared or
116    /// vanished: the index and the entry follow them, and what that means
117    /// comes back. A path outside the folder or under `.devpage/` is not the
118    /// folder's. The entry's own file refreshes open pages whatever `watch`
119    /// says; any other path in sight refreshes them as its site's `watch`
120    /// list decides.
121    pub fn changed(&self, paths: &[PathBuf]) -> Changed {
122        let mut refresh = false;
123        let mut reshaped = false;
124        for path in paths {
125            let Some(relative) = self.served().relative(path) else {
126                continue;
127            };
128            if relative.starts_with(".devpage") {
129                continue;
130            }
131            let was_site = self.kind(path) == Some(KindName::Site);
132            self.index.changed(path);
133            let document_file = path
134                .extension()
135                .is_some_and(|ext| ext == "yml" || ext == "yaml");
136            reshaped |= path.file_name().is_some_and(|name| name == ".gitignore")
137                || path == self.entry_file()
138                || was_site
139                || self.kind(path) == Some(KindName::Site)
140                || (document_file && !path.exists());
141            if path == self.entry_file() {
142                self.entry.reload(self.served());
143                refresh = true;
144            } else if !self.ignored(path, path.is_dir()) && self.refreshes(path) {
145                refresh = true;
146            }
147        }
148        Changed {
149            changes: if refresh {
150                vec![Change::Refresh]
151            } else {
152                Vec::new()
153            },
154            reshaped,
155        }
156    }
157
158    /// Whether `path` is out of sight: inside `.git` or `.devpage`, or
159    /// excluded by a `.gitignore` in the served folder.
160    pub(crate) fn ignored(&self, path: &Path, is_dir: bool) -> bool {
161        self.index.ignored(path, is_dir)
162    }
163
164    /// The kind of an indexed document file.
165    fn kind(&self, file: &Path) -> Option<KindName> {
166        self.index.kind(file)
167    }
168
169    /// Every indexed document file.
170    fn documents(&self) -> Vec<PathBuf> {
171        self.index.documents()
172    }
173}
174
175/// The document devpage was started with, re-read whenever its file changes,
176/// so `/` and the watcher follow the file without a restart. While the file
177/// is invalid, the last valid document stays in use and the error is kept to
178/// show in its place.
179struct Entry {
180    file: PathBuf,
181    state: RwLock<(Arc<Document>, Option<String>)>,
182}
183
184impl Entry {
185    fn new(document: Arc<Document>) -> Self {
186        Self {
187            file: document.path(),
188            state: RwLock::new((document, None)),
189        }
190    }
191
192    fn document(&self) -> Arc<Document> {
193        self.read().0.clone()
194    }
195
196    fn error(&self) -> Option<String> {
197        self.read().1.clone()
198    }
199
200    /// Reads the entry's file again: a valid file replaces the document, an
201    /// invalid one keeps it and records the error.
202    fn reload(&self, served: &ServedFolder) {
203        let loaded = Document::load(&self.file, served);
204        let mut state = self
205            .state
206            .write()
207            .unwrap_or_else(|poisoned| poisoned.into_inner());
208        match loaded {
209            Ok(document) => *state = (Arc::new(document), None),
210            Err(error) => state.1 = Some(format!("{error:#}")),
211        }
212    }
213
214    fn read(&self) -> std::sync::RwLockReadGuard<'_, (Arc<Document>, Option<String>)> {
215        self.state
216            .read()
217            .unwrap_or_else(|poisoned| poisoned.into_inner())
218    }
219}