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