frontmatter_gen/extractor.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
//! This module provides functionality for extracting frontmatter from content.
//!
//! It includes functions to extract frontmatter in various formats (YAML, TOML, JSON) from a given string content, as well as utilities to detect the format of the frontmatter.
use crate::error::Error;
use crate::types::Format;
/// Extracts raw frontmatter from the content, detecting YAML, TOML, or JSON formats.
///
/// This function tries to extract frontmatter based on the common delimiters for
/// YAML (`---`), TOML (`+++`), and JSON (`{}`). If frontmatter is detected, it
/// returns the extracted frontmatter and the remaining content.
///
/// # Arguments
///
/// * `content` - The full content string that may contain frontmatter.
///
/// # Returns
///
/// A `Result` containing a tuple of two `&str` slices: the raw frontmatter and the remaining content.
/// If no valid frontmatter format is found, it returns `Error::InvalidFormat`.
///
/// # Errors
///
/// - `Error::InvalidFormat`: When the frontmatter format is not recognized.
/// - `Error::ExtractionError`: When there is an issue extracting frontmatter.
///
/// # Example
///
/// ```rust
/// use frontmatter_gen::extractor::{extract_delimited_frontmatter, extract_raw_frontmatter, extract_json_frontmatter};
/// let content = "---\ntitle: Example\n---\nContent here";
/// let result = extract_raw_frontmatter(content).unwrap();
/// assert_eq!(result.0, "title: Example");
/// assert_eq!(result.1, "Content here");
/// ```
pub fn extract_raw_frontmatter(
content: &str,
) -> Result<(&str, &str), Error> {
// Extract YAML frontmatter
if let Some(yaml) =
extract_delimited_frontmatter(content, "---\n", "\n---")
.or_else(|| {
extract_delimited_frontmatter(
content, "---\r\n", "\r\n---",
)
})
{
let remaining = &content[content
.find("\n---\n")
.or_else(|| content.find("\r\n---\r\n"))
.map_or(content.len(), |i| i + 5)..];
return Ok((yaml, remaining.trim_start()));
}
// Extract TOML frontmatter
if let Some(toml) =
extract_delimited_frontmatter(content, "+++\n", "\n+++")
.or_else(|| {
extract_delimited_frontmatter(
content, "+++\r\n", "\r\n+++",
)
})
{
let remaining = &content[content
.find("\n+++\n")
.or_else(|| content.find("\r\n+++\r\n"))
.map_or(content.len(), |i| i + 5)..];
return Ok((toml, remaining.trim_start()));
}
// Extract JSON frontmatter
if let Ok(json) = extract_json_frontmatter(content) {
let remaining = &content[json.len()..];
return Ok((json, remaining.trim_start()));
}
// Handle cases where frontmatter delimiters exist but are empty
if content.starts_with("---\n---")
|| content.starts_with("+++\n+++")
{
return Err(Error::InvalidFormat);
}
Err(Error::InvalidFormat)
}
/// Extracts JSON frontmatter from the content by detecting balanced curly braces (`{}`).
///
/// This function attempts to locate a valid JSON object starting with `{` and checks for balanced
/// curly braces to identify the end of the frontmatter. If the JSON object is found, it returns
/// the frontmatter as a string slice. A maximum nesting depth is enforced to prevent deeply nested
/// JSON from causing stack overflow.
///
/// # Arguments
///
/// * `content` - The full content string that may contain JSON frontmatter.
///
/// # Returns
///
/// A `Result` containing the extracted JSON frontmatter string slice.
/// If no valid JSON frontmatter is detected, it returns an `Error`.
///
/// # Errors
///
/// - `Error::InvalidJson`: If the content does not start with `{` or contains unbalanced braces.
/// - `Error::JsonDepthLimitExceeded`: If the JSON object exceeds the allowed nesting depth.
///
/// # Example
///
/// ```rust
/// use frontmatter_gen::extractor::extract_json_frontmatter;
/// let content = "{ \"title\": \"Example\" }\nContent";
/// let frontmatter = extract_json_frontmatter(content).unwrap();
/// assert_eq!(frontmatter, "{ \"title\": \"Example\" }");
/// ```
pub fn extract_json_frontmatter(content: &str) -> Result<&str, Error> {
const MAX_DEPTH: usize = 100; // Limit maximum nesting depth
let trimmed = content.trim_start();
// If the content doesn't start with '{', it's not JSON frontmatter.
if !trimmed.starts_with('{') {
return Err(Error::InvalidJson);
}
let mut brace_count = 0;
let mut depth = 0;
let mut in_string = false;
let mut escape_next = false;
// Iterate over the characters in the trimmed content, looking for balanced braces.
for (idx, ch) in trimmed.char_indices() {
if escape_next {
escape_next = false;
continue;
}
match ch {
'"' if !in_string => in_string = true,
'"' if in_string => in_string = false,
'\\' if in_string => escape_next = true,
'{' if !in_string => {
brace_count += 1;
depth += 1;
// Check if the maximum depth is exceeded
if depth > MAX_DEPTH {
return Err(Error::JsonDepthLimitExceeded);
}
}
'}' if !in_string => {
brace_count -= 1;
// Decrease depth when closing braces
if depth > 0 {
depth = depth.saturating_sub(1);
}
// Once braces are balanced (brace_count == 0), we've reached the end of the JSON object.
if brace_count == 0 {
return Ok(&trimmed[..=idx]);
}
}
_ => {}
}
}
// If no balanced braces are found, return an error.
Err(Error::InvalidJson)
}
/// Detects the format of the extracted frontmatter.
///
/// This function analyzes the raw frontmatter and determines whether it is in YAML,
/// TOML, or JSON format by examining the structure of the data.
///
/// # Arguments
///
/// * `raw_frontmatter` - The extracted frontmatter as a string slice.
///
/// # Returns
///
/// A `Result` containing the detected `Format` (either `Json`, `Toml`, or `Yaml`).
///
/// # Errors
///
/// - `Error::InvalidFormat`: If the format cannot be determined.
///
/// # Example
///
/// ```rust
/// use frontmatter_gen::extractor::detect_format;
/// use frontmatter_gen::Format;
/// let raw = "---\ntitle: Example\n---";
/// let format = detect_format(raw).unwrap();
/// assert_eq!(format, Format::Yaml);
/// ```
pub fn detect_format(raw_frontmatter: &str) -> Result<Format, Error> {
let trimmed = raw_frontmatter.trim_start();
// Check for YAML front matter marker
if trimmed.starts_with("---") {
return Ok(Format::Yaml);
}
// Check for JSON structure
if trimmed.starts_with('{') {
return Ok(Format::Json);
}
// Check for YAML-like structure
if trimmed.contains(':') && !trimmed.contains('{') {
return Ok(Format::Yaml);
}
// Check for TOML-like structure
if trimmed.contains('=') {
return Ok(Format::Toml);
}
// Default to an error if none of the formats match
Err(Error::InvalidFormat)
}
/// Extracts frontmatter enclosed by the given start and end delimiters.
///
/// This function checks for frontmatter enclosed by delimiters like `---` for YAML or `+++` for TOML.
/// It returns the extracted frontmatter if the delimiters are found.
///
/// # Arguments
///
/// * `content` - The full content string containing frontmatter.
/// * `start_delim` - The starting delimiter (e.g., `---\n` for YAML).
/// * `end_delim` - The ending delimiter (e.g., `\n---\n` for YAML).
///
/// # Returns
///
/// An `Option` containing the extracted frontmatter as a string slice. Returns `None`
/// if the delimiters are not found.
///
/// # Example
///
/// ```rust
/// use frontmatter_gen::extractor::extract_delimited_frontmatter;
/// let content = "---\ntitle: Example\n---\nContent";
/// let frontmatter = extract_delimited_frontmatter(content, "---\n", "\n---\n").unwrap();
/// assert_eq!(frontmatter, "title: Example");
/// ```
#[must_use]
pub fn extract_delimited_frontmatter<'a>(
content: &'a str,
start_delim: &str,
end_delim: &str,
) -> Option<&'a str> {
let start_index = content.find(start_delim)? + start_delim.len();
let end_index = content.find(end_delim)?;
if start_index <= end_index {
Some(content[start_index..end_index].trim())
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Tests for extracting raw frontmatter
mod extract_raw_frontmatter {
use super::*;
#[test]
fn test_extract_yaml() {
let content = r"---
title: Example
---
Content here";
let result = extract_raw_frontmatter(content).unwrap();
assert_eq!(result.0, "title: Example");
assert_eq!(result.1, "Content here");
}
#[test]
fn test_extract_toml() {
let content = r#"+++
title = "Example"
+++
Content here"#;
let result = extract_raw_frontmatter(content).unwrap();
assert_eq!(result.0, r#"title = "Example""#);
assert_eq!(result.1, "Content here");
}
#[test]
fn test_extract_json() {
let content = r#"{ "title": "Example" }
Content here"#;
let result = extract_raw_frontmatter(content).unwrap();
assert_eq!(result.0, r#"{ "title": "Example" }"#);
assert_eq!(result.1, "Content here");
}
#[test]
fn test_invalid_format() {
let content = "Invalid frontmatter";
let result = detect_format(content);
if let Err(Error::InvalidFormat) = result {
// Test passed
} else {
panic!("Expected Err(InvalidFormat), got {:?}", result);
}
}
}
/// Tests for JSON frontmatter extraction
mod extract_json_frontmatter {
use super::*;
#[test]
fn test_valid_json() {
let content = r#"{ "title": "Example" }
Content here"#;
let result = extract_json_frontmatter(content).unwrap();
assert_eq!(result, r#"{ "title": "Example" }"#);
}
#[test]
fn test_nested_json() {
let content = r#"{ "a": { "b": { "c": { "d": { "e": {} }}}}}
Content here"#;
let result = extract_json_frontmatter(content);
assert!(result.is_ok());
assert_eq!(
result.unwrap(),
r#"{ "a": { "b": { "c": { "d": { "e": {} }}}}}"#
);
}
#[test]
fn test_too_deep_json() {
let mut content = String::from("{ ");
for _ in 0..101 {
content.push_str(r#""a": { "#);
}
content.push_str(&"}".repeat(101));
content.push_str("\nContent here");
let result = extract_json_frontmatter(&content);
assert!(matches!(
result,
Err(Error::JsonDepthLimitExceeded)
));
}
#[test]
fn test_escaped_characters() {
let content = r#"{ "title": "Example with \"quotes\" and {braces}", "content": "Some text with \\ backslash" }
Actual content starts here"#;
let result = extract_json_frontmatter(content).unwrap();
assert_eq!(
result,
r#"{ "title": "Example with \"quotes\" and {braces}", "content": "Some text with \\ backslash" }"#
);
}
#[test]
fn test_invalid_json() {
let content = "Not a JSON frontmatter";
let result = extract_json_frontmatter(content);
assert!(matches!(result, Err(Error::InvalidJson)));
}
}
/// Tests for format detection
mod detect_format {
use super::*;
#[test]
fn test_yaml_format() {
let content = "title: Example";
let result = detect_format(content).unwrap();
assert_eq!(result, Format::Yaml);
}
#[test]
fn test_toml_format() {
let content = "title = \"Example\"";
let result = detect_format(content).unwrap();
assert_eq!(result, Format::Toml);
}
#[test]
fn test_json_format() {
let content = r#"{ "title": "Example" }"#;
let result = detect_format(content).unwrap();
assert_eq!(result, Format::Json);
}
#[test]
fn test_invalid_format() {
let content = "Invalid content";
let result = detect_format(content);
assert!(matches!(result, Err(Error::InvalidFormat)));
}
}
/// Tests for delimited frontmatter extraction
mod extract_delimited_frontmatter {
use super::*;
#[test]
fn test_valid_yaml() {
let content = "---\ntitle: Example\n---\nContent here";
let result = extract_delimited_frontmatter(
content, "---\n", "\n---\n",
)
.unwrap();
assert_eq!(result, "title: Example");
}
#[test]
fn test_valid_toml() {
let content = "+++\ntitle = \"Example\"\n+++\nContent here";
let result = extract_delimited_frontmatter(
content, "+++\n", "\n+++\n",
)
.unwrap();
assert_eq!(result, r#"title = "Example""#);
}
#[test]
fn test_valid_windows_format() {
let content =
"---\r\ntitle: Example\r\n---\r\nContent here";
let result = extract_delimited_frontmatter(
content,
"---\r\n",
"\r\n---\r\n",
)
.unwrap();
assert_eq!(result, "title: Example");
}
#[test]
fn test_missing_start_delimiter() {
let content = "title: Example\n---\nContent here";
let result = extract_delimited_frontmatter(
content, "---\n", "\n---\n",
);
assert!(result.is_none());
}
#[test]
fn test_missing_end_delimiter() {
let content = "---\ntitle: Example\nContent here";
let result = extract_delimited_frontmatter(
content, "---\n", "\n---\n",
);
assert!(result.is_none());
}
}
}