Skip to main content

ito_core/
front_matter.rs

1//! YAML front matter parsing, writing, and metadata utilities.
2//!
3//! Ito module and change markdown artifacts support an optional YAML front
4//! matter header delimited by `---` lines at the beginning of the file.
5//!
6//! Front matter stores stable metadata (timestamps, identifiers, integrity
7//! checksums) that is independent of filesystem attributes and survives
8//! copies across hosts.
9
10use chrono::{DateTime, Utc};
11use serde::{Deserialize, Serialize};
12use sha2::{Digest, Sha256};
13use std::collections::BTreeMap;
14
15use crate::errors::CoreError;
16
17/// Parsed YAML front matter metadata for an Ito artifact.
18///
19/// Timestamps are stored as RFC 3339 strings to avoid requiring the `serde`
20/// feature on `chrono`. Use [`FrontMatter::created_at_dt`] and
21/// [`FrontMatter::updated_at_dt`] to parse them into `DateTime<Utc>`.
22#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
23pub struct FrontMatter {
24    /// Schema version for forward compatibility.
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub schema_version: Option<String>,
27
28    /// When the artifact was first created (RFC 3339 UTC string).
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub created_at: Option<String>,
31
32    /// When the artifact was last updated (RFC 3339 UTC string).
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub updated_at: Option<String>,
35
36    /// Identity of the creator (optional).
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub created_by: Option<String>,
39
40    /// Identity of the last updater (optional).
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub updated_by: Option<String>,
43
44    /// Change identifier for integrity validation.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub change_id: Option<String>,
47
48    /// Module identifier for integrity validation.
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub module_id: Option<String>,
51
52    /// Integrity metadata for corruption detection.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub integrity: Option<IntegrityMetadata>,
55
56    /// Additional fields not captured by the typed struct.
57    #[serde(flatten, default)]
58    pub extra: BTreeMap<String, serde_yaml::Value>,
59}
60
61impl FrontMatter {
62    /// Parse `created_at` into a `DateTime<Utc>`, if present and valid.
63    pub fn created_at_dt(&self) -> Option<DateTime<Utc>> {
64        self.created_at
65            .as_deref()
66            .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
67            .map(|dt| dt.with_timezone(&Utc))
68    }
69
70    /// Parse `updated_at` into a `DateTime<Utc>`, if present and valid.
71    pub fn updated_at_dt(&self) -> Option<DateTime<Utc>> {
72        self.updated_at
73            .as_deref()
74            .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
75            .map(|dt| dt.with_timezone(&Utc))
76    }
77}
78
79/// Integrity metadata for checksum-based corruption detection.
80#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
81pub struct IntegrityMetadata {
82    /// SHA-256 hex digest of the markdown body (content after front matter).
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub body_sha256: Option<String>,
85}
86
87/// Result of parsing front matter from a markdown document.
88#[derive(Debug, Clone, PartialEq)]
89pub struct ParsedDocument {
90    /// Parsed front matter, if present.
91    pub front_matter: Option<FrontMatter>,
92    /// Markdown body (everything after the closing `---`).
93    pub body: String,
94}
95
96/// Front matter delimiter.
97const DELIMITER: &str = "---";
98
99/// Parse a markdown document that may start with YAML front matter.
100///
101/// Front matter is delimited by `---` on a line by itself at the start
102/// of the document. The opening `---` must be the very first line.
103/// The closing `---` terminates the YAML block.
104///
105/// Returns the parsed metadata (if present) and the remaining markdown body.
106pub fn parse(content: &str) -> Result<ParsedDocument, CoreError> {
107    let Some(rest) = content.strip_prefix(DELIMITER) else {
108        return Ok(ParsedDocument {
109            front_matter: None,
110            body: content.to_string(),
111        });
112    };
113
114    // The delimiter must be followed by a newline (or be the entire first line)
115    let Some(rest) = rest
116        .strip_prefix('\n')
117        .or_else(|| rest.strip_prefix("\r\n"))
118    else {
119        // The line has content after `---`, so this is not front matter
120        return Ok(ParsedDocument {
121            front_matter: None,
122            body: content.to_string(),
123        });
124    };
125
126    // Find the closing delimiter
127    let Some(end_pos) = find_closing_delimiter(rest) else {
128        // No closing delimiter found — treat entire content as body
129        return Ok(ParsedDocument {
130            front_matter: None,
131            body: content.to_string(),
132        });
133    };
134
135    let yaml_block = &rest[..end_pos];
136    let body_start = end_pos + DELIMITER.len();
137    let remaining = &rest[body_start..];
138
139    // Strip exactly one leading newline from the body
140    let body = remaining
141        .strip_prefix('\n')
142        .or_else(|| remaining.strip_prefix("\r\n"))
143        .unwrap_or(remaining);
144
145    let front_matter: FrontMatter = serde_yaml::from_str(yaml_block)
146        .map_err(|e| CoreError::Parse(format!("invalid YAML front matter: {e}")))?;
147
148    Ok(ParsedDocument {
149        front_matter: Some(front_matter),
150        body: body.to_string(),
151    })
152}
153
154/// Find the position of the closing `---` delimiter in the remaining text.
155///
156/// The closing delimiter must appear on a line by itself (possibly with
157/// trailing whitespace).
158fn find_closing_delimiter(text: &str) -> Option<usize> {
159    let mut pos = 0;
160    for line in text.lines() {
161        if line.trim() == DELIMITER {
162            return Some(pos);
163        }
164        // Advance past this line plus its newline
165        pos += line.len();
166        // Account for the newline character(s)
167        if text[pos..].starts_with("\r\n") {
168            pos += 2;
169        } else if text[pos..].starts_with('\n') {
170            pos += 1;
171        }
172    }
173    None
174}
175
176/// Serialize front matter and body back into a markdown document with
177/// YAML front matter.
178///
179/// If `front_matter` is `None`, the body is returned as-is.
180pub fn write(front_matter: Option<&FrontMatter>, body: &str) -> Result<String, CoreError> {
181    let Some(fm) = front_matter else {
182        return Ok(body.to_string());
183    };
184
185    let yaml = serde_yaml::to_string(fm)
186        .map_err(|e| CoreError::Parse(format!("failed to serialize front matter: {e}")))?;
187
188    // serde_yaml adds a trailing newline; remove it so we control formatting
189    let yaml = yaml.trim_end();
190
191    Ok(format!("{DELIMITER}\n{yaml}\n{DELIMITER}\n{body}"))
192}
193
194/// Format a `DateTime<Utc>` as an RFC 3339 string for front matter.
195fn format_timestamp(dt: DateTime<Utc>) -> String {
196    dt.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
197}
198
199/// Update the `updated_at` timestamp in front matter to the current time.
200///
201/// If `front_matter` is `None`, creates a new `FrontMatter` with only
202/// `created_at` and `updated_at` set to `now`.
203pub fn touch(front_matter: Option<FrontMatter>, now: DateTime<Utc>) -> FrontMatter {
204    let ts = format_timestamp(now);
205    match front_matter {
206        Some(mut fm) => {
207            fm.updated_at = Some(ts);
208            fm
209        }
210        None => FrontMatter {
211            schema_version: Some("1".to_string()),
212            created_at: Some(ts.clone()),
213            updated_at: Some(ts),
214            created_by: None,
215            updated_by: None,
216            change_id: None,
217            module_id: None,
218            integrity: None,
219            extra: BTreeMap::new(),
220        },
221    }
222}
223
224/// Compute the SHA-256 hex digest of a body string.
225pub fn body_sha256(body: &str) -> String {
226    let mut hasher = Sha256::new();
227    hasher.update(body.as_bytes());
228    hex::encode(hasher.finalize())
229}
230
231/// Update the integrity checksum in front matter to match the given body.
232pub fn update_integrity(front_matter: &mut FrontMatter, body: &str) {
233    let checksum = body_sha256(body);
234    match &mut front_matter.integrity {
235        Some(integrity) => {
236            integrity.body_sha256 = Some(checksum);
237        }
238        None => {
239            front_matter.integrity = Some(IntegrityMetadata {
240                body_sha256: Some(checksum),
241            });
242        }
243    }
244}
245
246/// Validate that a front matter checksum matches the body content.
247///
248/// Returns `Ok(())` if there is no checksum or the checksum matches.
249/// Returns `Err` if the checksum is present but does not match.
250pub fn validate_integrity(front_matter: &FrontMatter, body: &str) -> Result<(), CoreError> {
251    let Some(integrity) = &front_matter.integrity else {
252        return Ok(());
253    };
254
255    let Some(expected) = &integrity.body_sha256 else {
256        return Ok(());
257    };
258
259    let actual = body_sha256(body);
260    if *expected != actual {
261        return Err(CoreError::Validation(format!(
262            "artifact body checksum mismatch: expected {expected}, got {actual}"
263        )));
264    }
265
266    Ok(())
267}
268
269/// Validate that a front matter identifier matches the expected value.
270///
271/// Returns `Ok(())` if the front matter field is `None` (absent).
272/// Returns `Err` if the field is present and does not match.
273pub fn validate_id(
274    field_name: &str,
275    front_matter_value: Option<&str>,
276    expected: &str,
277) -> Result<(), CoreError> {
278    let Some(actual) = front_matter_value else {
279        return Ok(());
280    };
281
282    if actual != expected {
283        return Err(CoreError::Validation(format!(
284            "{field_name} mismatch in front matter: expected '{expected}', found '{actual}'"
285        )));
286    }
287
288    Ok(())
289}
290
291#[cfg(test)]
292#[path = "front_matter_tests.rs"]
293mod front_matter_tests;