Skip to main content

features_cli/
file_scanner.rs

1use anyhow::{Context, Result};
2use git2::Repository;
3use std::cell::RefCell;
4use std::collections::{BTreeMap, HashMap};
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::rc::Rc;
8
9use crate::dependency_resolver::{
10    build_file_to_feature_map, collect_feature_info, resolve_feature_dependencies,
11};
12use crate::feature_metadata_detector::{self, FeatureMetadataMap};
13use crate::features_toml_parser::{find_features_toml, read_features_toml};
14use crate::git_helper::{CommitHistory, get_all_commits_by_path};
15use crate::import_detector::{ImportStatement, build_file_map, scan_file_for_imports};
16use crate::models::{Change, Feature, Stats};
17use crate::readme_parser::{ReadmeInfo, parse_readme_info, read_readme_info};
18use crate::skip_dirs::SKIPPED_DIRS;
19
20fn is_documentation_directory(dir_path: &Path) -> bool {
21    let dir_name = dir_path
22        .file_name()
23        .and_then(|name| name.to_str())
24        .unwrap_or("");
25
26    // Common documentation directory names
27    let doc_dirs = ["docs", "__docs__", ".docs"];
28
29    doc_dirs.contains(&dir_name.to_lowercase().as_str())
30}
31
32fn is_inside_documentation_directory(dir_path: &Path) -> bool {
33    // Check if any parent directory is a documentation directory
34    for ancestor in dir_path.ancestors().skip(1) {
35        if is_documentation_directory(ancestor) {
36            return true;
37        }
38    }
39    false
40}
41
42fn is_direct_subfolder_of_features(dir_path: &Path) -> bool {
43    if let Some(parent) = dir_path.parent()
44        && let Some(parent_name) = parent.file_name().and_then(|name| name.to_str())
45    {
46        return parent_name == "features";
47    }
48    false
49}
50
51/// Check if a directory is ignored, i.e. matches (or is nested inside) one of the
52/// paths passed via `--ignore-path`. Ignored directories and all their subfolders
53/// are excluded from feature detection entirely.
54fn is_ignored_path(dir_path: &Path, ignore_paths: &[PathBuf]) -> bool {
55    if ignore_paths.is_empty() {
56        return false;
57    }
58
59    let Ok(canonical) = fs::canonicalize(dir_path) else {
60        return false;
61    };
62
63    ignore_paths
64        .iter()
65        .any(|ignored| canonical.starts_with(ignored))
66}
67
68/// Decides which folders the feature, stats and import walkers leave out
69#[derive(Clone, Copy)]
70struct WalkFilter<'a> {
71    ignore_paths: &'a [PathBuf],
72    /// Scan the folders in `SKIPPED_DIRS` instead of skipping them
73    include_skipped_dirs: bool,
74}
75
76impl WalkFilter<'_> {
77    fn skips(&self, dir_path: &Path) -> bool {
78        let is_skipped_name = !self.include_skipped_dirs
79            && dir_path
80                .file_name()
81                .and_then(|name| name.to_str())
82                .is_some_and(|name| SKIPPED_DIRS.contains(&name));
83
84        is_skipped_name || is_ignored_path(dir_path, self.ignore_paths)
85    }
86}
87
88fn find_readme_file(dir_path: &Path) -> Option<std::path::PathBuf> {
89    let readme_candidates = ["README.md", "README.mdx"];
90
91    for candidate in &readme_candidates {
92        let readme_path = dir_path.join(candidate);
93        if readme_path.exists() {
94            return Some(readme_path);
95        }
96    }
97
98    None
99}
100
101/// A directory's README, read and parsed at most once per scan
102struct Readme {
103    path: PathBuf,
104    /// None when the file exists but can't be read as text
105    info: Option<ReadmeInfo>,
106}
107
108#[derive(Default)]
109struct ReadmeCache(RefCell<HashMap<PathBuf, Option<Rc<Readme>>>>);
110
111impl ReadmeCache {
112    fn get(&self, dir_path: &Path) -> Option<Rc<Readme>> {
113        if let Some(cached) = self.0.borrow().get(dir_path) {
114            return cached.clone();
115        }
116
117        let readme = find_readme_file(dir_path).map(|path| {
118            let info = fs::read_to_string(&path)
119                .ok()
120                .map(|content| parse_readme_info(&content));
121            Rc::new(Readme { path, info })
122        });
123
124        self.0
125            .borrow_mut()
126            .insert(dir_path.to_path_buf(), readme.clone());
127        readme
128    }
129
130    /// The `feature` boolean from a directory's README front matter, if present.
131    fn feature_flag(&self, dir_path: &Path) -> Option<bool> {
132        self.get(dir_path)?.info.as_ref()?.feature_flag
133    }
134}
135
136/// Check if a directory should be treated as a feature
137fn is_feature_directory(dir_path: &Path, readmes: &ReadmeCache) -> bool {
138    // Skip documentation directories
139    if is_documentation_directory(dir_path) || is_inside_documentation_directory(dir_path) {
140        return false;
141    }
142
143    // An explicit `feature: false` in the README always skips this directory
144    // from being a feature itself, even if it would otherwise qualify (e.g. a
145    // direct subfolder of `features`). Its own subfolders are still scanned
146    // normally, so any nested features it contains are kept.
147    let feature_flag = readmes.feature_flag(dir_path);
148    if feature_flag == Some(false) {
149        return false;
150    }
151
152    // Check if it's a direct subfolder of "features" (existing behavior)
153    if is_direct_subfolder_of_features(dir_path) {
154        return true;
155    }
156
157    // Check if the directory has a README with feature: true
158    feature_flag == Some(true)
159}
160
161/// Inputs shared by every level of the recursive feature scan
162#[derive(Clone, Copy)]
163struct ScanContext<'a> {
164    base_path: &'a Path,
165    history: Option<&'a CommitHistory>,
166    feature_metadata_map: &'a FeatureMetadataMap,
167    filter: WalkFilter<'a>,
168    readmes: &'a ReadmeCache,
169    /// Skip everything not needed to resolve feature ownership
170    ownership_only: bool,
171}
172
173pub fn list_files_recursive(
174    dir: &Path,
175    ignore_paths: &[PathBuf],
176    include_skipped_dirs: bool,
177) -> Result<Vec<Feature>> {
178    // Scan entire base_path for feature metadata once
179    let feature_metadata =
180        feature_metadata_detector::scan_directory_for_feature_metadata(dir).unwrap_or_default();
181
182    // First pass: build feature structure without dependencies
183    let filter = WalkFilter {
184        ignore_paths,
185        include_skipped_dirs,
186    };
187    let readmes = ReadmeCache::default();
188    let ctx = ScanContext {
189        base_path: dir,
190        history: None,
191        feature_metadata_map: &feature_metadata,
192        filter,
193        readmes: &readmes,
194        ownership_only: false,
195    };
196    let mut features = list_files_recursive_impl(dir, None, &ctx)?;
197
198    // Second pass: scan for imports and resolve dependencies
199    populate_dependencies(&mut features, dir, &ctx)?;
200
201    Ok(features)
202}
203
204/// Build the feature tree with only what is needed to know who owns what:
205/// name, owner, path, meta from README/FEATURES.toml and nested features.
206///
207/// Skips everything that reads source files or git history (changes, stats,
208/// decisions, feature metadata comments and dependencies), which makes it
209/// suitable for CODEOWNERS generation on large repositories.
210pub fn list_features_ownership_only(
211    dir: &Path,
212    ignore_paths: &[PathBuf],
213    include_skipped_dirs: bool,
214) -> Result<Vec<Feature>> {
215    let feature_metadata = FeatureMetadataMap::new();
216
217    let filter = WalkFilter {
218        ignore_paths,
219        include_skipped_dirs,
220    };
221    let readmes = ReadmeCache::default();
222    let ctx = ScanContext {
223        base_path: dir,
224        history: None,
225        feature_metadata_map: &feature_metadata,
226        filter,
227        readmes: &readmes,
228        ownership_only: true,
229    };
230    list_files_recursive_impl(dir, None, &ctx)
231}
232
233pub fn list_files_recursive_with_changes(
234    dir: &Path,
235    ignore_paths: &[PathBuf],
236    include_skipped_dirs: bool,
237) -> Result<Vec<Feature>> {
238    // Get all commits once at the beginning for efficiency
239    let history = get_all_commits_by_path(dir).unwrap_or_default();
240    // Scan entire base_path for feature metadata once
241    let feature_metadata =
242        feature_metadata_detector::scan_directory_for_feature_metadata(dir).unwrap_or_default();
243
244    // First pass: build feature structure without dependencies
245    let filter = WalkFilter {
246        ignore_paths,
247        include_skipped_dirs,
248    };
249    let readmes = ReadmeCache::default();
250    let ctx = ScanContext {
251        base_path: dir,
252        history: Some(&history),
253        feature_metadata_map: &feature_metadata,
254        filter,
255        readmes: &readmes,
256        ownership_only: false,
257    };
258    let mut features = list_files_recursive_impl(dir, None, &ctx)?;
259
260    // Second pass: scan for imports and resolve dependencies
261    populate_dependencies(&mut features, dir, &ctx)?;
262
263    Ok(features)
264}
265
266/// Populate dependencies for all features by scanning imports
267fn populate_dependencies(
268    features: &mut [Feature],
269    base_path: &Path,
270    ctx: &ScanContext,
271) -> Result<()> {
272    // Build file map for quick path resolution
273    let file_map = build_file_map(base_path);
274
275    // Collect all feature info (flat list with paths)
276    let mut feature_info_list = Vec::new();
277    collect_feature_info(features, None, &mut feature_info_list);
278
279    // Build file-to-feature mapping
280    let file_to_feature_map = build_file_to_feature_map(&feature_info_list, base_path);
281
282    // Build feature path to name mapping (path is the unique identifier)
283    let mut feature_path_to_name_map = HashMap::new();
284    for info in &feature_info_list {
285        feature_path_to_name_map.insert(info.path.to_string_lossy().to_string(), info.name.clone());
286    }
287
288    // Scan all files in each feature for imports
289    let mut feature_imports: HashMap<String, Vec<ImportStatement>> = HashMap::new();
290
291    for feature_info in &feature_info_list {
292        let feature_path = base_path.join(&feature_info.path);
293        let imports = scan_feature_directory_for_imports(&feature_path, ctx);
294        // Use feature path as key instead of name to handle features with duplicate names
295        feature_imports.insert(feature_info.path.to_string_lossy().to_string(), imports);
296    }
297
298    // Now populate dependencies in the feature tree
299    populate_dependencies_recursive(
300        features,
301        base_path,
302        &feature_imports,
303        &file_to_feature_map,
304        &feature_path_to_name_map,
305        &file_map,
306    );
307
308    Ok(())
309}
310
311/// Scan a feature directory for all import statements
312fn scan_feature_directory_for_imports(
313    feature_path: &Path,
314    ctx: &ScanContext,
315) -> Vec<ImportStatement> {
316    let mut all_imports = Vec::new();
317
318    if let Ok(entries) = fs::read_dir(feature_path) {
319        // Collect and sort entries alphabetically by filename
320        let mut paths: Vec<_> = entries.flatten().map(|e| e.path()).collect();
321        paths.sort_by(|a, b| {
322            let name_a = a.file_name().unwrap_or_default().to_string_lossy();
323            let name_b = b.file_name().unwrap_or_default().to_string_lossy();
324            name_a.cmp(&name_b)
325        });
326
327        for path in paths {
328            // Skip documentation directories
329            if is_documentation_directory(&path) {
330                continue;
331            }
332
333            if path.is_file() {
334                if let Ok(imports) = scan_file_for_imports(&path) {
335                    all_imports.extend(imports);
336                }
337            } else if path.is_dir() {
338                // Skip 'features' subdirectory (contains nested features)
339                let dir_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
340                if dir_name == "features" || ctx.filter.skips(&path) {
341                    continue;
342                }
343
344                // Skip nested feature directories (check if it's a direct child of "features" directory with README)
345                if is_feature_directory(&path, ctx.readmes) {
346                    continue;
347                }
348
349                // Recursively scan subdirectories
350                let nested_imports = scan_feature_directory_for_imports(&path, ctx);
351                all_imports.extend(nested_imports);
352            }
353        }
354    }
355
356    all_imports
357}
358
359/// Recursively populate dependencies in the feature tree
360fn populate_dependencies_recursive(
361    features: &mut [Feature],
362    base_path: &Path,
363    feature_imports: &HashMap<String, Vec<ImportStatement>>,
364    file_to_feature_map: &HashMap<std::path::PathBuf, String>,
365    feature_path_to_name_map: &HashMap<String, String>,
366    file_map: &HashMap<String, std::path::PathBuf>,
367) {
368    for feature in features {
369        // Get imports for this feature using path as key (not name, since multiple features can have same name)
370        if let Some(imports) = feature_imports.get(&feature.path) {
371            let feature_path = std::path::PathBuf::from(&feature.path);
372
373            // Resolve dependencies
374            let dependencies = resolve_feature_dependencies(
375                &feature.name,
376                &feature_path,
377                base_path,
378                imports,
379                file_to_feature_map,
380                feature_path_to_name_map,
381                file_map,
382            );
383
384            feature.dependencies = dependencies;
385        }
386
387        // Recursively process nested features
388        if !feature.features.is_empty() {
389            populate_dependencies_recursive(
390                &mut feature.features,
391                base_path,
392                feature_imports,
393                file_to_feature_map,
394                feature_path_to_name_map,
395                file_map,
396            );
397        }
398    }
399}
400
401fn read_decision_files(feature_path: &Path) -> Result<Vec<String>> {
402    let mut decisions = Vec::new();
403
404    // Check both "decision" and "decisions" folder names
405    let decision_paths = [
406        feature_path.join(".docs").join("decisions"),
407        feature_path.join("__docs__").join("decisions"),
408    ];
409
410    for decisions_dir in &decision_paths {
411        if decisions_dir.exists() && decisions_dir.is_dir() {
412            let entries = fs::read_dir(decisions_dir).with_context(|| {
413                format!(
414                    "could not read decisions directory `{}`",
415                    decisions_dir.display()
416                )
417            })?;
418
419            // Collect all decision file paths first
420            let mut decision_paths_vec = Vec::new();
421
422            for entry in entries {
423                let entry = entry?;
424                let path = entry.path();
425
426                // Skip README.md files and only process .md files
427                if path.is_file()
428                    && let Some(file_name) = path.file_name()
429                {
430                    let file_name_str = file_name.to_string_lossy();
431                    if file_name_str.ends_with(".md") && file_name_str != "README.md" {
432                        decision_paths_vec.push(path);
433                    }
434                }
435            }
436
437            // Sort decision files alphabetically by filename
438            decision_paths_vec.sort_by(|a, b| {
439                let name_a = a.file_name().unwrap_or_default().to_string_lossy();
440                let name_b = b.file_name().unwrap_or_default().to_string_lossy();
441                name_a.cmp(&name_b)
442            });
443
444            // Read the sorted files
445            for path in decision_paths_vec {
446                let content = fs::read_to_string(&path).with_context(|| {
447                    format!("could not read decision file `{}`", path.display())
448                })?;
449                decisions.push(content);
450            }
451
452            break; // If we found one of the directories, don't check the other
453        }
454    }
455
456    Ok(decisions)
457}
458
459/// File, line and TODO totals for a feature directory
460#[derive(Default)]
461struct FileCounts {
462    files: usize,
463    lines: usize,
464    todos: usize,
465}
466
467/// Case-insensitive search for "TODO", without allocating
468fn contains_todo(line: &str) -> bool {
469    line.as_bytes()
470        .windows(4)
471        .any(|window| window.eq_ignore_ascii_case(b"TODO"))
472}
473
474/// Count files, lines and TODO comments in a feature directory (excluding
475/// documentation), reading each file once
476fn count_feature_files(
477    dir: &Path,
478    nested_feature_paths: &[String],
479    filter: &WalkFilter,
480    counts: &mut FileCounts,
481) {
482    let Ok(entries) = fs::read_dir(dir) else {
483        return;
484    };
485
486    for entry in entries.flatten() {
487        let path = entry.path();
488
489        // Skip documentation directories
490        if is_documentation_directory(&path) {
491            continue;
492        }
493
494        // Skip nested feature directories
495        let path_str = path.to_string_lossy();
496        if nested_feature_paths
497            .iter()
498            .any(|nfp| path_str.starts_with(nfp.as_str()))
499        {
500            continue;
501        }
502
503        if path.is_file() {
504            counts.files += 1;
505
506            // Files that aren't text only count towards the number of files
507            if let Ok(content) = fs::read_to_string(&path) {
508                for line in content.lines() {
509                    counts.lines += 1;
510                    if contains_todo(line) {
511                        counts.todos += 1;
512                    }
513                }
514            }
515        } else if path.is_dir() && !filter.skips(&path) {
516            count_feature_files(&path, nested_feature_paths, filter, counts);
517        }
518    }
519}
520
521/// A feature's changes and where it sits in its repository
522struct FeatureHistory {
523    changes: Vec<Change>,
524    repo_workdir: PathBuf,
525    relative_path: String,
526}
527
528/// Compute commit statistics for a feature
529fn compute_commit_stats(
530    feature_history: &FeatureHistory,
531    history: &CommitHistory,
532    nested_features: &[Feature],
533) -> BTreeMap<String, serde_json::Value> {
534    // Convert nested feature paths to repo-relative paths once for all commits
535    let nested_relative_paths: Vec<String> = nested_features
536        .iter()
537        .filter_map(|feature| {
538            let canonical = fs::canonicalize(&feature.path).ok()?;
539            let relative = canonical.strip_prefix(&feature_history.repo_workdir).ok()?;
540            Some(relative.to_string_lossy().to_string())
541        })
542        .collect();
543
544    // Filter changes to only include those that affect files in this feature
545    // (not exclusively in nested features)
546    let filtered_changes: Vec<&Change> = feature_history
547        .changes
548        .iter()
549        .filter(|change| {
550            let Some(affected_files) = history.affected_paths.get(&change.hash) else {
551                return false;
552            };
553
554            // Check if any affected file is in this feature but not in a nested feature
555            affected_files.iter().any(|file_path| {
556                file_path.starts_with(&feature_history.relative_path)
557                    && !nested_relative_paths
558                        .iter()
559                        .any(|nested_path| file_path.starts_with(nested_path.as_str()))
560            })
561        })
562        .collect();
563
564    let mut commits = BTreeMap::new();
565
566    // Add total commit count
567    commits.insert(
568        "total_commits".to_string(),
569        serde_json::json!(filtered_changes.len()),
570    );
571
572    // Count commits by author
573    let mut authors_count: HashMap<String, usize> = HashMap::new();
574    for change in &filtered_changes {
575        *authors_count.entry(change.author_name.clone()).or_insert(0) += 1;
576    }
577    commits.insert(
578        "authors_count".to_string(),
579        serde_json::json!(authors_count),
580    );
581
582    // Count commits by conventional commit type
583    let mut count_by_type: HashMap<String, usize> = HashMap::new();
584    for change in &filtered_changes {
585        let commit_type = extract_commit_type(&change.title);
586        *count_by_type.entry(commit_type).or_insert(0) += 1;
587    }
588    commits.insert(
589        "count_by_type".to_string(),
590        serde_json::json!(count_by_type),
591    );
592
593    // Get first and last commit dates
594    if let Some(first) = filtered_changes.first() {
595        commits.insert(
596            "first_commit_date".to_string(),
597            serde_json::json!(first.date.clone()),
598        );
599    }
600    if let Some(last) = filtered_changes.last() {
601        commits.insert(
602            "last_commit_date".to_string(),
603            serde_json::json!(last.date.clone()),
604        );
605    }
606
607    commits
608}
609
610/// Extract the commit type from a conventional commit title
611fn extract_commit_type(title: &str) -> String {
612    // Common conventional commit types
613    let known_types = [
614        "feat", "fix", "docs", "style", "refactor", "perf", "test", "build", "ci", "chore",
615        "revert",
616    ];
617
618    // Check if the title follows conventional commit format (type: description or type(scope): description)
619    if let Some(colon_pos) = title.find(':') {
620        let prefix = &title[..colon_pos];
621
622        // Remove scope if present (e.g., "feat(auth)" -> "feat")
623        let type_part = if let Some(paren_pos) = prefix.find('(') {
624            &prefix[..paren_pos]
625        } else {
626            prefix
627        };
628
629        let type_part = type_part.trim().to_lowercase();
630
631        // Check if it's a known conventional commit type
632        if known_types.contains(&type_part.as_str()) {
633            return type_part;
634        }
635    }
636
637    // If not a conventional commit, return "other"
638    "other".to_string()
639}
640
641fn process_feature_directory(
642    path: &Path,
643    name: &str,
644    parent_owner: Option<&str>,
645    ctx: &ScanContext,
646) -> Result<Feature> {
647    let ScanContext {
648        base_path,
649        history,
650        feature_metadata_map,
651        filter,
652        readmes,
653        ownership_only,
654    } = *ctx;
655
656    // First try to find and read FEATURES.toml file
657    let (title, owner, description, mut meta) = if let Some(toml_path) = find_features_toml(path) {
658        if let Ok(toml_data) = read_features_toml(&toml_path) {
659            (
660                toml_data.name,
661                toml_data.owner.unwrap_or_default(),
662                toml_data.description.unwrap_or_default(),
663                toml_data.meta,
664            )
665        } else {
666            (
667                None,
668                String::new(),
669                String::new(),
670                std::collections::BTreeMap::new(),
671            )
672        }
673    } else {
674        // Fall back to README file if FEATURES.toml not found
675        let readme_info = match readmes.get(path) {
676            Some(readme) => match &readme.info {
677                Some(info) => info.clone(),
678                // Read it again to report why it can't be read
679                None => read_readme_info(&readme.path)?,
680            },
681            None => ReadmeInfo::default(),
682        };
683        (
684            readme_info.title,
685            readme_info.owner,
686            readme_info.description,
687            readme_info.meta,
688        )
689    };
690
691    // Remove the 'feature' key from meta if it exists (it's redundant since we know it's a feature)
692    meta.remove("feature");
693
694    // Get the relative path to this feature directory for metadata lookup
695    let relative_path = path
696        .strip_prefix(base_path)
697        .unwrap_or(path)
698        .to_string_lossy()
699        .to_string();
700
701    // Check if this feature has any metadata from the global scan (matched by feature path)
702    if let Some(metadata_map) = feature_metadata_map.get(&relative_path) {
703        // Iterate through each metadata key (e.g., "feature-flag", "feature-experiment")
704        for (metadata_key, flags) in metadata_map {
705            // Convert Vec<HashMap<String, String>> to JSON array
706            let flags_json: Vec<serde_json::Value> = flags
707                .iter()
708                .map(|flag_map| {
709                    let json_map: serde_json::Map<String, serde_json::Value> = flag_map
710                        .iter()
711                        .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
712                        .collect();
713                    serde_json::Value::Object(json_map)
714                })
715                .collect();
716
717            // Check if this metadata key already exists, append if it does
718            meta.entry(metadata_key.clone())
719                .and_modify(|existing| {
720                    if let serde_json::Value::Array(arr) = existing {
721                        arr.extend(flags_json.clone());
722                    }
723                })
724                .or_insert_with(|| serde_json::Value::Array(flags_json));
725        }
726    }
727
728    // Convert the absolute path to a repo-relative path and look up changes
729    let feature_history = history.and_then(|h| get_feature_history(path, h).ok());
730
731    // Always include decisions regardless of include_changes flag
732    let decisions = if ownership_only {
733        Vec::new()
734    } else {
735        read_decision_files(path).unwrap_or_default()
736    };
737
738    // Determine the actual owner and whether it's inherited
739    let (actual_owner, is_owner_inherited) = if owner.is_empty() {
740        if let Some(parent) = parent_owner {
741            (parent.to_string(), true)
742        } else {
743            ("".to_string(), false)
744        }
745    } else {
746        (owner.clone(), false)
747    };
748
749    // Check if this feature has nested features in a 'features' subdirectory
750    let nested_features_path = path.join("features");
751    let mut nested_features = if nested_features_path.exists()
752        && nested_features_path.is_dir()
753        && !filter.skips(&nested_features_path)
754    {
755        list_files_recursive_impl(&nested_features_path, Some(&actual_owner), ctx)
756            .unwrap_or_default()
757    } else {
758        Vec::new()
759    };
760
761    // Also check for nested features marked with feature: true in subdirectories
762    let entries = fs::read_dir(path)
763        .with_context(|| format!("could not read directory `{}`", path.display()))?;
764
765    let mut entries: Vec<_> = entries.collect::<Result<_, _>>()?;
766    entries.sort_by_key(|entry| entry.path());
767
768    for entry in entries {
769        let entry_path = entry.path();
770        let entry_name = entry_path.file_name().unwrap().to_string_lossy();
771
772        if entry_path.is_dir()
773            && entry_name != "features" // Don't process 'features' folder twice
774            && !is_documentation_directory(&entry_path)
775            && !filter.skips(&entry_path)
776        {
777            if readmes.feature_flag(&entry_path) == Some(true) {
778                // This directory is a feature itself
779                let nested_feature =
780                    process_feature_directory(&entry_path, &entry_name, Some(&actual_owner), ctx)?;
781                nested_features.push(nested_feature);
782            } else {
783                // This directory is not a feature, but might contain features
784                // Recursively search for features inside it
785                let deeper_features =
786                    list_files_recursive_impl(&entry_path, Some(&actual_owner), ctx)?;
787                nested_features.extend(deeper_features);
788            }
789        }
790    }
791
792    let stats = if ownership_only {
793        None
794    } else {
795        // Collect paths of nested features to exclude from file/line counts
796        let nested_feature_paths: Vec<String> =
797            nested_features.iter().map(|f| f.path.clone()).collect();
798
799        let mut counts = FileCounts::default();
800        count_feature_files(path, &nested_feature_paths, &filter, &mut counts);
801
802        // Commit statistics are only available if the feature has changes
803        let commits = match (&feature_history, history) {
804            (Some(feature_history), Some(history)) if !feature_history.changes.is_empty() => {
805                compute_commit_stats(feature_history, history, &nested_features)
806            }
807            _ => BTreeMap::new(),
808        };
809
810        Some(Stats {
811            files_count: Some(counts.files),
812            lines_count: Some(counts.lines),
813            todos_count: Some(counts.todos),
814            commits,
815            coverage: None,
816        })
817    };
818
819    // Make path relative to base_path
820    let relative_path = path
821        .strip_prefix(base_path)
822        .unwrap_or(path)
823        .to_string_lossy()
824        .to_string();
825
826    Ok(Feature {
827        name: title.unwrap_or_else(|| name.to_string()),
828        description,
829        owner: actual_owner,
830        is_owner_inherited,
831        path: relative_path,
832        features: nested_features,
833        meta,
834        changes: feature_history.map(|fh| fh.changes).unwrap_or_default(),
835        decisions,
836        stats,
837        dependencies: Vec::new(), // Will be populated in second pass
838    })
839}
840
841fn list_files_recursive_impl(
842    dir: &Path,
843    parent_owner: Option<&str>,
844    ctx: &ScanContext,
845) -> Result<Vec<Feature>> {
846    let entries = fs::read_dir(dir)
847        .with_context(|| format!("could not read directory `{}`", dir.display()))?;
848
849    let mut entries: Vec<_> = entries.collect::<Result<_, _>>()?;
850    entries.sort_by_key(|entry| entry.path());
851
852    let mut features: Vec<Feature> = Vec::new();
853
854    for entry in entries {
855        let path = entry.path();
856        let name = path.file_name().unwrap().to_string_lossy();
857
858        if path.is_dir() {
859            if ctx.filter.skips(&path) {
860                continue;
861            }
862
863            if is_feature_directory(&path, ctx.readmes) {
864                let feature = process_feature_directory(&path, &name, parent_owner, ctx)?;
865                features.push(feature);
866            } else if !is_documentation_directory(&path)
867                && !is_inside_documentation_directory(&path)
868            {
869                // Recursively search for features in non-documentation subdirectories
870                let new_features = list_files_recursive_impl(&path, parent_owner, ctx)?;
871                features.extend(new_features);
872            }
873        }
874    }
875
876    Ok(features)
877}
878
879/// Get a feature's changes from the pre-computed commit history
880fn get_feature_history(path: &Path, history: &CommitHistory) -> Result<FeatureHistory> {
881    // Canonicalize the path
882    let canonical_path = std::fs::canonicalize(path)?;
883
884    // Find the repository and get the working directory
885    let repo = Repository::discover(path)?;
886    let repo_workdir = repo
887        .workdir()
888        .context("repository has no working directory")?;
889
890    // Convert to relative path from repo root
891    let relative_path = canonical_path
892        .strip_prefix(repo_workdir)
893        .context("path is not within repository")?
894        .to_string_lossy()
895        .to_string();
896
897    // Look up the changes in the map
898    let changes = history
899        .changes_by_path
900        .get(&relative_path)
901        .cloned()
902        .unwrap_or_default();
903
904    Ok(FeatureHistory {
905        changes,
906        repo_workdir: repo_workdir.to_path_buf(),
907        relative_path,
908    })
909}
910
911#[cfg(test)]
912mod tests {
913    use super::*;
914
915    #[test]
916    fn test_extract_commit_type() {
917        // Test standard conventional commit types
918        assert_eq!(extract_commit_type("feat: add new feature"), "feat");
919        assert_eq!(extract_commit_type("fix: resolve bug"), "fix");
920        assert_eq!(extract_commit_type("docs: update README"), "docs");
921        assert_eq!(extract_commit_type("style: format code"), "style");
922        assert_eq!(
923            extract_commit_type("refactor: improve structure"),
924            "refactor"
925        );
926        assert_eq!(extract_commit_type("perf: optimize performance"), "perf");
927        assert_eq!(extract_commit_type("test: add unit tests"), "test");
928        assert_eq!(extract_commit_type("build: update dependencies"), "build");
929        assert_eq!(extract_commit_type("ci: fix CI pipeline"), "ci");
930        assert_eq!(extract_commit_type("chore: update gitignore"), "chore");
931        assert_eq!(
932            extract_commit_type("revert: undo previous commit"),
933            "revert"
934        );
935
936        // Test with scope
937        assert_eq!(extract_commit_type("feat(auth): add login"), "feat");
938        assert_eq!(
939            extract_commit_type("fix(api): resolve endpoint issue"),
940            "fix"
941        );
942        assert_eq!(
943            extract_commit_type("docs(readme): update instructions"),
944            "docs"
945        );
946
947        // Test case insensitivity
948        assert_eq!(extract_commit_type("FEAT: uppercase type"), "feat");
949        assert_eq!(extract_commit_type("Fix: mixed case"), "fix");
950        assert_eq!(extract_commit_type("DOCS: all caps"), "docs");
951
952        // Test non-conventional commits
953        assert_eq!(extract_commit_type("random commit message"), "other");
954        assert_eq!(extract_commit_type("update: not conventional"), "other");
955        assert_eq!(
956            extract_commit_type("feature: close but not standard"),
957            "other"
958        );
959        assert_eq!(extract_commit_type("no colon here"), "other");
960        assert_eq!(extract_commit_type(""), "other");
961
962        // Test edge cases
963        assert_eq!(extract_commit_type("feat:no space after colon"), "feat");
964        assert_eq!(extract_commit_type("feat  : extra spaces"), "feat");
965        assert_eq!(
966            extract_commit_type("feat(scope)(weird): nested parens"),
967            "feat"
968        );
969    }
970
971    fn write_readme(dir: &Path, content: &str) {
972        fs::write(dir.join("README.md"), content).unwrap();
973    }
974
975    #[test]
976    fn test_feature_flag_in_readme_true() {
977        let temp_dir = tempfile::TempDir::new().unwrap();
978        write_readme(temp_dir.path(), "---\nfeature: true\n---\n\n# Feature\n");
979
980        let readmes = ReadmeCache::default();
981        assert_eq!(readmes.feature_flag(temp_dir.path()), Some(true));
982    }
983
984    #[test]
985    fn test_feature_flag_in_readme_false() {
986        let temp_dir = tempfile::TempDir::new().unwrap();
987        write_readme(temp_dir.path(), "---\nfeature: false\n---\n\n# Feature\n");
988
989        let readmes = ReadmeCache::default();
990        assert_eq!(readmes.feature_flag(temp_dir.path()), Some(false));
991    }
992
993    #[test]
994    fn test_feature_flag_in_readme_missing() {
995        let temp_dir = tempfile::TempDir::new().unwrap();
996
997        // No README at all
998        assert_eq!(ReadmeCache::default().feature_flag(temp_dir.path()), None);
999
1000        // README without a `feature` property
1001        write_readme(temp_dir.path(), "---\nowner: team\n---\n\n# Feature\n");
1002        assert_eq!(ReadmeCache::default().feature_flag(temp_dir.path()), None);
1003    }
1004
1005    #[test]
1006    fn test_readme_cache_reads_each_readme_once() {
1007        let temp_dir = tempfile::TempDir::new().unwrap();
1008        write_readme(temp_dir.path(), "---\nfeature: true\n---\n\n# Feature\n");
1009
1010        let readmes = ReadmeCache::default();
1011        assert_eq!(readmes.feature_flag(temp_dir.path()), Some(true));
1012
1013        // A later change on disk isn't seen, because the file isn't read again
1014        write_readme(temp_dir.path(), "---\nfeature: false\n---\n\n# Feature\n");
1015        assert_eq!(readmes.feature_flag(temp_dir.path()), Some(true));
1016    }
1017
1018    #[test]
1019    fn test_contains_todo() {
1020        assert!(contains_todo("// TODO: fix"));
1021        assert!(contains_todo("// todo: fix"));
1022        assert!(contains_todo("// ToDo"));
1023        assert!(contains_todo("todo"));
1024        assert!(contains_todo("écrit // tOdO é"));
1025        assert!(!contains_todo(""));
1026        assert!(!contains_todo("tod"));
1027        assert!(!contains_todo("to do"));
1028    }
1029
1030    #[test]
1031    fn test_count_feature_files() {
1032        let temp_dir = tempfile::TempDir::new().unwrap();
1033        let base = temp_dir.path();
1034        fs::create_dir_all(base.join("sub")).unwrap();
1035        fs::create_dir_all(base.join("docs")).unwrap();
1036        fs::create_dir_all(base.join("node_modules")).unwrap();
1037        fs::write(base.join("a.ts"), "// todo one\nline\n// TODO two\n").unwrap();
1038        fs::write(base.join("sub/b.ts"), "todo\n").unwrap();
1039        fs::write(base.join("binary"), [0xff, 0xfe]).unwrap();
1040        fs::write(base.join("docs/doc.md"), "todo\n").unwrap();
1041        fs::write(base.join("node_modules/c.js"), "todo\n").unwrap();
1042
1043        let filter = WalkFilter {
1044            ignore_paths: &[],
1045            include_skipped_dirs: false,
1046        };
1047        let mut counts = FileCounts::default();
1048        count_feature_files(base, &[], &filter, &mut counts);
1049        assert_eq!((counts.files, counts.lines, counts.todos), (3, 4, 3));
1050
1051        let filter = WalkFilter {
1052            ignore_paths: &[],
1053            include_skipped_dirs: true,
1054        };
1055        let mut counts = FileCounts::default();
1056        count_feature_files(base, &[], &filter, &mut counts);
1057        assert_eq!((counts.files, counts.lines, counts.todos), (4, 5, 4));
1058    }
1059
1060    #[test]
1061    fn test_is_feature_directory_direct_subfolder_of_features() {
1062        let temp_dir = tempfile::TempDir::new().unwrap();
1063        let features_dir = temp_dir.path().join("features");
1064        let feature_dir = features_dir.join("my-feature");
1065        fs::create_dir_all(&feature_dir).unwrap();
1066
1067        // No README needed: a direct subfolder of `features` is a feature by default
1068        assert!(is_feature_directory(&feature_dir, &ReadmeCache::default()));
1069    }
1070
1071    #[test]
1072    fn test_is_feature_directory_skips_when_feature_false_even_under_features_folder() {
1073        let temp_dir = tempfile::TempDir::new().unwrap();
1074        let features_dir = temp_dir.path().join("features");
1075        let feature_dir = features_dir.join("my-feature");
1076        fs::create_dir_all(&feature_dir).unwrap();
1077        write_readme(&feature_dir, "---\nfeature: false\n---\n\n# My Feature\n");
1078
1079        // Explicit `feature: false` overrides the "direct subfolder of `features`" rule
1080        assert!(!is_feature_directory(&feature_dir, &ReadmeCache::default()));
1081    }
1082
1083    #[test]
1084    fn test_is_feature_directory_readme_feature_true_outside_features_folder() {
1085        let temp_dir = tempfile::TempDir::new().unwrap();
1086        let feature_dir = temp_dir.path().join("some-dir");
1087        fs::create_dir_all(&feature_dir).unwrap();
1088        write_readme(&feature_dir, "---\nfeature: true\n---\n\n# Some Dir\n");
1089
1090        assert!(is_feature_directory(&feature_dir, &ReadmeCache::default()));
1091    }
1092
1093    #[test]
1094    fn test_is_feature_directory_readme_feature_false_outside_features_folder() {
1095        let temp_dir = tempfile::TempDir::new().unwrap();
1096        let feature_dir = temp_dir.path().join("some-dir");
1097        fs::create_dir_all(&feature_dir).unwrap();
1098        write_readme(&feature_dir, "---\nfeature: false\n---\n\n# Some Dir\n");
1099
1100        assert!(!is_feature_directory(&feature_dir, &ReadmeCache::default()));
1101    }
1102
1103    /// Skipping a feature via `feature: false` must keep its sub-children discoverable:
1104    /// both a nested `features/` folder and a subfolder with its own `feature: true` README.
1105    #[test]
1106    fn test_list_files_recursive_skips_feature_but_keeps_sub_children() {
1107        let temp_dir = tempfile::TempDir::new().unwrap();
1108        let base = temp_dir.path();
1109
1110        let features_dir = base.join("features");
1111        let skipped_dir = features_dir.join("skipped-feature");
1112        fs::create_dir_all(&skipped_dir).unwrap();
1113        write_readme(
1114            &skipped_dir,
1115            "---\nfeature: false\nowner: skipped-owner\n---\n\n# Skipped Feature\n",
1116        );
1117
1118        // A nested `features` folder inside the skipped directory.
1119        let nested_via_features_folder = skipped_dir.join("features").join("child-a");
1120        fs::create_dir_all(&nested_via_features_folder).unwrap();
1121
1122        // A subfolder marked as a feature via its own README.
1123        let nested_via_readme = skipped_dir.join("child-b");
1124        fs::create_dir_all(&nested_via_readme).unwrap();
1125        write_readme(
1126            &nested_via_readme,
1127            "---\nfeature: true\nowner: child-b-owner\n---\n\n# Child B\n",
1128        );
1129
1130        let features = list_files_recursive(base, &[], false).unwrap();
1131
1132        // The skipped feature itself must not appear anywhere in the tree.
1133        fn collect_names(features: &[Feature], out: &mut Vec<String>) {
1134            for feature in features {
1135                out.push(feature.name.clone());
1136                collect_names(&feature.features, out);
1137            }
1138        }
1139        let mut names = Vec::new();
1140        collect_names(&features, &mut names);
1141        assert!(!names.contains(&"skipped-feature".to_string()));
1142        assert!(!names.contains(&"Skipped Feature".to_string()));
1143
1144        // Both sub-children are still discovered, as top-level features (since their
1145        // skipped parent no longer exists as a node in the tree).
1146        assert!(names.contains(&"child-a".to_string()));
1147        let child_b = features
1148            .iter()
1149            .find(|f| f.name == "Child B")
1150            .expect("child-b feature should be present");
1151        assert_eq!(child_b.owner, "child-b-owner");
1152    }
1153}