Skip to main content

devpage_core/comments/
yaml.rs

1//! The comment store as files: one YAML file per thread under
2//! `.devpage/comments/`, by the path of the page it is about. It writes
3//! nothing outside `.devpage/`.
4//!
5//! It also remembers what each thread file held when open pages last heard
6//! of it, so the watcher announces a thread file only when someone other
7//! than this store changed it — a write through the store is announced once,
8//! by [`super::Comments`], and a hand edit once, by the watcher.
9
10use std::collections::HashMap;
11use std::path::{Path, PathBuf};
12use std::sync::Mutex;
13
14use anyhow::{Result, bail};
15
16use super::{Anchor, Listed, Message, Store, Thread, is_id, is_page, new_id, now};
17
18/// Thread files that don't parse, each with its error.
19type Unparsable = Vec<(PathBuf, String)>;
20
21pub struct Yaml {
22    root: PathBuf,
23    /// Each thread file's bytes as open pages last heard of them — `None`
24    /// once it is gone. Held while writing, so the watcher never reads a
25    /// write before it is remembered.
26    heard: Mutex<HashMap<PathBuf, Option<Vec<u8>>>>,
27}
28
29impl Yaml {
30    pub fn new(served: impl AsRef<Path>) -> Self {
31        Self {
32            root: served.as_ref().join(".devpage"),
33            heard: Mutex::default(),
34        }
35    }
36
37    /// The folder holding a page's threads. `page` is a path from the top of
38    /// the served folder; anything climbing out of it is refused.
39    fn folder(&self, page: &str) -> Result<PathBuf> {
40        if !is_page(page) {
41            bail!(
42                "{} is not a page in the served folder",
43                page.trim_start_matches('/')
44            );
45        }
46        Ok(self
47            .root
48            .join("comments")
49            .join(page.trim_start_matches('/')))
50    }
51
52    fn thread_file(&self, page: &str, id: &str) -> Result<PathBuf> {
53        if !is_id(id) {
54            bail!("no thread {id}");
55        }
56        Ok(self.folder(page)?.join(format!("{id}.yml")))
57    }
58
59    /// Creates `.devpage/` with a `.gitignore` that keeps git away from it.
60    fn prepare(&self) -> Result<()> {
61        std::fs::create_dir_all(&self.root)?;
62        let ignore = self.root.join(".gitignore");
63        if !ignore.exists() {
64            std::fs::write(ignore, "*\n")?;
65        }
66        Ok(())
67    }
68
69    /// The page's threads, and the thread files that don't parse with why.
70    fn read(&self, page: &str) -> Result<(Vec<Listed>, Unparsable)> {
71        let Ok(entries) = std::fs::read_dir(self.folder(page)?) else {
72            return Ok(Default::default());
73        };
74        let (mut listed, mut broken) = (Vec::new(), Vec::new());
75        for entry in entries.flatten() {
76            let path = entry.path();
77            if path.extension().is_none_or(|ext| ext != "yml") {
78                continue;
79            }
80            let parsed = std::fs::read_to_string(&path)
81                .map_err(anyhow::Error::from)
82                .and_then(|text| Ok(serde_yaml::from_str::<Thread>(&text)?));
83            match parsed {
84                Ok(thread) => {
85                    let id = path
86                        .file_stem()
87                        .unwrap_or_default()
88                        .to_string_lossy()
89                        .into_owned();
90                    listed.push(Listed {
91                        id,
92                        thread,
93                        detached: false,
94                    });
95                }
96                Err(error) => broken.push((path, format!("{error:#}"))),
97            }
98        }
99        listed.sort_by(|a, b| a.id.cmp(&b.id));
100        broken.sort();
101        Ok((listed, broken))
102    }
103
104    /// Writes `thread` to `file`, remembering it as heard.
105    fn write(&self, file: PathBuf, thread: &Thread) -> Result<()> {
106        let bytes = serde_yaml::to_string(thread)?.into_bytes();
107        let mut heard = self.heard.lock().unwrap_or_else(|p| p.into_inner());
108        std::fs::write(&file, &bytes)?;
109        heard.insert(file, Some(bytes));
110        Ok(())
111    }
112
113    /// Whether open pages have yet to hear of the thread file at `path` as it
114    /// is now — true for a file someone else changed, false for one this
115    /// store just wrote or deleted. Asking marks it heard: whoever asks
116    /// announces it.
117    pub fn unheard(&self, path: &Path) -> bool {
118        let mut heard = self.heard.lock().unwrap_or_else(|p| p.into_inner());
119        let now = std::fs::read(path).ok();
120        if heard.get(path) == Some(&now) {
121            return false;
122        }
123        heard.insert(path.to_path_buf(), now);
124        true
125    }
126}
127
128impl Store for Yaml {
129    /// A thread file that doesn't parse is left out — and left alone;
130    /// [`problems`] names it.
131    fn list(&self, page: &str) -> Result<Vec<Listed>> {
132        Ok(self.read(page)?.0)
133    }
134
135    fn create(&self, page: &str, anchor: Anchor, author: &str, text: &str) -> Result<String> {
136        self.prepare()?;
137        let (id, stamp) = new_id();
138        let file = self.thread_file(page, &id)?;
139        std::fs::create_dir_all(file.parent().unwrap())?;
140        let thread = Thread {
141            anchor,
142            thread: vec![Message {
143                author: author.into(),
144                at: stamp,
145                text: text.into(),
146            }],
147        };
148        self.write(file, &thread)?;
149        Ok(id)
150    }
151
152    fn reply(&self, page: &str, id: &str, author: &str, text: &str) -> Result<()> {
153        let file = self.thread_file(page, id)?;
154        let mut thread: Thread = serde_yaml::from_str(&std::fs::read_to_string(&file)?)?;
155        thread.thread.push(Message {
156            author: author.into(),
157            at: now().0,
158            text: text.into(),
159        });
160        self.write(file, &thread)
161    }
162
163    /// Resolving a thread deletes its file.
164    fn resolve(&self, page: &str, id: &str) -> Result<()> {
165        let file = self.thread_file(page, id)?;
166        let mut heard = self.heard.lock().unwrap_or_else(|p| p.into_inner());
167        std::fs::remove_file(&file)?;
168        heard.insert(file, None);
169        Ok(())
170    }
171}
172
173/// The page's thread files that don't parse, as problems: listed on the page
174/// in the preview and reported by `devpage check`.
175pub fn problems(document: &crate::document::Document, page: &Path) -> Vec<crate::problem::Problem> {
176    let store = Yaml::new(&document.served);
177    // A page names its threads by its path in the served folder, whatever
178    // the folder's mount.
179    let unparsable = store
180        .read(&format!("/{}", document.name(page)))
181        .map(|(_, broken)| broken);
182    unparsable
183        .unwrap_or_default()
184        .into_iter()
185        .map(|(file, error)| crate::problem::Problem {
186            file: document
187                .served
188                .relative(&file)
189                .unwrap_or(&file)
190                .display()
191                .to_string(),
192            line: None,
193            message: format!("comment thread doesn't parse — {error}"),
194            target: None,
195        })
196        .collect()
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202    use std::process::Command;
203
204    fn git(repo: &Path, args: &[&str]) -> String {
205        let output = Command::new("git")
206            .arg("-C")
207            .arg(repo)
208            .args(args)
209            .output()
210            .unwrap();
211        String::from_utf8_lossy(&output.stdout).into_owned()
212    }
213
214    fn anchor() -> Anchor {
215        Anchor {
216            quote: "retries".into(),
217            prefix: "The client ".into(),
218            suffix: ".".into(),
219        }
220    }
221
222    #[test]
223    fn a_thread_lives_and_dies_without_touching_the_repository() {
224        let repo = std::env::temp_dir().join(format!("devpage-comments-{}", std::process::id()));
225        std::fs::create_dir_all(repo.join("docs")).unwrap();
226        std::fs::write(repo.join("docs/a.md"), "# A\n\nThe client retries.\n").unwrap();
227        git(&repo, &["init", "-q"]);
228        git(&repo, &["add", "."]);
229        git(
230            &repo,
231            &[
232                "-c",
233                "user.name=t",
234                "-c",
235                "user.email=t@t",
236                "commit",
237                "-qm",
238                "x",
239            ],
240        );
241
242        let store = Yaml::new(&repo);
243        let id = store
244            .create("/docs/a.md", anchor(), "Ana", "Every write?")
245            .unwrap();
246        store
247            .reply("/docs/a.md", &id, "Bo", "Only the outbox.")
248            .unwrap();
249        let listed = store.list("/docs/a.md").unwrap();
250        assert_eq!(listed.len(), 1);
251        assert_eq!(listed[0].thread.anchor, anchor());
252        assert_eq!(listed[0].thread.thread[1].author, "Bo");
253        assert!(
254            repo.join(format!(".devpage/comments/docs/a.md/{id}.yml"))
255                .is_file()
256        );
257        assert_eq!(
258            git(&repo, &["status", "--porcelain"]),
259            "",
260            "git sees nothing"
261        );
262
263        store.resolve("/docs/a.md", &id).unwrap();
264        assert!(store.list("/docs/a.md").unwrap().is_empty());
265        assert!(store.create("/../x.md", anchor(), "Ana", "no").is_err());
266    }
267
268    #[test]
269    fn a_thread_file_is_the_yaml_it_always_was() {
270        let root = std::env::temp_dir().join(format!("devpage-format-{}", std::process::id()));
271        let _ = std::fs::remove_dir_all(&root);
272        let store = Yaml::new(&root);
273        let id = store
274            .create("/a.md", anchor(), "Ana", "Every write?")
275            .unwrap();
276        store.reply("/a.md", &id, "Bo", "Only the outbox.").unwrap();
277        let file = root.join(format!(".devpage/comments/a.md/{id}.yml"));
278        let text = std::fs::read_to_string(file).unwrap();
279        let at: Vec<&str> = text
280            .lines()
281            .filter_map(|line| line.trim_start_matches("- ").strip_prefix("  at: "))
282            .collect();
283        assert_eq!(
284            text,
285            format!(
286                "anchor:\n  quote: retries\n  prefix: 'The client '\n  suffix: .\nthread:\n\
287                 - author: Ana\n  at: {}\n  text: Every write?\n\
288                 - author: Bo\n  at: {}\n  text: Only the outbox.\n",
289                at[0], at[1]
290            )
291        );
292        assert_eq!(
293            std::fs::read_to_string(root.join(".devpage/.gitignore")).unwrap(),
294            "*\n"
295        );
296    }
297
298    #[test]
299    fn a_thread_file_that_doesnt_parse_is_named_and_left_alone() {
300        let root = std::env::temp_dir().join(format!("devpage-unparsable-{}", std::process::id()));
301        let _ = std::fs::remove_dir_all(&root);
302        let store = Yaml::new(&root);
303        store.create("/a.md", anchor(), "Ana", "fine").unwrap();
304        let bad = root.join(".devpage/comments/a.md/20261025T000000Z-0000.yml");
305        std::fs::write(&bad, "anchor: [not, a, mapping]\n").unwrap();
306        assert_eq!(
307            store.list("/a.md").unwrap().len(),
308            1,
309            "the good thread still lists"
310        );
311        let broken = store.read("/a.md").unwrap().1;
312        assert_eq!(broken.len(), 1);
313        assert_eq!(broken[0].0, bad);
314        assert!(bad.is_file(), "left alone");
315
316        std::fs::write(root.join("a.md"), "# A\n").unwrap();
317        let document = crate::document::Document::load(&root.join("a.md"), &root).unwrap();
318        let found = problems(&document, &document.served.path().join("a.md"));
319        assert_eq!(found.len(), 1);
320        assert_eq!(
321            found[0].file,
322            ".devpage/comments/a.md/20261025T000000Z-0000.yml"
323        );
324        assert!(
325            found[0].message.starts_with("comment thread doesn't parse"),
326            "{}",
327            found[0]
328        );
329    }
330
331    #[test]
332    fn only_a_change_the_store_didnt_make_is_unheard() {
333        let root = std::env::temp_dir().join(format!("devpage-unheard-{}", std::process::id()));
334        let _ = std::fs::remove_dir_all(&root);
335        let store = Yaml::new(&root);
336        let id = store
337            .create("/a.md", anchor(), "Ana", "Every write?")
338            .unwrap();
339        let file = root.join(format!(".devpage/comments/a.md/{id}.yml"));
340        assert!(!store.unheard(&file), "the store's own write");
341        store.reply("/a.md", &id, "Bo", "Only the outbox.").unwrap();
342        assert!(!store.unheard(&file), "the store's own reply");
343
344        // A hand edit is unheard once; asked again, it has been heard.
345        let edited =
346            std::fs::read_to_string(&file).unwrap() + "- author: Cy\n  at: x\n  text: hi\n";
347        std::fs::write(&file, &edited).unwrap();
348        assert!(store.unheard(&file), "a hand edit");
349        assert!(!store.unheard(&file), "the same edit, heard");
350
351        // Editing it back to what the store wrote is a change pages haven't seen.
352        store.reply("/a.md", &id, "Bo", "Again.").unwrap();
353        let written = std::fs::read(&file).unwrap();
354        std::fs::write(&file, &edited).unwrap();
355        assert!(store.unheard(&file));
356        std::fs::write(&file, &written).unwrap();
357        assert!(
358            store.unheard(&file),
359            "back to the store's bytes, after an edit"
360        );
361
362        store.resolve("/a.md", &id).unwrap();
363        assert!(!store.unheard(&file), "the store's own delete");
364        let other = root.join(".devpage/comments/a.md/20261025T000000Z-0000.yml");
365        std::fs::write(&other, "x").unwrap();
366        std::fs::remove_file(&other).unwrap();
367        assert!(store.unheard(&other), "a file the store never touched");
368    }
369}