Skip to main content

agent_rules_tool/
parse.rs

1//! Parse markdown rule files into YAML frontmatter and body text.
2
3use crate::error::Error;
4use serde_json::Value;
5
6/// Parsed rule file: JSON frontmatter value and markdown body.
7#[derive(Debug, Clone)]
8pub struct ParsedRule {
9    /// Frontmatter converted to JSON for schema validation.
10    pub frontmatter: Value,
11    /// Markdown content after the closing `---`.
12    pub body: String,
13}
14
15/// Parse a rule file string into frontmatter and body.
16///
17/// Empty or missing frontmatter becomes JSON `null`.
18pub fn parse_rule(content: &str) -> Result<ParsedRule, Error> {
19    let (yaml_value, body) = markdown_frontmatter::parse::<serde_yaml::Value>(content)?;
20    let frontmatter = yaml_to_json(yaml_value)?;
21    Ok(ParsedRule {
22        frontmatter,
23        body: body.to_string(),
24    })
25}
26
27fn yaml_to_json(yaml: serde_yaml::Value) -> Result<Value, Error> {
28    match yaml {
29        serde_yaml::Value::Null => Ok(Value::Null),
30        other => serde_json::to_value(other).map_err(|e| Error::Yaml(e.to_string())),
31    }
32}
33
34/// Returns `true` when frontmatter is null or an empty object.
35pub fn is_empty_frontmatter(value: &Value) -> bool {
36    match value {
37        Value::Null => true,
38        Value::Object(map) => map.is_empty(),
39        _ => false,
40    }
41}