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