forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

follow.rs72 lines, 2.8 KiBHistoryRawDownload
1//! Live follow: whether the `.edith` the window has open was written on disk by
2//! someone else (the agent, through `edith_mcp`) since the window last looked.
3//! The decision is a pure function of two stamps and one flag, so it reads and
4//! tests without a window; [`crate::Player`] supplies the three inputs.
5
6use std::path::Path;
7use std::time::SystemTime;
8
9/// A project file as the window last saw it: when it was written and how long
10/// it is. Both must match for a file to count as unchanged.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub(crate) struct Stamp {
13 pub(crate) mtime: SystemTime,
14 pub(crate) len: u64,
15}
16
17/// What the window does about one look at the project file.
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub(crate) enum Follow {
20 /// Nothing settled to read (missing, empty, or mid-write). Change nothing
21 /// and look again on the next tick.
22 Wait,
23 /// The file is the one the window already accounts for.
24 Idle,
25 /// The window had no stamp for this file yet. Take the current one as the
26 /// known state, silently.
27 Adopt,
28 /// Changed on disk and the window holds no unsaved edits: reload in place.
29 Reload,
30 /// Changed on disk under unsaved edits: ask once, and keep the question
31 /// away from the window until the file changes again.
32 Ask,
33}
34
35/// The whole rule. `known` is the stamp the window last accounted for (set on
36/// open, on its own save, and when a change has been answered). `now` is the
37/// file as it stands. `edited` says the window holds edits the file does not.
38///
39/// The window's own save needs no case here: [`crate::Player::save_project`]
40/// records the stamp it just wrote as `known`, so its own write reads as `Idle`.
41pub(crate) fn follow_decision(known: Option<Stamp>, now: Option<Stamp>, edited: bool) -> Follow {
42 match (known, now) {
43 (_, None) => Follow::Wait,
44 (None, Some(_)) => Follow::Adopt,
45 (Some(known), Some(now)) if known == now => Follow::Idle,
46 (Some(_), Some(_)) if edited => Follow::Ask,
47 (Some(_), Some(_)) => Follow::Reload,
48 }
49}
50
51/// The stamp of `path` as it stands, or `None` when there is nothing settled to
52/// read: no path, no file, a zero-length file, or a `<path>.part` beside it. The
53/// engine writes `<path>.part` and renames it over `path`, so the file is only
54/// final once that sibling is gone.
55pub(crate) fn stamp(path: &Path) -> Option<Stamp> {
56 if path.as_os_str().is_empty() {
57 return None;
58 }
59 let mut part = path.as_os_str().to_owned();
60 part.push(".part");
61 if Path::new(&part).exists() {
62 return None;
63 }
64 let meta = std::fs::metadata(path).ok()?;
65 if meta.len() == 0 {
66 return None;
67 }
68 Some(Stamp {
69 mtime: meta.modified().ok()?,
70 len: meta.len(),
71 })
72}