Skip to main content

features_cli/
file_scanner.rs

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