Skip to main content

features_cli/
readme_parser.rs

1use anyhow::{Context, Result};
2use std::collections::BTreeMap;
3use std::fs;
4use std::path::Path;
5
6/// Information extracted from a README file
7#[derive(Clone, Default)]
8pub struct ReadmeInfo {
9    /// Optional title extracted from the first markdown heading
10    pub title: Option<String>,
11    /// Owner of the feature
12    pub owner: String,
13    /// Description content (everything after the first heading)
14    pub description: String,
15    /// Additional metadata from YAML frontmatter
16    pub meta: BTreeMap<String, serde_json::Value>,
17    /// The `feature` boolean from YAML frontmatter, if present
18    pub feature_flag: Option<bool>,
19}
20
21fn extract_first_title(content: &str) -> Option<String> {
22    for line in content.lines() {
23        let trimmed = line.trim();
24
25        // Check if this line is a title (starting with #)
26        if trimmed.starts_with('#') {
27            // Remove all leading # characters and whitespace
28            let title = trimmed.trim_start_matches('#').trim();
29            if !title.is_empty() {
30                return Some(title.to_string());
31            }
32        }
33    }
34    None
35}
36
37fn read_readme_content(content: &str) -> String {
38    let mut found_first_title = false;
39    let mut lines_after_title: Vec<&str> = Vec::new();
40
41    for line in content.lines() {
42        let trimmed = line.trim();
43
44        // Check if we found the first title (starting with #)
45        if !found_first_title && trimmed.starts_with('#') {
46            found_first_title = true;
47            continue;
48        }
49
50        // Collect all lines after the first title
51        if found_first_title {
52            lines_after_title.push(line);
53        }
54    }
55
56    // Join all lines after the first title
57    lines_after_title.join("\n").trim().to_string()
58}
59
60/// Reads README information from README.md or README.mdx files
61/// Returns ReadmeInfo containing title, owner, description, and metadata
62/// The title is extracted from the first markdown heading (# Title)
63pub fn read_readme_info(readme_path: &Path) -> Result<ReadmeInfo> {
64    if !readme_path.exists() {
65        return Ok(ReadmeInfo::default());
66    }
67
68    let content = fs::read_to_string(readme_path)
69        .with_context(|| format!("could not read README file at `{}`", readme_path.display()))?;
70
71    Ok(parse_readme_info(&content))
72}
73
74/// Parses README information from the content of a README file
75pub fn parse_readme_info(content: &str) -> ReadmeInfo {
76    let mut title: Option<String> = None;
77    let mut owner = "".to_string();
78    let mut description = "".to_string();
79    let mut meta: BTreeMap<String, serde_json::Value> = BTreeMap::new();
80    let mut feature_flag = None;
81
82    // Check if content starts with YAML front matter (---)
83    if let Some(stripped) = content.strip_prefix("---\n") {
84        if let Some(end_pos) = stripped.find("\n---\n") {
85            let yaml_content = &stripped[..end_pos];
86            let markdown_content = stripped[end_pos + 5..].to_string();
87
88            // Parse YAML front matter
89            if let Ok(yaml_value) = serde_yaml::from_str::<serde_yaml::Value>(yaml_content)
90                && let Some(mapping) = yaml_value.as_mapping()
91            {
92                for (key, value) in mapping {
93                    if let Some(key_str) = key.as_str() {
94                        if key_str == "owner" {
95                            if let Some(owner_value) = value.as_str() {
96                                owner = owner_value.to_string();
97                            }
98                        } else {
99                            if key_str == "feature" {
100                                feature_flag = value.as_bool();
101                            }
102
103                            // Convert YAML value to JSON value for meta
104                            if let Ok(json_value) = serde_json::to_value(value) {
105                                meta.insert(key_str.to_string(), json_value);
106                            }
107                        }
108                    }
109                }
110            }
111
112            // Extract title from markdown content (after frontmatter)
113            title = extract_first_title(&markdown_content);
114            description = read_readme_content(&markdown_content)
115        }
116    } else {
117        // No frontmatter, extract title and description from full content
118        title = extract_first_title(content);
119        description = read_readme_content(content)
120    }
121
122    ReadmeInfo {
123        title,
124        owner,
125        description,
126        meta,
127        feature_flag,
128    }
129}