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