ferrous_forge/
doc_coverage.rs

1//! Documentation coverage checking module
2//!
3//! This module provides functionality to check documentation coverage
4//! for Rust projects, ensuring all public APIs are properly documented.
5
6use crate::{Error, Result};
7use regex::Regex;
8use serde::{Deserialize, Serialize};
9use std::path::Path;
10use std::process::Command;
11
12/// Documentation coverage report
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct DocCoverage {
15    /// Total number of documentable items
16    pub total_items: usize,
17    /// Number of documented items
18    pub documented_items: usize,
19    /// Coverage percentage
20    pub coverage_percent: f32,
21    /// List of items missing documentation
22    pub missing: Vec<String>,
23}
24
25impl DocCoverage {
26    /// Check if coverage meets minimum threshold
27    pub fn meets_threshold(&self, min_coverage: f32) -> bool {
28        self.coverage_percent >= min_coverage
29    }
30
31    /// Generate a human-readable report
32    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
66/// Check documentation coverage for a Rust project
67pub async fn check_documentation_coverage(project_path: &Path) -> Result<DocCoverage> {
68    // Run cargo doc with JSON output to get warnings
69    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    // Parse JSON messages for missing docs warnings
84    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                    // Extract the item name from the message
91                    if let Some(item_match) = extract_item_name(message) {
92                        missing.push(item_match);
93                    }
94                }
95            }
96        }
97    }
98
99    // Also check stderr for traditional warnings
100    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    // Count public items by parsing the source
108    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
124/// Count documentation items in the project
125async fn count_documentation_items(project_path: &Path) -> Result<(usize, usize)> {
126    let mut total = 0;
127    let mut documented = 0;
128
129    // Walk through all Rust files
130    let walker = walkdir::WalkDir::new(project_path)
131        .into_iter()
132        .filter_map(|e| e.ok())
133        .filter(|e| {
134            e.path().extension().map_or(false, |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
148/// Count documentation items in a single file
149fn 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            // Check if there's documentation above this line
162            if i > 0 && (lines[i - 1].trim().starts_with("///") || 
163                        lines[i - 1].trim().starts_with("//!")) {
164                documented += 1;
165            }
166        }
167    }
168    
169    Ok((total, documented))
170}
171
172/// Extract item name from error message
173fn extract_item_name(message: &str) -> Option<String> {
174    // Try to extract the item name from messages like:
175    // "missing documentation for a struct"
176    // "missing documentation for function `foo`"
177    if let Some(start) = message.find('`') {
178        if let Some(end) = message[start + 1..].find('`') {
179            return Some(message[start + 1..start + 1 + end].to_string());
180        }
181    }
182    
183    // Fallback: extract type after "for"
184    if let Some(pos) = message.find("for ") {
185        Some(message[pos + 4..].trim().to_string())
186    } else {
187        None
188    }
189}
190
191/// Suggest documentation for missing items
192pub fn suggest_documentation(item_type: &str, item_name: &str) -> String {
193    match item_type {
194        "fn" | "function" => format!(
195            "/// TODO: Document function `{}`.\n\
196             ///\n\
197             /// # Arguments\n\
198             ///\n\
199             /// # Returns\n\
200             ///\n\
201             /// # Examples\n\
202             /// ```\n\
203             /// // Example usage\n\
204             /// ```",
205            item_name
206        ),
207        "struct" => format!(
208            "/// TODO: Document struct `{}`.\n\
209             ///\n\
210             /// # Fields\n\
211             ///\n\
212             /// # Examples\n\
213             /// ```\n\
214             /// // Example usage\n\
215             /// ```",
216            item_name
217        ),
218        "enum" => format!(
219            "/// TODO: Document enum `{}`.\n\
220             ///\n\
221             /// # Variants\n\
222             ///\n\
223             /// # Examples\n\
224             /// ```\n\
225             /// // Example usage\n\
226             /// ```",
227            item_name
228        ),
229        _ => format!("/// TODO: Document `{}`.", item_name),
230    }
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    #[test]
238    fn test_count_items_in_file() {
239        let content = r#"
240/// Documented function
241pub fn documented() {}
242
243pub fn undocumented() {}
244
245/// Documented struct
246pub struct DocStruct {}
247
248pub struct UndocStruct {}
249"#;
250        let (total, documented) = count_items_in_file(content).unwrap();
251        assert_eq!(total, 4);
252        assert_eq!(documented, 2);
253    }
254
255    #[test]
256    fn test_coverage_calculation() {
257        let coverage = DocCoverage {
258            total_items: 10,
259            documented_items: 8,
260            coverage_percent: 80.0,
261            missing: vec![],
262        };
263        
264        assert!(coverage.meets_threshold(75.0));
265        assert!(!coverage.meets_threshold(85.0));
266    }
267}