features_cli/
readme_parser.rs1use anyhow::{Context, Result};
2use std::collections::BTreeMap;
3use std::fs;
4use std::path::Path;
5
6#[derive(Clone, Default)]
8pub struct ReadmeInfo {
9 pub title: Option<String>,
11 pub owner: String,
13 pub description: String,
15 pub meta: BTreeMap<String, serde_json::Value>,
17 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 if trimmed.starts_with('#') {
27 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 if !found_first_title && trimmed.starts_with('#') {
46 found_first_title = true;
47 continue;
48 }
49
50 if found_first_title {
52 lines_after_title.push(line);
53 }
54 }
55
56 lines_after_title.join("\n").trim().to_string()
58}
59
60pub 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
74pub 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 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 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 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 title = extract_first_title(&markdown_content);
114 description = read_readme_content(&markdown_content)
115 }
116 } else {
117 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}