mdstore 1.2.0

A file-based storage engine that stores structured data as Markdown files with YAML frontmatter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use gray_matter::engine::YAML;
use gray_matter::Matter;
use serde::{de::DeserializeOwned, Serialize};
use thiserror::Error;

#[derive(Debug, Error)]
pub enum FrontmatterError {
    #[error("Invalid frontmatter format: {0}")]
    InvalidFormat(String),
    #[error("YAML parse error: {0}")]
    YamlError(#[from] serde_yaml::Error),
}

/// Split content (after frontmatter) into (title, body).
/// Title is extracted from the first `# Heading`, if present.
fn split_title_body(content: &str) -> (String, String) {
    let lines: Vec<&str> = content.lines().skip_while(|line| line.is_empty()).collect();

    if lines.first().is_some_and(|l| l.starts_with("# ")) {
        let title = lines
            .first()
            .and_then(|l| l.strip_prefix("# "))
            .unwrap_or("")
            .to_string();
        let body = lines
            .get(1..)
            .unwrap_or(&[])
            .iter()
            .skip_while(|line| line.is_empty())
            .copied()
            .collect::<Vec<_>>()
            .join("\n")
            .trim_end()
            .to_string();
        (title, body)
    } else {
        (String::new(), lines.join("\n").trim_end().to_string())
    }
}

/// Parse markdown content with YAML frontmatter.
///
/// Returns a tuple of:
/// - Deserialized metadata from frontmatter
/// - Title extracted from the H1 heading after frontmatter
/// - Body content (everything after the title)
///
/// # Format
/// ```markdown
/// ---
/// key: value
/// ---
/// # Title
///
/// Body content...
/// ```
pub fn parse_frontmatter<T: DeserializeOwned>(
    content: &str,
) -> Result<(T, String, String), FrontmatterError> {
    let matter = Matter::<YAML>::new();
    let result: gray_matter::ParsedEntity<serde_yaml::Value> = matter
        .parse(content)
        .map_err(|e| FrontmatterError::InvalidFormat(e.to_string()))?;

    if result.matter.is_empty() {
        return Err(FrontmatterError::InvalidFormat(
            "No frontmatter found".to_string(),
        ));
    }

    let metadata: T = serde_yaml::from_str(&result.matter)?;
    let (title, body) = split_title_body(&result.content);

    Ok((metadata, title, body))
}

/// Parse markdown content with YAML frontmatter into a raw `serde_yaml::Value`.
///
/// Same splitting logic as `parse_frontmatter<T>` but deserializes YAML into
/// `serde_yaml::Value` so that unknown/type-specific fields are preserved.
pub fn parse_frontmatter_raw(
    content: &str,
) -> Result<(serde_yaml::Value, String, String), FrontmatterError> {
    let matter = Matter::<YAML>::new();
    let result: gray_matter::ParsedEntity<serde_yaml::Value> = matter
        .parse(content)
        .map_err(|e| FrontmatterError::InvalidFormat(e.to_string()))?;

    if result.matter.is_empty() {
        return Err(FrontmatterError::InvalidFormat(
            "No frontmatter found".to_string(),
        ));
    }

    let value: serde_yaml::Value = serde_yaml::from_str(&result.matter)?;
    let (title, body) = split_title_body(&result.content);

    Ok((value, title, body))
}

/// Extract the YAML comment block from the top of the frontmatter section.
///
/// Returns the raw comment lines (including `# ` prefix) as a single string,
/// or `None` if no comment lines are found at the top of the frontmatter.
pub fn extract_frontmatter_comment(content: &str) -> Option<String> {
    let content = content.trim_start();
    if !content.starts_with("---") {
        return None;
    }
    let rest = content.get(3..)?.trim_start_matches('\n');
    let end = rest.find("\n---")?;
    let fm_block = &rest[..end];

    let mut comment_lines: Vec<&str> = Vec::new();
    for line in fm_block.lines() {
        if line.starts_with('#') {
            comment_lines.push(line);
        } else {
            break;
        }
    }

    if comment_lines.is_empty() {
        None
    } else {
        Some(comment_lines.join("\n"))
    }
}

/// Generate markdown content from a raw `serde_yaml::Value`.
pub fn generate_frontmatter_raw(
    value: &serde_yaml::Value,
    title: &str,
    body: &str,
    comment: Option<&str>,
) -> String {
    let yaml = serde_yaml::to_string(value).unwrap_or_default();
    let yaml = yaml.trim_end();

    let fm_content = match comment {
        Some(c) if !c.is_empty() => format!("{c}\n{yaml}"),
        _ => yaml.to_string(),
    };

    let title_trimmed = title.trim();
    if title_trimmed.is_empty() {
        if body.is_empty() {
            format!("---\n{fm_content}\n---\n")
        } else {
            format!("---\n{fm_content}\n---\n\n{body}\n")
        }
    } else if body.is_empty() {
        format!("---\n{fm_content}\n---\n\n# {title_trimmed}\n")
    } else {
        format!("---\n{fm_content}\n---\n\n# {title_trimmed}\n\n{body}\n")
    }
}

/// Generate markdown content with YAML frontmatter.
///
/// # Arguments
/// - `metadata`: Struct to serialize as YAML frontmatter
/// - `title`: The H1 heading title
/// - `body`: The body content after the title
/// - `comment`: Optional YAML comment lines to write at the top of the frontmatter block
///
/// # Returns
/// Formatted markdown string with frontmatter
pub fn generate_frontmatter<T: Serialize>(
    metadata: &T,
    title: &str,
    body: &str,
    comment: Option<&str>,
) -> String {
    // Serialize metadata to YAML
    let yaml = serde_yaml::to_string(metadata).unwrap_or_default();
    // serde_yaml adds a trailing newline, so trim it
    let yaml = yaml.trim_end();

    let fm_content = match comment {
        Some(c) if !c.is_empty() => format!("{c}\n{yaml}"),
        _ => yaml.to_string(),
    };

    let title_trimmed = title.trim();
    if title_trimmed.is_empty() {
        if body.is_empty() {
            format!("---\n{fm_content}\n---\n")
        } else {
            format!("---\n{fm_content}\n---\n\n{body}\n")
        }
    } else if body.is_empty() {
        format!("---\n{fm_content}\n---\n\n# {title_trimmed}\n")
    } else {
        format!("---\n{fm_content}\n---\n\n# {title_trimmed}\n\n{body}\n")
    }
}

#[cfg(test)]
mod tests {
    /// Escape a string for use in YAML values.
    /// Handles backslashes and double quotes.
    fn escape_yaml_string(s: &str) -> String {
        s.replace('\\', "\\\\").replace('"', "\\\"")
    }
    use super::*;
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Serialize, Deserialize, PartialEq)]
    #[serde(rename_all = "camelCase")]
    struct TestMetadata {
        display_number: u32,
        status: String,
        #[serde(default)]
        draft: bool,
    }

    #[test]
    fn test_parse_frontmatter_basic() {
        let content = r"---
displayNumber: 42
status: open
draft: false
---

# Test Title

This is the body content.";

        let (metadata, title, body): (TestMetadata, String, String) =
            parse_frontmatter(content).unwrap();

        assert_eq!(metadata.display_number, 42);
        assert_eq!(metadata.status, "open");
        assert!(!metadata.draft);
        assert_eq!(title, "Test Title");
        assert_eq!(body, "This is the body content.");
    }

    #[test]
    fn test_parse_frontmatter_empty_body() {
        let content = r"---
displayNumber: 1
status: closed
---

# Just a Title";

        let (metadata, title, body): (TestMetadata, String, String) =
            parse_frontmatter(content).unwrap();

        assert_eq!(metadata.display_number, 1);
        assert_eq!(title, "Just a Title");
        assert_eq!(body, "");
    }

    #[test]
    fn test_parse_frontmatter_multiline_body() {
        let content = r"---
displayNumber: 5
status: in-progress
---

# Multi Line

Line 1.

Line 2.

Line 3.";

        let (metadata, title, body): (TestMetadata, String, String) =
            parse_frontmatter(content).unwrap();

        assert_eq!(metadata.display_number, 5);
        assert_eq!(title, "Multi Line");
        assert_eq!(body, "Line 1.\n\nLine 2.\n\nLine 3.");
    }

    #[test]
    fn test_parse_frontmatter_missing_opening() {
        let content = "# No Frontmatter\n\nJust content.";
        let result: Result<(TestMetadata, String, String), _> = parse_frontmatter(content);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_frontmatter_missing_closing() {
        let content = "---\ndisplayNumber: 1\nstatus: open\n# Title";
        let result: Result<(TestMetadata, String, String), _> = parse_frontmatter(content);
        assert!(result.is_err());
    }

    #[test]
    fn test_generate_frontmatter_basic() {
        let metadata = TestMetadata {
            display_number: 42,
            status: "open".to_string(),
            draft: false,
        };

        let result = generate_frontmatter(&metadata, "Test Title", "Body content.", None);

        assert!(result.starts_with("---\n"));
        assert!(result.contains("displayNumber: 42"));
        assert!(result.contains("status: open"));
        assert!(result.contains("# Test Title"));
        assert!(result.contains("Body content."));
    }

    #[test]
    fn test_generate_frontmatter_empty_body() {
        let metadata = TestMetadata {
            display_number: 1,
            status: "closed".to_string(),
            draft: true,
        };

        let result = generate_frontmatter(&metadata, "Title Only", "", None);

        assert!(result.contains("# Title Only"));
        assert!(result.ends_with("# Title Only\n"));
    }

    #[test]
    fn test_generate_frontmatter_with_comment() {
        let metadata = TestMetadata {
            display_number: 1,
            status: "open".to_string(),
            draft: false,
        };
        let comment = "# This file was auto-generated. Do not edit manually.";

        let result = generate_frontmatter(&metadata, "My Doc", "Body.", Some(comment));

        assert!(result.starts_with("---\n# This file was auto-generated"));
        assert!(result.contains("displayNumber: 1"));
    }

    #[test]
    fn test_roundtrip() {
        let original_metadata = TestMetadata {
            display_number: 99,
            status: "review".to_string(),
            draft: true,
        };
        let original_title = "Round Trip Test";
        let original_body = "This should survive the round trip.";

        let generated =
            generate_frontmatter(&original_metadata, original_title, original_body, None);
        let (parsed_metadata, parsed_title, parsed_body): (TestMetadata, String, String) =
            parse_frontmatter(&generated).unwrap();

        assert_eq!(parsed_metadata, original_metadata);
        assert_eq!(parsed_title, original_title);
        assert_eq!(parsed_body, original_body);
    }

    #[test]
    fn test_roundtrip_with_comment() {
        let original_metadata = TestMetadata {
            display_number: 5,
            status: "open".to_string(),
            draft: false,
        };
        let comment = "# Auto-generated";

        let generated = generate_frontmatter(&original_metadata, "Title", "Body.", Some(comment));
        let extracted = extract_frontmatter_comment(&generated);
        let (parsed_metadata, parsed_title, _): (TestMetadata, String, String) =
            parse_frontmatter(&generated).unwrap();

        assert_eq!(extracted, Some(comment.to_string()));
        assert_eq!(parsed_metadata, original_metadata);
        assert_eq!(parsed_title, "Title");
    }

    #[test]
    fn test_extract_frontmatter_comment_none() {
        let content = "---\ndisplayNumber: 1\nstatus: open\n---\n\n# Title\n";
        assert_eq!(extract_frontmatter_comment(content), None);
    }

    #[test]
    fn test_extract_frontmatter_comment_multiline() {
        let content = "---\n# Line 1\n# Line 2\ndisplayNumber: 1\n---\n\n# Title\n";
        assert_eq!(
            extract_frontmatter_comment(content),
            Some("# Line 1\n# Line 2".to_string())
        );
    }

    #[test]
    fn test_generate_frontmatter_empty_title_no_body() {
        let metadata = TestMetadata {
            display_number: 1,
            status: "open".to_string(),
            draft: false,
        };
        let result = generate_frontmatter(&metadata, "", "", None);
        assert!(!result.contains("# "), "should not contain H1 heading");
        assert!(result.starts_with("---\n"));
    }

    #[test]
    fn test_generate_frontmatter_empty_title_with_body() {
        let metadata = TestMetadata {
            display_number: 1,
            status: "open".to_string(),
            draft: false,
        };
        let result = generate_frontmatter(&metadata, "", "body text here", None);
        assert!(!result.contains("# "), "should not contain H1 heading");
        assert!(result.contains("body text here"));
    }

    #[test]
    fn test_generate_frontmatter_whitespace_only_title() {
        let metadata = TestMetadata {
            display_number: 1,
            status: "open".to_string(),
            draft: false,
        };
        let result = generate_frontmatter(&metadata, "   ", "body", None);
        assert!(!result.contains("# "), "should not contain H1 heading");
        assert!(result.contains("body"));
    }

    #[test]
    fn test_escape_yaml_string() {
        assert_eq!(escape_yaml_string("hello"), "hello");
        assert_eq!(escape_yaml_string(r#"say "hi""#), r#"say \"hi\""#);
        assert_eq!(escape_yaml_string(r"back\slash"), r"back\\slash");
    }
}