Skip to main content

docgen_bases/
note.rs

1//! The corpus: the set of notes a base queries over. Each [`Note`] carries its
2//! frontmatter properties (as typed [`Value`]s) plus file metadata (`file.*`).
3//! The caller (docgen-build / docgen-core) constructs these from discovered docs;
4//! this crate stays free of any filesystem or docgen-specific types.
5
6use std::collections::BTreeMap;
7
8use crate::value::{BaseDate, BaseLink, Value};
9
10/// One note (markdown file) in the vault, queryable by a base.
11#[derive(Debug, Clone, Default)]
12pub struct Note {
13    /// Frontmatter properties, keyed by name, coerced to typed values. Accessed
14    /// via `note.<name>` or a bare `<name>` in expressions.
15    pub properties: BTreeMap<String, Value>,
16    // --- file.* metadata ---
17    /// `file.name` — filename with extension (e.g. `Intro.md`).
18    pub name: String,
19    /// `file.basename` — filename without extension.
20    pub basename: String,
21    /// `file.path` — full vault-relative path (e.g. `guide/Intro.md`).
22    pub path: String,
23    /// `file.folder` — containing folder path (empty for root).
24    pub folder: String,
25    /// `file.ext` — extension without the dot (`md`).
26    pub ext: String,
27    /// `file.size` — byte length of the source file.
28    pub size: u64,
29    /// `file.ctime` — creation time, if known.
30    pub ctime: Option<BaseDate>,
31    /// `file.mtime` — modification time, if known.
32    pub mtime: Option<BaseDate>,
33    /// `file.tags` — all `#tags` (frontmatter + body), without the leading `#`.
34    pub tags: Vec<String>,
35    /// `file.links` — outbound internal link targets.
36    pub links: Vec<BaseLink>,
37    /// The doc's site slug (docgen-specific; used to build the cell hyperlink to
38    /// the rendered page). Not exposed as a base property.
39    pub slug: String,
40}
41
42impl Note {
43    /// Resolve a `file.<field>` access to a value. Unknown fields → `Null`.
44    pub fn file_property(&self, field: &str) -> Value {
45        match field {
46            "name" => Value::Str(self.name.clone()),
47            "basename" => Value::Str(self.basename.clone()),
48            "path" => Value::Str(self.path.clone()),
49            "folder" => Value::Str(self.folder.clone()),
50            "ext" => Value::Str(self.ext.clone()),
51            "size" => Value::Number(self.size as f64),
52            "ctime" => self.ctime.map(Value::Date).unwrap_or(Value::Null),
53            "mtime" => self.mtime.map(Value::Date).unwrap_or(Value::Null),
54            "tags" => Value::List(self.tags.iter().cloned().map(Value::Str).collect()),
55            "links" => Value::List(self.links.iter().cloned().map(Value::Link).collect()),
56            // `file.file` / `file.properties` reflect the note itself.
57            "properties" => Value::Object(self.properties.clone()),
58            _ => Value::Null,
59        }
60    }
61
62    /// Resolve a bare/`note.` property. Unknown → `Null`.
63    pub fn note_property(&self, name: &str) -> Value {
64        self.properties.get(name).cloned().unwrap_or(Value::Null)
65    }
66
67    /// Whether this note has any of `tags` (Obsidian's `file.hasTag` matches a tag
68    /// or any of its parents: a note tagged `#a/b` matches `hasTag("a")`).
69    pub fn has_tag(&self, want: &str) -> bool {
70        let want = want.trim_start_matches('#');
71        self.tags
72            .iter()
73            .any(|t| t == want || t.starts_with(&format!("{want}/")))
74    }
75
76    /// Whether this note lives in `folder` or any subfolder of it.
77    pub fn in_folder(&self, folder: &str) -> bool {
78        let folder = folder.trim_matches('/');
79        if folder.is_empty() {
80            return true;
81        }
82        self.folder == folder || self.folder.starts_with(&format!("{folder}/"))
83    }
84
85    /// Whether this note links to `target` (by basename/path).
86    pub fn has_link(&self, target: &BaseLink) -> bool {
87        self.links.iter().any(|l| l.same_target(target))
88    }
89}
90
91/// The whole set of notes a base evaluates against.
92#[derive(Debug, Clone, Default)]
93pub struct Corpus {
94    pub notes: Vec<Note>,
95}
96
97impl Corpus {
98    pub fn new(notes: Vec<Note>) -> Self {
99        Self { notes }
100    }
101
102    /// Notes that link to `target` — backs `file.backlinks` / `linksTo`.
103    pub fn backlinks_to(&self, target: &BaseLink) -> Vec<&Note> {
104        self.notes.iter().filter(|n| n.has_link(target)).collect()
105    }
106}
107
108/// Convert a parsed YAML frontmatter mapping (`serde_yml::Value`) into typed base
109/// properties. Strings that look like `[[wikilinks]]` become [`Value::Link`];
110/// `YYYY-MM-DD[ HH:mm[:ss]]` strings become [`Value::Date`]; sequences become
111/// lists; nested maps become objects. This is the bridge from docgen's
112/// frontmatter to the base value model.
113pub fn properties_from_yaml(fm: &serde_yml::Value) -> BTreeMap<String, Value> {
114    let mut out = BTreeMap::new();
115    if let serde_yml::Value::Mapping(map) = fm {
116        // serde_yml (noyalib shim) mappings are String-keyed.
117        for (k, v) in map {
118            out.insert(k.to_string(), value_from_yaml(v));
119        }
120    }
121    out
122}
123
124/// Convert a single YAML node into a base [`Value`], inferring dates and links
125/// from string scalars.
126pub fn value_from_yaml(v: &serde_yml::Value) -> Value {
127    match v {
128        serde_yml::Value::Null => Value::Null,
129        serde_yml::Value::Bool(b) => Value::Bool(*b),
130        serde_yml::Value::Number(_) => v.as_f64().map(Value::Number).unwrap_or(Value::Null),
131        serde_yml::Value::String(s) => scalar_string_to_value(s),
132        serde_yml::Value::Sequence(items) => {
133            Value::List(items.iter().map(value_from_yaml).collect())
134        }
135        serde_yml::Value::Mapping(map) => {
136            let mut obj = BTreeMap::new();
137            for (k, val) in map {
138                obj.insert(k.to_string(), value_from_yaml(val));
139            }
140            Value::Object(obj)
141        }
142        // Tagged scalars (e.g. `!Custom foo`): treat as their string form.
143        other => other
144            .as_str()
145            .map(scalar_string_to_value)
146            .unwrap_or(Value::Null),
147    }
148}
149
150/// Infer a value from a YAML string scalar: `[[wikilink]]`/`[[a|b]]` → link,
151/// ISO-ish date → date, otherwise a plain string.
152pub fn scalar_string_to_value(s: &str) -> Value {
153    let trimmed = s.trim();
154    if let Some(link) = parse_wikilink(trimmed) {
155        return Value::Link(link);
156    }
157    if let Some(date) = parse_date(trimmed) {
158        return Value::Date(date);
159    }
160    Value::Str(s.to_string())
161}
162
163/// Parse a `[[target]]` or `[[target|display]]` wikilink string. Returns `None`
164/// if the string isn't a single wikilink.
165pub fn parse_wikilink(s: &str) -> Option<BaseLink> {
166    let inner = s.strip_prefix("[[")?.strip_suffix("]]")?;
167    if inner.contains("[[") {
168        return None; // not a single link
169    }
170    let (target, display) = match inner.split_once('|') {
171        Some((t, d)) => (t.trim(), Some(d.trim().to_string())),
172        None => (inner.trim(), None),
173    };
174    // Drop any `#heading` / `^block` anchor from the target.
175    let target = target.split(['#', '^']).next().unwrap_or(target).trim();
176    let target = target.strip_suffix(".md").unwrap_or(target);
177    Some(BaseLink {
178        path: target.to_string(),
179        display,
180    })
181}
182
183/// Parse a `YYYY-MM-DD`, `YYYY-MM-DDTHH:mm[:ss]`, or `YYYY-MM-DD HH:mm[:ss]`
184/// string into a [`BaseDate`]. Lenient but strict enough not to swallow arbitrary
185/// hyphenated text. Returns `None` when the shape doesn't match.
186pub fn parse_date(s: &str) -> Option<BaseDate> {
187    let s = s.trim();
188    let (date_part, time_part) = match s.split_once(['T', ' ']) {
189        Some((d, t)) => (d, Some(t)),
190        None => (s, None),
191    };
192    let mut dp = date_part.split('-');
193    let year: i64 = dp.next()?.parse().ok()?;
194    let month: u32 = dp.next()?.parse().ok()?;
195    let day: u32 = dp.next()?.parse().ok()?;
196    if dp.next().is_some() || !(1..=12).contains(&month) {
197        return None;
198    }
199    // Reject impossible calendar dates (e.g. Feb 30, Apr 31): validate the day
200    // against the month's actual length so `epoch_millis` never aliases an
201    // out-of-range day onto a different real date.
202    if day < 1 || day > days_in_month(year, month) {
203        return None;
204    }
205    // A plausible year band guards against matching things like `12-34-56` ids.
206    if !(1000..=9999).contains(&year) {
207        return None;
208    }
209    let (mut hour, mut minute, mut second, mut millisecond, has_time) =
210        (0u32, 0u32, 0u32, 0u32, time_part.is_some());
211    if let Some(t) = time_part {
212        // Strip a trailing timezone (`Z` or `±hh:mm`) — dates are treated as naive.
213        // A time never contains `+`/`-` itself, so splitting on them isolates the
214        // clock portion for both positive and negative offsets.
215        let t = t.trim().trim_end_matches('Z');
216        let t = t.split(['+', '-']).next().unwrap_or(t);
217        let mut tp = t.split(':');
218        hour = tp.next()?.trim().parse().ok()?;
219        minute = tp.next().unwrap_or("0").parse().ok()?;
220        // Seconds may carry a fractional part (`ss.SSS`); split it into millis.
221        let sec_field = tp.next().unwrap_or("0");
222        let (sec_str, ms) = match sec_field.split_once('.') {
223            Some((s, frac)) => {
224                // Take up to 3 fractional digits, right-padded, as milliseconds.
225                let mut f = frac.chars().take(3).collect::<String>();
226                while f.len() < 3 {
227                    f.push('0');
228                }
229                (s, f.parse::<u32>().ok()?)
230            }
231            None => (sec_field, 0),
232        };
233        second = sec_str.parse().ok()?;
234        millisecond = ms;
235        if hour > 23 || minute > 59 || second > 59 {
236            return None;
237        }
238    }
239    Some(BaseDate {
240        year,
241        month,
242        day,
243        hour,
244        minute,
245        second,
246        millisecond,
247        has_time,
248    })
249}
250
251/// Days in `month` (1-12) of `year`, accounting for leap years (proleptic
252/// Gregorian).
253fn days_in_month(year: i64, month: u32) -> u32 {
254    match month {
255        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
256        4 | 6 | 9 | 11 => 30,
257        2 => {
258            let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
259            if leap {
260                29
261            } else {
262                28
263            }
264        }
265        _ => 0,
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272
273    #[test]
274    fn wikilink_parsing() {
275        let l = parse_wikilink("[[Books]]").unwrap();
276        assert_eq!(l.path, "Books");
277        assert_eq!(l.display, None);
278        let l2 = parse_wikilink("[[Categories/Books|Books]]").unwrap();
279        assert_eq!(l2.path, "Categories/Books");
280        assert_eq!(l2.display.as_deref(), Some("Books"));
281        assert!(parse_wikilink("not a link").is_none());
282        // Anchor stripped.
283        assert_eq!(parse_wikilink("[[Note#Heading]]").unwrap().path, "Note");
284    }
285
286    #[test]
287    fn date_parsing() {
288        let d = parse_date("2024-01-02").unwrap();
289        assert_eq!((d.year, d.month, d.day), (2024, 1, 2));
290        assert!(!d.has_time);
291        let dt = parse_date("2024-01-02 15:04:05").unwrap();
292        assert_eq!((dt.hour, dt.minute, dt.second), (15, 4, 5));
293        assert!(dt.has_time);
294        let iso = parse_date("2024-01-02T15:04").unwrap();
295        assert_eq!((iso.hour, iso.minute), (15, 4));
296        // Non-dates.
297        assert!(parse_date("hello").is_none());
298        assert!(parse_date("12-34-56").is_none());
299        assert!(parse_date("2024-13-01").is_none());
300    }
301
302    #[test]
303    fn parse_date_handles_timezones_and_fractions() {
304        // Negative offset (Western timezone) must parse, not degrade to a string.
305        let d = parse_date("2024-01-02T15:04:05-05:00").unwrap();
306        assert_eq!((d.hour, d.minute, d.second), (15, 4, 5));
307        // Positive offset and Z too.
308        assert!(parse_date("2024-01-02T15:04:05+05:30").is_some());
309        assert!(parse_date("2024-01-02T15:04:05Z").is_some());
310        // Fractional seconds → milliseconds.
311        let f = parse_date("2024-01-02T15:04:05.123").unwrap();
312        assert_eq!(f.millisecond, 123);
313        assert_eq!(f.second, 5);
314    }
315
316    #[test]
317    fn parse_date_rejects_impossible_calendar_dates() {
318        assert!(parse_date("2024-02-30").is_none()); // Feb never has 30
319        assert!(parse_date("2023-02-29").is_none()); // 2023 not a leap year
320        assert!(parse_date("2024-02-29").is_some()); // 2024 is a leap year
321        assert!(parse_date("2024-04-31").is_none()); // April has 30 days
322        assert!(parse_date("2024-04-30").is_some());
323    }
324
325    #[test]
326    fn yaml_to_values_infers_types() {
327        let fm: serde_yml::Value = serde_yml::from_str(
328            "title: Hello\ncount: 3\ndone: true\ncats:\n  - \"[[Categories/Books|Books]]\"\ncreated: 2024-05-06\n",
329        )
330        .unwrap();
331        let props = properties_from_yaml(&fm);
332        assert!(matches!(props.get("title"), Some(Value::Str(s)) if s == "Hello"));
333        assert!(matches!(props.get("count"), Some(Value::Number(n)) if *n == 3.0));
334        assert!(matches!(props.get("done"), Some(Value::Bool(true))));
335        match props.get("cats") {
336            Some(Value::List(items)) => {
337                assert!(matches!(&items[0], Value::Link(l) if l.path == "Categories/Books"));
338            }
339            other => panic!("expected list, got {other:?}"),
340        }
341        // A bare YAML date scalar is parsed by serde_yml as a string here.
342        assert!(matches!(props.get("created"), Some(Value::Date(_))));
343    }
344
345    #[test]
346    fn has_tag_matches_parents() {
347        let mut n = Note::default();
348        n.tags = vec!["project/active".into()];
349        assert!(n.has_tag("project"));
350        assert!(n.has_tag("project/active"));
351        assert!(n.has_tag("#project"));
352        assert!(!n.has_tag("proj"));
353    }
354
355    #[test]
356    fn in_folder_matches_subfolders() {
357        let mut n = Note::default();
358        n.folder = "Home/Things".into();
359        assert!(n.in_folder("Home"));
360        assert!(n.in_folder("Home/Things"));
361        assert!(!n.in_folder("Misc"));
362        assert!(n.in_folder("")); // vault root matches all
363    }
364}