Skip to main content

features_cli/
scan.rs

1//! Unified scanning API for features
2//!
3//! This module provides a high-level interface for scanning features with configurable options.
4//! It consolidates the functionality from file_scanner and coverage_parser into a single,
5//! easy-to-use API.
6
7use anyhow::Result;
8use std::path::{Path, PathBuf};
9
10use crate::coverage_parser::{self, map_coverage_to_features, parse_coverage_reports};
11use crate::file_scanner::{list_files_recursive, list_files_recursive_with_changes};
12use crate::models::Feature;
13
14/// Configuration options for scanning features
15#[derive(Debug, Clone)]
16pub struct ScanConfig<'a> {
17    /// Whether to include git history (changes, commits, stats)
18    pub skip_changes: bool,
19
20    /// Whether to add coverage information to features
21    pub should_add_coverage: bool,
22
23    /// Optional override for coverage directory location
24    /// If None, will search in multiple default locations
25    pub coverage_dir_override: Option<&'a Path>,
26
27    /// Current working directory (used for finding coverage)
28    pub current_dir: &'a Path,
29
30    /// Optional project directory (used for finding coverage)
31    pub project_dir: Option<&'a Path>,
32
33    /// Paths to ignore (and all their subfolders) when scanning for features
34    pub ignore_paths: Vec<PathBuf>,
35}
36
37impl<'a> ScanConfig<'a> {
38    /// Create a new ScanConfig with minimal required parameters
39    pub fn new(current_dir: &'a Path) -> Self {
40        Self {
41            skip_changes: false,
42            should_add_coverage: false,
43            coverage_dir_override: None,
44            current_dir,
45            project_dir: None,
46            ignore_paths: Vec::new(),
47        }
48    }
49
50    /// Set whether to skip git history
51    pub fn skip_changes(mut self, skip: bool) -> Self {
52        self.skip_changes = skip;
53        self
54    }
55
56    /// Set whether to add coverage information
57    pub fn with_coverage(mut self, should_add: bool) -> Self {
58        self.should_add_coverage = should_add;
59        self
60    }
61
62    /// Set a specific coverage directory to use
63    pub fn coverage_dir(mut self, dir: &'a Path) -> Self {
64        self.coverage_dir_override = Some(dir);
65        self
66    }
67
68    /// Set the project directory for finding coverage
69    pub fn project_dir(mut self, dir: &'a Path) -> Self {
70        self.project_dir = Some(dir);
71        self
72    }
73
74    /// Set the paths to ignore (and all their subfolders) when scanning for features
75    pub fn ignore_paths(mut self, paths: Vec<PathBuf>) -> Self {
76        self.ignore_paths = paths;
77        self
78    }
79}
80
81/// Scan features in a directory with the given configuration
82///
83/// # Arguments
84///
85/// * `base_path` - The directory to scan for features
86/// * `config` - Configuration options for the scan
87///
88/// # Returns
89///
90/// A vector of Feature objects representing the discovered features
91///
92/// # Example
93///
94/// ```no_run
95/// use features_cli::scan::{scan_features, ScanConfig};
96/// use std::path::Path;
97///
98/// let current_dir = std::env::current_dir().unwrap();
99/// let config = ScanConfig::new(&current_dir)
100///     .skip_changes(false)
101///     .with_coverage(true);
102///
103/// let features = scan_features(Path::new("./src"), config).unwrap();
104/// println!("Found {} features", features.len());
105/// ```
106pub fn scan_features(base_path: &Path, config: ScanConfig) -> Result<Vec<Feature>> {
107    // Step 1: Scan features with or without git history
108    let mut features = if config.skip_changes {
109        list_files_recursive(base_path, &config.ignore_paths)?
110    } else {
111        list_files_recursive_with_changes(base_path, &config.ignore_paths)?
112    };
113
114    // Step 2: Add coverage if requested
115    if config.should_add_coverage {
116        add_coverage_to_features(
117            &mut features,
118            base_path,
119            config.coverage_dir_override,
120            config.current_dir,
121            config.project_dir,
122        );
123    }
124
125    Ok(features)
126}
127
128/// Add coverage information to features
129///
130/// This function searches for coverage reports in multiple locations and
131/// updates the features with coverage statistics.
132fn add_coverage_to_features(
133    features: &mut [Feature],
134    base_path: &Path,
135    coverage_dir_override: Option<&Path>,
136    current_dir: &Path,
137    project_dir: Option<&Path>,
138) {
139    let coverage_dirs = if let Some(override_dir) = coverage_dir_override {
140        // If override is provided, only use that directory
141        vec![override_dir.to_path_buf()]
142    } else {
143        // Check multiple locations:
144        // 1. .coverage and coverage in base_path
145        // 2. .coverage and coverage in current directory (where executable is run)
146        // 3. .coverage and coverage in project_dir (if provided)
147        let mut dirs = vec![
148            base_path.join(".coverage"),
149            base_path.join("coverage"),
150            current_dir.join(".coverage"),
151            current_dir.join("coverage"),
152        ];
153
154        // Add project_dir coverage directories if provided
155        if let Some(proj_dir) = project_dir {
156            let proj_coverage = proj_dir.join(".coverage");
157            let proj_coverage_plain = proj_dir.join("coverage");
158
159            // Only add if different from already added paths
160            if !dirs.contains(&proj_coverage) {
161                dirs.push(proj_coverage);
162            }
163            if !dirs.contains(&proj_coverage_plain) {
164                dirs.push(proj_coverage_plain);
165            }
166        }
167
168        dirs
169    };
170
171    for coverage_dir in &coverage_dirs {
172        // Parse coverage reports if the directory exists
173        if let Ok(coverage_map) = parse_coverage_reports(coverage_dir, base_path)
174            && !coverage_map.is_empty()
175        {
176            // Use coverage from the first directory found
177            let feature_coverage = map_coverage_to_features(features, coverage_map, base_path);
178            update_features_with_coverage(features, &feature_coverage);
179            break; // Stop after finding coverage in one directory
180        }
181    }
182}
183
184/// Recursively update features with coverage data
185fn update_features_with_coverage(
186    features: &mut [Feature],
187    feature_coverage: &std::collections::HashMap<String, coverage_parser::CoverageStats>,
188) {
189    for feature in features {
190        if let Some(coverage) = feature_coverage.get(&feature.path) {
191            // Update or create stats
192            if let Some(stats) = &mut feature.stats {
193                stats.coverage = Some(coverage.clone());
194            } else {
195                feature.stats = Some(crate::models::Stats {
196                    files_count: None,
197                    lines_count: None,
198                    todos_count: None,
199                    commits: std::collections::BTreeMap::new(),
200                    coverage: Some(coverage.clone()),
201                });
202            }
203        }
204
205        // Recursively update nested features
206        update_features_with_coverage(&mut feature.features, feature_coverage);
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use std::path::PathBuf;
214
215    #[test]
216    fn test_scan_config_builder() {
217        let current_dir = PathBuf::from("/tmp");
218        let project_dir = PathBuf::from("/project");
219
220        let config = ScanConfig::new(&current_dir)
221            .skip_changes(true)
222            .with_coverage(true)
223            .project_dir(&project_dir);
224
225        assert!(config.skip_changes);
226        assert!(config.should_add_coverage);
227        assert!(config.project_dir.is_some());
228    }
229
230    #[test]
231    fn test_scan_config_defaults() {
232        let current_dir = PathBuf::from("/tmp");
233        let config = ScanConfig::new(&current_dir);
234
235        assert!(!config.skip_changes);
236        assert!(!config.should_add_coverage);
237        assert!(config.coverage_dir_override.is_none());
238        assert!(config.project_dir.is_none());
239    }
240
241    #[test]
242    fn test_scan_features_basic() {
243        let test_path = PathBuf::from("../../examples/tests_skip_changes/src");
244
245        if !test_path.exists() {
246            println!("Skipping test - test path does not exist");
247            return;
248        }
249
250        let current_dir = std::env::current_dir().unwrap();
251        let config = ScanConfig::new(&current_dir).skip_changes(true);
252
253        let result = scan_features(&test_path, config);
254        assert!(result.is_ok(), "Failed to scan features");
255
256        let features = result.unwrap();
257        assert!(!features.is_empty(), "Should find at least one feature");
258    }
259
260    #[test]
261    fn test_scan_features_with_changes() {
262        let test_path = PathBuf::from("../../examples/tests-with-changes/src");
263
264        if !test_path.exists() {
265            println!("Skipping test - test path does not exist");
266            return;
267        }
268
269        let current_dir = std::env::current_dir().unwrap();
270        let config = ScanConfig::new(&current_dir).skip_changes(false);
271
272        let result = scan_features(&test_path, config);
273        assert!(result.is_ok(), "Failed to scan features with changes");
274
275        let features = result.unwrap();
276        assert!(!features.is_empty(), "Should find at least one feature");
277
278        // At least one feature should have changes
279        let has_changes = features.iter().any(|f| !f.changes.is_empty());
280        assert!(has_changes, "At least one feature should have git history");
281    }
282}