1use chrono::{DateTime, Utc};
11use serde::{Deserialize, Serialize};
12use sha2::{Digest, Sha256};
13use std::collections::BTreeMap;
14
15use crate::errors::CoreError;
16
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
23pub struct FrontMatter {
24 #[serde(default, skip_serializing_if = "Option::is_none")]
26 pub schema_version: Option<String>,
27
28 #[serde(default, skip_serializing_if = "Option::is_none")]
30 pub created_at: Option<String>,
31
32 #[serde(default, skip_serializing_if = "Option::is_none")]
34 pub updated_at: Option<String>,
35
36 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub created_by: Option<String>,
39
40 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub updated_by: Option<String>,
43
44 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub change_id: Option<String>,
47
48 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub module_id: Option<String>,
51
52 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub integrity: Option<IntegrityMetadata>,
55
56 #[serde(flatten, default)]
58 pub extra: BTreeMap<String, serde_yaml::Value>,
59}
60
61impl FrontMatter {
62 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 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#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
81pub struct IntegrityMetadata {
82 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub body_sha256: Option<String>,
85}
86
87#[derive(Debug, Clone, PartialEq)]
89pub struct ParsedDocument {
90 pub front_matter: Option<FrontMatter>,
92 pub body: String,
94}
95
96const DELIMITER: &str = "---";
98
99pub 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 let Some(rest) = rest
116 .strip_prefix('\n')
117 .or_else(|| rest.strip_prefix("\r\n"))
118 else {
119 return Ok(ParsedDocument {
121 front_matter: None,
122 body: content.to_string(),
123 });
124 };
125
126 let Some(end_pos) = find_closing_delimiter(rest) else {
128 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 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
154fn 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 pos += line.len();
166 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
176pub 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 let yaml = yaml.trim_end();
190
191 Ok(format!("{DELIMITER}\n{yaml}\n{DELIMITER}\n{body}"))
192}
193
194fn format_timestamp(dt: DateTime<Utc>) -> String {
196 dt.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
197}
198
199pub 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
224pub 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
231pub 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
246pub 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
269pub 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;