frontmatter_gen/
lib.rs

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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
#![doc = include_str!("../README.md")]
#![doc(
    html_favicon_url = "https://kura.pro/frontmatter-gen/images/favicon.ico",
    html_logo_url = "https://kura.pro/frontmatter-gen/images/logos/frontmatter-gen.svg",
    html_root_url = "https://docs.rs/frontmatter-gen"
)]

//! # Frontmatter Gen
//!
//! `frontmatter-gen` is a fast, secure, and memory-efficient library for working with
//! frontmatter in multiple formats (YAML, TOML, and JSON).
//!
//! ## Overview
//!
//! Frontmatter is metadata prepended to content files, commonly used in static site
//! generators and content management systems. This library provides:
//!
//! - **Zero-copy parsing** for optimal performance
//! - **Format auto-detection** between YAML, TOML, and JSON
//! - **Memory safety** with no unsafe code
//! - **Comprehensive validation** of all inputs
//! - **Rich error handling** with detailed diagnostics
//! - **Async support** for non-blocking operations
//!
//! ## Quick Start
//!
//! ```rust
//! use frontmatter_gen::{extract, Format, Result};
//!
//! fn main() -> Result<()> {
//!     let content = r#"---
//! title: My Post
//! date: 2025-09-09
//! draft: false
//! ---
//! # Post content here
//! "#;
//!
//!     let (frontmatter, content) = extract(content)?;
//!     println!("Title: {}", frontmatter.get("title")
//!         .and_then(|v| v.as_str())
//!         .unwrap_or("Untitled"));
//!
//!     Ok(())
//! }
//! ```

/// Prelude module for convenient imports.
///
/// This module provides the most commonly used types and traits.
/// Import all contents with `use frontmatter_gen::prelude::*`.
pub mod prelude {
    pub use crate::{
        extract, to_format, Config, Format, Frontmatter,
        FrontmatterError, Result, Value,
    };
}

// Re-export core types and traits
pub use crate::{
    config::Config,
    error::FrontmatterError,
    extractor::{detect_format, extract_raw_frontmatter},
    parser::{parse, to_string},
    types::{Format, Frontmatter, Value},
};

// Module declarations
pub mod config;
pub mod engine;
pub mod error;
pub mod extractor;
pub mod parser;
pub mod types;
pub mod utils;

/// A specialized Result type for frontmatter operations.
///
/// This type alias provides a consistent error type throughout the crate
/// and simplifies error handling for library users.
pub type Result<T> = std::result::Result<T, FrontmatterError>;

/// Extracts and parses frontmatter from content with format auto-detection.
///
/// This function provides a zero-copy extraction of frontmatter, automatically
/// detecting the format (YAML, TOML, or JSON) and parsing it into a structured
/// representation.
///
/// # Performance
///
/// This function performs a single pass over the input with O(n) complexity
/// and avoids unnecessary allocations where possible.
///
/// # Examples
///
/// ```rust
/// use frontmatter_gen::extract;
///
/// let content = r#"---
/// title: My Post
/// date: 2025-09-09
/// ---
/// Content here"#;
///
/// let (frontmatter, content) = extract(content)?;
/// assert_eq!(frontmatter.get("title").unwrap().as_str().unwrap(), "My Post");
/// assert_eq!(content.trim(), "Content here");
/// # Ok::<(), frontmatter_gen::FrontmatterError>(())
/// ```
///
/// # Errors
///
/// Returns `FrontmatterError` if:
/// - Content is malformed
/// - Frontmatter format is invalid
/// - Parsing fails
#[inline]
pub fn extract(content: &str) -> Result<(Frontmatter, &str)> {
    let (raw_frontmatter, remaining_content) =
        extract_raw_frontmatter(content)?;
    let format = detect_format(raw_frontmatter)?;
    let frontmatter = parse(raw_frontmatter, format)?;
    Ok((frontmatter, remaining_content))
}

/// Converts frontmatter to a specific format.
///
/// # Arguments
///
/// * `frontmatter` - The frontmatter to convert
/// * `format` - Target format for conversion
///
/// # Returns
///
/// Returns the formatted string representation or an error.
///
/// # Examples
///
/// ```rust
/// use frontmatter_gen::{Frontmatter, Format, Value, to_format};
///
/// let mut frontmatter = Frontmatter::new();
/// frontmatter.insert("title".to_string(), Value::String("My Post".into()));
///
/// let yaml = to_format(&frontmatter, Format::Yaml)?;
/// assert!(yaml.contains("title: My Post"));
/// # Ok::<(), frontmatter_gen::FrontmatterError>(())
/// ```
///
/// # Errors
///
/// Returns `FrontmatterError` if:
/// - Serialization fails
/// - Format conversion fails
/// - Invalid data types are encountered
pub fn to_format(
    frontmatter: &Frontmatter,
    format: Format,
) -> Result<String> {
    to_string(frontmatter, format)
}

#[cfg(test)]
mod extractor_tests {
    use crate::FrontmatterError;

    fn mock_operation(
        input: Option<&str>,
    ) -> Result<String, FrontmatterError> {
        match input {
            Some(value) => Ok(value.to_uppercase()), // Successful operation
            None => Err(FrontmatterError::ParseError(
                "Input is missing".to_string(),
            )),
        }
    }

    #[test]
    fn test_result_type_success() {
        let input = Some("hello");
        let result = mock_operation(input);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "HELLO".to_string());
    }

    #[test]
    fn test_result_type_error() {
        let input = None;
        let result = mock_operation(input);
        assert!(matches!(
            result,
            Err(FrontmatterError::ParseError(ref e)) if e == "Input is missing"
        ));
    }

    #[test]
    fn test_result_type_pattern_matching() {
        let input = Some("world");
        let result = mock_operation(input);
        match result {
            Ok(value) => assert_eq!(value, "WORLD".to_string()),
            Err(e) => panic!("Operation failed: {:?}", e),
        }
    }

    #[test]
    fn test_result_type_unwrap() {
        let input = Some("rust");
        let result = mock_operation(input);
        assert_eq!(result.unwrap(), "RUST".to_string());
    }

    #[test]
    fn test_result_type_expect() {
        let input = Some("test");
        let result = mock_operation(input);
        assert_eq!(
            result.expect("Unexpected error"),
            "TEST".to_string()
        );
    }

    #[test]
    fn test_result_type_debug_format() {
        let input = None;
        let result = mock_operation(input);
        assert_eq!(
            format!("{:?}", result),
            "Err(ParseError(\"Input is missing\"))"
        );
    }
}

#[cfg(test)]
mod parser_tests {
    use super::*;

    #[test]
    fn test_parse_yaml_frontmatter() {
        let raw = "title: Test Post\npublished: true";
        let format = Format::Yaml;
        let parsed = parse(raw, format).unwrap();
        assert_eq!(
            parsed.get("title").unwrap().as_str().unwrap(),
            "Test Post"
        );
        assert!(parsed.get("published").unwrap().as_bool().unwrap());
    }

    #[test]
    fn test_parse_toml_frontmatter() {
        let raw = "title = \"Test Post\"\npublished = true";
        let format = Format::Toml;
        let parsed = parse(raw, format).unwrap();
        assert_eq!(
            parsed.get("title").unwrap().as_str().unwrap(),
            "Test Post"
        );
        assert!(parsed.get("published").unwrap().as_bool().unwrap());
    }

    #[test]
    fn test_invalid_yaml_syntax() {
        let raw = "title: : invalid yaml";
        let format = Format::Yaml;
        let result = parse(raw, format);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_invalid_toml_syntax() {
        let raw = "title = \"Unmatched quote";
        let format = Format::Toml;
        let result = parse(raw, format);
        assert!(result.is_err(), "Should fail for invalid TOML syntax");
    }

    #[test]
    fn test_parse_invalid_json_syntax() {
        let raw = "{\"title\": \"Missing closing brace\"";
        let format = Format::Json;
        let result = parse(raw, format);
        assert!(result.is_err(), "Should fail for invalid JSON syntax");
    }

    #[test]
    fn test_parse_with_unknown_format() {
        let raw = "random text";
        let format = Format::Unsupported;
        let result = parse(raw, format);
        assert!(result.is_err(), "Should fail for unsupported formats");
    }

    #[test]
    fn test_parse_valid_yaml() {
        let raw = "title: Valid Post\npublished: true";
        let format = Format::Yaml;
        let frontmatter = parse(raw, format).unwrap();
        assert_eq!(
            frontmatter.get("title").unwrap().as_str().unwrap(),
            "Valid Post"
        );
        assert!(frontmatter
            .get("published")
            .unwrap()
            .as_bool()
            .unwrap());
    }

    #[test]
    fn test_parse_malformed_yaml() {
        let raw = "title: : bad yaml";
        let format = Format::Yaml;
        let result = parse(raw, format);
        assert!(result.is_err(), "Should fail for malformed YAML");
    }

    #[test]
    fn test_parse_json() {
        let raw = r#"{"title": "Valid Post", "draft": false}"#;
        let format = Format::Json;
        let frontmatter = parse(raw, format).unwrap();
        assert_eq!(
            frontmatter.get("title").unwrap().as_str().unwrap(),
            "Valid Post"
        );
        assert!(!frontmatter.get("draft").unwrap().as_bool().unwrap());
    }
}

#[cfg(test)]
mod format_tests {
    use super::*;

    #[test]
    fn test_to_format_yaml() {
        let mut frontmatter = Frontmatter::new();
        let _ = frontmatter.insert(
            "title".to_string(),
            Value::String("Test Post".to_string()),
        );
        let yaml = to_format(&frontmatter, Format::Yaml).unwrap();
        assert!(yaml.contains("title: Test Post"));
    }

    #[test]
    fn test_format_conversion_roundtrip() {
        let mut frontmatter = Frontmatter::new();
        let _ = frontmatter.insert(
            "key".to_string(),
            Value::String("value".to_string()),
        );
        let yaml = to_format(&frontmatter, Format::Yaml).unwrap();
        let content = format!("---\n{}\n---\nContent", yaml);
        let (parsed, _) = extract(&content).unwrap();
        assert_eq!(
            parsed.get("key").unwrap().as_str().unwrap(),
            "value"
        );
    }

    #[test]
    fn test_unsupported_format() {
        let result =
            to_format(&Frontmatter::new(), Format::Unsupported);
        assert!(result.is_err());
    }

    #[test]
    fn test_convert_to_yaml() {
        let mut frontmatter = Frontmatter::new();
        let _ = frontmatter.insert(
            "title".to_string(),
            Value::String("Test Post".into()),
        );
        let yaml = to_format(&frontmatter, Format::Yaml).unwrap();
        assert!(yaml.contains("title: Test Post"));
    }

    #[test]
    fn test_roundtrip_conversion() {
        let content = "---\ntitle: Test Post\n---\nContent";
        let (parsed, _) = extract(content).unwrap();
        let yaml = to_format(&parsed, Format::Yaml).unwrap();
        assert!(yaml.contains("title: Test Post"));
    }

    #[test]
    fn test_format_invalid_data() {
        let frontmatter = Frontmatter::new();
        let result = to_format(&frontmatter, Format::Unsupported);
        assert!(result.is_err());
    }
}

#[cfg(test)]
mod integration_tests {
    use super::*;

    #[test]
    fn test_end_to_end_extraction_and_parsing() {
        let content = "---\ntitle: Test Post\n---\nContent here";
        let (frontmatter, content) = extract(content).unwrap();
        assert_eq!(
            frontmatter.get("title").unwrap().as_str().unwrap(),
            "Test Post"
        );
        assert_eq!(content.trim(), "Content here");
    }

    #[test]
    fn test_roundtrip_conversion() {
        let content = "---\ntitle: Test Post\n---\nContent";
        let (frontmatter, _) = extract(content).unwrap();
        let yaml = to_format(&frontmatter, Format::Yaml).unwrap();
        assert!(yaml.contains("title: Test Post"));
    }

    #[test]
    fn test_complete_workflow() {
        let content = "---\ntitle: Integration Test\n---\nBody content";
        let (frontmatter, body) = extract(content).unwrap();
        assert_eq!(
            frontmatter.get("title").unwrap().as_str().unwrap(),
            "Integration Test"
        );
        assert_eq!(body.trim(), "Body content");
    }

    #[test]
    fn test_end_to_end_error_handling() {
        let content = "Invalid frontmatter";
        let result = extract(content);
        assert!(result.is_err());
    }
}

#[cfg(test)]
mod edge_case_tests {
    use super::*;

    #[test]
    fn test_special_characters_handling() {
        let cases = vec![
            (
                "---\ntitle: \"Special: &chars\"\n---\nContent",
                "Special: &chars",
            ),
            (
                "---\ntitle: \"Another > test\"\n---\nContent",
                "Another > test",
            ),
        ];

        for (content, expected_title) in cases {
            let (frontmatter, _) = extract(content).unwrap();
            assert_eq!(
                frontmatter.get("title").unwrap().as_str().unwrap(),
                expected_title
            );
        }
    }

    #[cfg(feature = "ssg")]
    #[tokio::test]
    async fn test_async_extraction() {
        let content = "---\ntitle: Async Test\n---\nContent";
        let (frontmatter, body) = extract(content).unwrap();
        assert_eq!(
            frontmatter.get("title").unwrap().as_str().unwrap(),
            "Async Test"
        );
        assert_eq!(body.trim(), "Content");
    }

    #[test]
    fn test_large_frontmatter() {
        let mut large_content = String::from("---\n");
        for i in 0..1000 {
            large_content
                .push_str(&format!("key_{}: value_{}\n", i, i));
        }
        large_content.push_str("---\nContent");
        let (frontmatter, content) = extract(&large_content).unwrap();
        assert_eq!(frontmatter.len(), 1000);
        assert_eq!(content.trim(), "Content");
    }

    #[test]
    fn test_special_characters() {
        let content =
            "---\ntitle: \"Special & <characters>\"\n---\nContent";
        let (frontmatter, _) = extract(content).unwrap();
        assert_eq!(
            frontmatter.get("title").unwrap().as_str().unwrap(),
            "Special & <characters>"
        );
    }
}