ferrous_forge/
doc_coverage.rs1use crate::{Error, Result};
7use regex::Regex;
8use serde::{Deserialize, Serialize};
9use std::path::Path;
10use std::process::Command;
11
12#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct DocCoverage {
15 pub total_items: usize,
17 pub documented_items: usize,
19 pub coverage_percent: f32,
21 pub missing: Vec<String>,
23}
24
25impl DocCoverage {
26 pub fn meets_threshold(&self, min_coverage: f32) -> bool {
28 self.coverage_percent >= min_coverage
29 }
30
31 pub fn report(&self) -> String {
33 let mut report = String::new();
34
35 if self.coverage_percent >= 100.0 {
36 report.push_str("✅ Documentation coverage: 100% - All items documented!\n");
37 } else if self.coverage_percent >= 80.0 {
38 report.push_str(&format!(
39 "📝 Documentation coverage: {:.1}% - Good coverage\n",
40 self.coverage_percent
41 ));
42 } else {
43 report.push_str(&format!(
44 "⚠️ Documentation coverage: {:.1}% - Needs improvement\n",
45 self.coverage_percent
46 ));
47 }
48
49 if !self.missing.is_empty() {
50 report.push_str("\nMissing documentation for:\n");
51 for (i, item) in self.missing.iter().take(10).enumerate() {
52 report.push_str(&format!(" {}. {}\n", i + 1, item));
53 }
54 if self.missing.len() > 10 {
55 report.push_str(&format!(
56 " ... and {} more items\n",
57 self.missing.len() - 10
58 ));
59 }
60 }
61
62 report
63 }
64}
65
66pub async fn check_documentation_coverage(project_path: &Path) -> Result<DocCoverage> {
68 let output = Command::new("cargo")
70 .args(&[
71 "doc",
72 "--no-deps",
73 "--document-private-items",
74 "--message-format=json",
75 ])
76 .current_dir(project_path)
77 .output()
78 .map_err(|e| Error::process(format!("Failed to run cargo doc: {}", e)))?;
79
80 let stderr = String::from_utf8_lossy(&output.stderr);
81 let stdout = String::from_utf8_lossy(&output.stdout);
82
83 let mut missing = Vec::new();
85
86 for line in stdout.lines() {
87 if line.contains("missing_docs") {
88 if let Ok(json) = serde_json::from_str::<serde_json::Value>(line) {
89 if let Some(message) = json["message"]["rendered"].as_str() {
90 if let Some(item_match) = extract_item_name(message) {
92 missing.push(item_match);
93 }
94 }
95 }
96 }
97 }
98
99 let warning_re = Regex::new(r"warning: missing documentation for (.+)")
101 .map_err(|e| Error::validation(format!("Invalid regex: {}", e)))?;
102
103 for cap in warning_re.captures_iter(&stderr) {
104 missing.push(cap[1].to_string());
105 }
106
107 let (total, documented) = count_documentation_items(project_path).await?;
109
110 let coverage_percent = if total > 0 {
111 (documented as f32 / total as f32) * 100.0
112 } else {
113 100.0
114 };
115
116 Ok(DocCoverage {
117 total_items: total,
118 documented_items: documented,
119 coverage_percent,
120 missing,
121 })
122}
123
124async fn count_documentation_items(project_path: &Path) -> Result<(usize, usize)> {
126 let mut total = 0;
127 let mut documented = 0;
128
129 let walker = walkdir::WalkDir::new(project_path)
131 .into_iter()
132 .filter_map(|e| e.ok())
133 .filter(|e| {
134 e.path().extension().is_some_and(|ext| ext == "rs")
135 && !e.path().to_string_lossy().contains("target")
136 });
137
138 for entry in walker {
139 let content = tokio::fs::read_to_string(entry.path()).await?;
140 let (file_total, file_documented) = count_items_in_file(&content)?;
141 total += file_total;
142 documented += file_documented;
143 }
144
145 Ok((total, documented))
146}
147
148fn count_items_in_file(content: &str) -> Result<(usize, usize)> {
150 let mut total = 0;
151 let mut documented = 0;
152 let lines: Vec<&str> = content.lines().collect();
153
154 let pub_item_re = Regex::new(r"^\s*pub\s+(fn|struct|enum|trait|type|const|static|mod)\s+")
155 .map_err(|e| Error::validation(format!("Failed to compile regex: {}", e)))?;
156
157 for (i, line) in lines.iter().enumerate() {
158 if pub_item_re.is_match(line) {
159 total += 1;
160
161 if i > 0
163 && (lines[i - 1].trim().starts_with("///")
164 || lines[i - 1].trim().starts_with("//!"))
165 {
166 documented += 1;
167 }
168 }
169 }
170
171 Ok((total, documented))
172}
173
174fn extract_item_name(message: &str) -> Option<String> {
176 if let Some(start) = message.find('`') {
180 if let Some(end) = message[start + 1..].find('`') {
181 return Some(message[start + 1..start + 1 + end].to_string());
182 }
183 }
184
185 if let Some(pos) = message.find("for ") {
187 Some(message[pos + 4..].trim().to_string())
188 } else {
189 None
190 }
191}
192
193pub fn suggest_documentation(item_type: &str, item_name: &str) -> String {
195 match item_type {
196 "fn" | "function" => format!(
197 "/// TODO: Document function `{}`.\n\
198 ///\n\
199 /// # Arguments\n\
200 ///\n\
201 /// # Returns\n\
202 ///\n\
203 /// # Examples\n\
204 /// ```\n\
205 /// // Example usage\n\
206 /// ```",
207 item_name
208 ),
209 "struct" => format!(
210 "/// TODO: Document struct `{}`.\n\
211 ///\n\
212 /// # Fields\n\
213 ///\n\
214 /// # Examples\n\
215 /// ```\n\
216 /// // Example usage\n\
217 /// ```",
218 item_name
219 ),
220 "enum" => format!(
221 "/// TODO: Document enum `{}`.\n\
222 ///\n\
223 /// # Variants\n\
224 ///\n\
225 /// # Examples\n\
226 /// ```\n\
227 /// // Example usage\n\
228 /// ```",
229 item_name
230 ),
231 _ => format!("/// TODO: Document `{}`.", item_name),
232 }
233}
234
235#[cfg(test)]
236#[allow(clippy::expect_used, clippy::unwrap_used)]
237mod tests {
238 use super::*;
239
240 #[test]
241 fn test_count_items_in_file() {
242 let content = r"
243/// Documented function
244pub fn documented() {}
245
246pub fn undocumented() {}
247
248/// Documented struct
249pub struct DocStruct {}
250
251pub struct UndocStruct {}
252";
253 let (total, documented) = count_items_in_file(content).expect("Should count items");
254 assert_eq!(total, 4);
255 assert_eq!(documented, 2);
256 }
257
258 #[test]
259 fn test_coverage_calculation() {
260 let coverage = DocCoverage {
261 total_items: 10,
262 documented_items: 8,
263 coverage_percent: 80.0,
264 missing: vec![],
265 };
266
267 assert!(coverage.meets_threshold(75.0));
268 assert!(!coverage.meets_threshold(85.0));
269 }
270}