features-cli 0.12.0

A CLI tool for discovering the features in a folder
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

use crate::models::Feature;

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct FileCoverageStats {
    pub lines_total: usize,
    pub lines_covered: usize,
    pub lines_missed: usize,
    pub line_coverage_percent: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branches_total: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branches_covered: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branch_coverage_percent: Option<f64>,
}

impl Default for FileCoverageStats {
    fn default() -> Self {
        Self {
            lines_total: 0,
            lines_covered: 0,
            lines_missed: 0,
            line_coverage_percent: 0.0,
            branches_total: None,
            branches_covered: None,
            branch_coverage_percent: None,
        }
    }
}

impl FileCoverageStats {
    pub fn new() -> Self {
        Self {
            lines_total: 0,
            lines_covered: 0,
            lines_missed: 0,
            line_coverage_percent: 0.0,
            branches_total: None,
            branches_covered: None,
            branch_coverage_percent: None,
        }
    }

    pub fn calculate_percentages(&mut self) {
        if self.lines_total > 0 {
            self.line_coverage_percent =
                (self.lines_covered as f64 / self.lines_total as f64) * 100.0;
        }

        if let (Some(total), Some(covered)) = (self.branches_total, self.branches_covered)
            && total > 0
        {
            self.branch_coverage_percent = Some((covered as f64 / total as f64) * 100.0);
        }
    }
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CoverageStats {
    pub lines_total: usize,
    pub lines_covered: usize,
    pub lines_missed: usize,
    pub line_coverage_percent: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branches_total: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branches_covered: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branch_coverage_percent: Option<f64>,
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub files: HashMap<String, FileCoverageStats>,
}

impl Default for CoverageStats {
    fn default() -> Self {
        Self {
            lines_total: 0,
            lines_covered: 0,
            lines_missed: 0,
            line_coverage_percent: 0.0,
            branches_total: None,
            branches_covered: None,
            branch_coverage_percent: None,
            files: HashMap::new(),
        }
    }
}

impl CoverageStats {
    // used by tests
    #[allow(dead_code)]
    pub fn new() -> Self {
        Self {
            lines_total: 0,
            lines_covered: 0,
            lines_missed: 0,
            line_coverage_percent: 0.0,
            branches_total: None,
            branches_covered: None,
            branch_coverage_percent: None,
            files: HashMap::new(),
        }
    }

    pub fn calculate_percentages(&mut self) {
        if self.lines_total > 0 {
            self.line_coverage_percent =
                (self.lines_covered as f64 / self.lines_total as f64) * 100.0;
        }

        if let (Some(total), Some(covered)) = (self.branches_total, self.branches_covered)
            && total > 0
        {
            self.branch_coverage_percent = Some((covered as f64 / total as f64) * 100.0);
        }
    }

    pub fn merge(&mut self, other: &CoverageStats) {
        self.lines_total += other.lines_total;
        self.lines_covered += other.lines_covered;
        // Recalculate lines_missed based on merged totals
        self.lines_missed = self.lines_total.saturating_sub(self.lines_covered);

        if let Some(other_branches_total) = other.branches_total {
            self.branches_total = Some(self.branches_total.unwrap_or(0) + other_branches_total);
        }

        if let Some(other_branches_covered) = other.branches_covered {
            self.branches_covered =
                Some(self.branches_covered.unwrap_or(0) + other_branches_covered);
        }

        // Merge file-level coverage
        for (file_path, file_stats) in &other.files {
            self.files.insert(file_path.clone(), file_stats.clone());
        }

        self.calculate_percentages();
    }
}

#[derive(Debug)]
struct FileCoverage {
    path: PathBuf,
    lines_total: usize,
    lines_covered: usize,
    branches_total: usize,
    branches_covered: usize,
}

/// Detects and parses coverage reports from the .coverage directory
pub fn parse_coverage_reports(
    coverage_dir: &Path,
    base_path: &Path,
) -> Result<HashMap<String, CoverageStats>> {
    let mut coverage_map: HashMap<String, CoverageStats> = HashMap::new();

    if !coverage_dir.exists() {
        return Ok(coverage_map);
    }

    // Find the project root (common path between coverage_dir and base_path)
    let project_root =
        find_common_ancestor(coverage_dir, base_path).unwrap_or_else(|| base_path.to_path_buf());

    // Find all coverage files in the directory
    let entries = fs::read_dir(coverage_dir).context("Failed to read coverage directory")?;

    for entry in entries {
        let entry = entry?;
        let path = entry.path();

        if path.is_file() {
            let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");

            // Detect file type and parse accordingly
            if (file_name.ends_with(".xml") || file_name.contains("cobertura"))
                && let Ok(file_coverage) = parse_cobertura_xml(&path)
            {
                merge_file_coverage(&mut coverage_map, file_coverage, &project_root, base_path);
            } else if (file_name.ends_with(".info") || file_name.contains("lcov"))
                && let Ok(file_coverage) = parse_lcov(&path)
            {
                merge_file_coverage(&mut coverage_map, file_coverage, &project_root, base_path);
            }
        }
    }

    Ok(coverage_map)
}

/// Find the common ancestor path between two paths
fn find_common_ancestor(path1: &Path, path2: &Path) -> Option<PathBuf> {
    // Try to canonicalize both paths
    let canon1 = std::fs::canonicalize(path1).ok()?;
    let canon2 = std::fs::canonicalize(path2).ok()?;

    let mut common = PathBuf::new();
    let components1: Vec<_> = canon1.components().collect();
    let components2: Vec<_> = canon2.components().collect();

    for (c1, c2) in components1.iter().zip(components2.iter()) {
        if c1 == c2 {
            common.push(c1);
        } else {
            break;
        }
    }

    if common.as_os_str().is_empty() {
        None
    } else {
        Some(common)
    }
}

/// Merge file coverage data into the coverage map
fn merge_file_coverage(
    coverage_map: &mut HashMap<String, CoverageStats>,
    file_coverage: Vec<FileCoverage>,
    project_root: &Path,
    base_path: &Path,
) {
    for fc in file_coverage {
        // Normalize the path: try to make it relative to base_path
        let normalized_path = normalize_coverage_path(&fc.path, project_root, base_path);

        let stats = coverage_map.entry(normalized_path.clone()).or_default();

        // Create individual file stats
        let mut file_stats = FileCoverageStats::new();
        file_stats.lines_total = fc.lines_total;
        file_stats.lines_covered = fc.lines_covered;
        file_stats.lines_missed = fc.lines_total.saturating_sub(fc.lines_covered);

        if fc.branches_total > 0 {
            file_stats.branches_total = Some(fc.branches_total);
            file_stats.branches_covered = Some(fc.branches_covered);
        }

        file_stats.calculate_percentages();

        // Store file-level coverage
        stats.files.insert(normalized_path, file_stats.clone());

        // Update aggregate stats
        stats.lines_total += fc.lines_total;
        stats.lines_covered += fc.lines_covered;
        stats.lines_missed += fc.lines_total.saturating_sub(fc.lines_covered);

        if fc.branches_total > 0 {
            stats.branches_total = Some(stats.branches_total.unwrap_or(0) + fc.branches_total);
            stats.branches_covered =
                Some(stats.branches_covered.unwrap_or(0) + fc.branches_covered);
        }

        stats.calculate_percentages();
    }
}

/// Normalize a coverage file path to be relative to base_path
fn normalize_coverage_path(file_path: &Path, project_root: &Path, base_path: &Path) -> String {
    // First, try to resolve the file path relative to project_root
    let resolved_path = if file_path.is_absolute() {
        file_path.to_path_buf()
    } else {
        project_root.join(file_path)
    };

    // Try to canonicalize paths for accurate comparison
    let canon_resolved = std::fs::canonicalize(&resolved_path).unwrap_or(resolved_path.clone());
    let canon_base = std::fs::canonicalize(base_path).unwrap_or_else(|_| base_path.to_path_buf());

    // Make the path relative to base_path
    if let Ok(relative) = canon_resolved.strip_prefix(&canon_base) {
        relative.to_string_lossy().to_string()
    } else {
        // If we can't make it relative, try with the original paths
        if let Ok(relative) = resolved_path.strip_prefix(base_path) {
            relative.to_string_lossy().to_string()
        } else {
            // Last resort: use the original file path as string
            file_path.to_string_lossy().to_string()
        }
    }
}

/// Parse Cobertura XML format
fn parse_cobertura_xml(path: &Path) -> Result<Vec<FileCoverage>> {
    let content = fs::read_to_string(path).context("Failed to read Cobertura XML file")?;

    let mut file_coverage = Vec::new();

    // Simple XML parsing without external dependencies
    // This is a basic parser that looks for <class> elements with coverage attributes
    let lines: Vec<&str> = content.lines().collect();
    let mut current_file: Option<String> = None;
    let mut lines_total = 0;
    let mut lines_covered = 0;
    let mut branches_total = 0;
    let mut branches_covered = 0;

    for line in lines {
        let trimmed = line.trim();

        // Look for class or file elements with filename attribute
        if trimmed.contains("<class") || trimmed.contains("<file") {
            // Save previous file if exists
            if let Some(file_path) = current_file.take() {
                if lines_total > 0 {
                    file_coverage.push(FileCoverage {
                        path: PathBuf::from(file_path),
                        lines_total,
                        lines_covered,
                        branches_total,
                        branches_covered,
                    });
                }
                lines_total = 0;
                lines_covered = 0;
                branches_total = 0;
                branches_covered = 0;
            }

            // Extract filename
            if let Some(filename) = extract_attribute(trimmed, "filename") {
                current_file = Some(filename);
            } else if let Some(filename) = extract_attribute(trimmed, "name") {
                current_file = Some(filename);
            }

            // Extract coverage metrics if present in the same tag
            if let Some(val) = extract_attribute(trimmed, "lines-valid") {
                lines_total = val.parse().unwrap_or(0);
            }
            if let Some(val) = extract_attribute(trimmed, "lines-covered") {
                lines_covered = val.parse().unwrap_or(0);
            }
            if let Some(val) = extract_attribute(trimmed, "branches-valid") {
                branches_total = val.parse().unwrap_or(0);
            }
            if let Some(val) = extract_attribute(trimmed, "branches-covered") {
                branches_covered = val.parse().unwrap_or(0);
            }
        }

        // Alternative: extract from line elements
        if current_file.is_some() && trimmed.contains("<line") {
            if let Some(hits) = extract_attribute(trimmed, "hits") {
                lines_total += 1;
                if hits.parse::<usize>().unwrap_or(0) > 0 {
                    lines_covered += 1;
                }
            }

            // Check for branch coverage
            if let Some(branch) = extract_attribute(trimmed, "branch")
                && branch == "true"
                && let Some(condition_coverage) = extract_attribute(trimmed, "condition-coverage")
                && let Some((covered, total)) = parse_condition_coverage(&condition_coverage)
            {
                branches_total += total;
                branches_covered += covered;
            }
        }
    }

    // Save last file
    if let Some(file_path) = current_file
        && lines_total > 0
    {
        file_coverage.push(FileCoverage {
            path: PathBuf::from(file_path),
            lines_total,
            lines_covered,
            branches_total,
            branches_covered,
        });
    }

    Ok(file_coverage)
}

/// Parse Lcov format
fn parse_lcov(path: &Path) -> Result<Vec<FileCoverage>> {
    let content = fs::read_to_string(path).context("Failed to read Lcov file")?;

    let mut file_coverage = Vec::new();
    let mut current_file: Option<&str> = None;
    let mut lines_total = 0;
    let mut lines_covered = 0;
    let mut branches_total = 0;
    let mut branches_covered = 0;

    for line in content.lines() {
        let trimmed = line.trim();

        if trimmed.starts_with("SF:") {
            // Start of a new file
            if let Some(file_path) = current_file.take() {
                file_coverage.push(FileCoverage {
                    path: PathBuf::from(file_path),
                    lines_total,
                    lines_covered,
                    branches_total,
                    branches_covered,
                });
                lines_total = 0;
                lines_covered = 0;
                branches_total = 0;
                branches_covered = 0;
            }
            current_file = trimmed.strip_prefix("SF:");
        } else if trimmed.starts_with("DA:")
            && let Some(comma_pos) = trimmed.find(',')
            && let Ok(count) = trimmed[comma_pos + 1..].parse::<usize>()
        {
            lines_total += 1;
            if count > 0 {
                lines_covered += 1;
            }
        } else if trimmed.starts_with("BRDA:") {
            // Branch coverage: BRDA:line_number,block_number,branch_number,taken
            branches_total += 1;
            let parts: Vec<&str> = trimmed
                .strip_prefix("BRDA:")
                .expect("")
                .split(',')
                .collect();
            if parts.len() >= 4 {
                let taken = parts[3];
                if taken != "-" && taken != "0" {
                    branches_covered += 1;
                }
            }
        } else if trimmed.starts_with("LF:")
            && let Ok(count) = trimmed[3..].parse::<usize>()
        {
            lines_total = count;
        } else if trimmed.starts_with("LH:")
            && let Ok(count) = trimmed[3..].parse::<usize>()
        {
            lines_covered = count;
        } else if trimmed.starts_with("BRF:")
            && let Ok(count) = trimmed[4..].parse::<usize>()
        {
            branches_total = count;
        } else if trimmed.starts_with("BRH:")
            && let Ok(count) = trimmed[4..].parse::<usize>()
        {
            branches_covered = count;
        } else if trimmed == "end_of_record" {
            // End of current file record
            if let Some(file_path) = current_file.take() {
                file_coverage.push(FileCoverage {
                    path: PathBuf::from(file_path),
                    lines_total,
                    lines_covered,
                    branches_total,
                    branches_covered,
                });
                lines_total = 0;
                lines_covered = 0;
                branches_total = 0;
                branches_covered = 0;
            }
        }
    }

    // Save last file if not already saved
    if let Some(file_path) = current_file {
        file_coverage.push(FileCoverage {
            path: PathBuf::from(file_path),
            lines_total,
            lines_covered,
            branches_total,
            branches_covered,
        });
    }

    Ok(file_coverage)
}

/// Extract an attribute value from an XML tag
fn extract_attribute(line: &str, attr_name: &str) -> Option<String> {
    let pattern = format!("{}=\"", attr_name);
    if let Some(start) = line.find(&pattern) {
        let value_start = start + pattern.len();
        if let Some(end) = line[value_start..].find('"') {
            return Some(line[value_start..value_start + end].to_string());
        }
    }
    None
}

/// Parse condition coverage string like "50% (1/2)"
fn parse_condition_coverage(coverage_str: &str) -> Option<(usize, usize)> {
    if let Some(paren_start) = coverage_str.find('(')
        && let Some(paren_end) = coverage_str.find(')')
    {
        let fraction = &coverage_str[paren_start + 1..paren_end];
        let parts: Vec<&str> = fraction.split('/').collect();
        if parts.len() == 2 {
            let covered = parts[0].parse().ok()?;
            let total = parts[1].parse().ok()?;
            return Some((covered, total));
        }
    }
    None
}

/// Map coverage data to features
pub fn map_coverage_to_features(
    features: &[Feature],
    coverage_map: HashMap<String, CoverageStats>,
    base_path: &Path,
) -> HashMap<String, CoverageStats> {
    let mut feature_coverage: HashMap<String, CoverageStats> = HashMap::new();

    // Normalize base path
    let canonical_base = std::fs::canonicalize(base_path).ok();

    for (file_path, coverage) in coverage_map {
        // Find which feature this file belongs to
        if let Some(feature_path) =
            find_feature_for_file(&file_path, features, canonical_base.as_deref())
        {
            let stats = feature_coverage.entry(feature_path.clone()).or_default();

            // Add each file's coverage to the feature
            for (individual_file_path, file_stats) in &coverage.files {
                // Check if this individual file belongs to the current feature
                if let Some(file_feature) =
                    find_feature_for_file(individual_file_path, features, canonical_base.as_deref())
                    && file_feature == feature_path
                {
                    stats
                        .files
                        .insert(individual_file_path.clone(), file_stats.clone());
                }
            }

            stats.merge(&coverage);
        }
    }

    feature_coverage
}

/// Find which feature a file belongs to
fn find_feature_for_file(
    file_path: &str,
    features: &[Feature],
    _canonical_base: Option<&Path>,
) -> Option<String> {
    let normalized_file = normalize_path(file_path);

    fn search_features(normalized_file: &str, features: &[Feature]) -> Option<String> {
        for feature in features {
            let normalized_feature = normalize_path(&feature.path);

            // Check if file is in this feature's folder (with proper path boundary)
            if normalized_file.starts_with(&normalized_feature) {
                let is_exact_match = normalized_file.len() == normalized_feature.len();
                let has_path_separator = normalized_file
                    .get(normalized_feature.len()..normalized_feature.len() + 1)
                    == Some("/");

                if is_exact_match || has_path_separator {
                    // Recursively check nested features first (more specific)
                    if let Some(nested) = search_features(normalized_file, &feature.features) {
                        return Some(nested);
                    }
                    return Some(feature.path.clone());
                }
            }
        }
        None
    }

    search_features(&normalized_file, features)
}

/// Normalize a path by removing leading ./ and converting to forward slashes
fn normalize_path(path: &str) -> String {
    let path = path.trim_start_matches("./");
    let path = path.replace('\\', "/");
    path.to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_find_feature_for_file_path_boundary() {
        // Test that a feature path doesn't match files in similarly-named directories
        let features = vec![
            Feature {
                name: "OffersRoute".to_string(),
                description: String::new(),
                owner: String::new(),
                is_owner_inherited: false,
                path: "airline/routes/OffersRoute".to_string(),
                features: vec![],
                meta: std::collections::BTreeMap::new(),
                changes: vec![],
                decisions: vec![],
                stats: None,
                dependencies: vec![],
            },
            Feature {
                name: "CruiseOffersRoute".to_string(),
                description: String::new(),
                owner: String::new(),
                is_owner_inherited: false,
                path: "cruise/routes/OffersRoute".to_string(),
                features: vec![],
                meta: std::collections::BTreeMap::new(),
                changes: vec![],
                decisions: vec![],
                stats: None,
                dependencies: vec![],
            },
        ];

        // File in cruise/routes/OffersRoute should match CruiseOffersRoute, not OffersRoute
        let result =
            find_feature_for_file("cruise/routes/OffersRoute/BidCard.tsx", &features, None);
        assert_eq!(result, Some("cruise/routes/OffersRoute".to_string()));

        // File in airline/routes/OffersRoute should match OffersRoute
        let result =
            find_feature_for_file("airline/routes/OffersRoute/BidCard.tsx", &features, None);
        assert_eq!(result, Some("airline/routes/OffersRoute".to_string()));
    }

    #[test]
    fn test_find_feature_for_file_no_false_prefix_match() {
        // Test that "routes/OffersRoute" doesn't match "routes/OffersRouteExtra"
        let features = vec![
            Feature {
                name: "OffersRoute".to_string(),
                description: String::new(),
                owner: String::new(),
                is_owner_inherited: false,
                path: "routes/OffersRoute".to_string(),
                features: vec![],
                meta: std::collections::BTreeMap::new(),
                changes: vec![],
                decisions: vec![],
                stats: None,
                dependencies: vec![],
            },
            Feature {
                name: "OffersRouteExtra".to_string(),
                description: String::new(),
                owner: String::new(),
                is_owner_inherited: false,
                path: "routes/OffersRouteExtra".to_string(),
                features: vec![],
                meta: std::collections::BTreeMap::new(),
                changes: vec![],
                decisions: vec![],
                stats: None,
                dependencies: vec![],
            },
        ];

        // File in routes/OffersRouteExtra should match OffersRouteExtra
        let result =
            find_feature_for_file("routes/OffersRouteExtra/Component.tsx", &features, None);
        assert_eq!(result, Some("routes/OffersRouteExtra".to_string()));

        // File in routes/OffersRoute should match OffersRoute
        let result = find_feature_for_file("routes/OffersRoute/Component.tsx", &features, None);
        assert_eq!(result, Some("routes/OffersRoute".to_string()));
    }

    #[test]
    fn test_find_feature_for_file_exact_match() {
        // Test that exact path matches work
        let features = vec![Feature {
            name: "MyFeature".to_string(),
            description: String::new(),
            owner: String::new(),
            is_owner_inherited: false,
            path: "src/features/MyFeature".to_string(),
            features: vec![],
            meta: std::collections::BTreeMap::new(),
            changes: vec![],
            decisions: vec![],
            stats: None,
            dependencies: vec![],
        }];

        // Exact match (file IS the feature directory)
        let result = find_feature_for_file("src/features/MyFeature", &features, None);
        assert_eq!(result, Some("src/features/MyFeature".to_string()));

        // File inside the feature
        let result = find_feature_for_file("src/features/MyFeature/index.tsx", &features, None);
        assert_eq!(result, Some("src/features/MyFeature".to_string()));
    }

    #[test]
    fn test_find_feature_for_file_no_match() {
        // Test that unrelated paths don't match
        let features = vec![Feature {
            name: "MyFeature".to_string(),
            description: String::new(),
            owner: String::new(),
            is_owner_inherited: false,
            path: "src/features/MyFeature".to_string(),
            features: vec![],
            meta: std::collections::BTreeMap::new(),
            changes: vec![],
            decisions: vec![],
            stats: None,
            dependencies: vec![],
        }];

        // Unrelated path
        let result = find_feature_for_file("src/other/Component.tsx", &features, None);
        assert_eq!(result, None);
    }

    #[test]
    fn test_find_feature_for_file_nested_features() {
        // Test that nested features are matched recursively and the most specific one is returned
        let features = vec![Feature {
            name: "ParentFeature".to_string(),
            description: String::new(),
            owner: String::new(),
            is_owner_inherited: false,
            path: "src/features/ParentFeature".to_string(),
            features: vec![
                Feature {
                    name: "SubFeatureA".to_string(),
                    description: String::new(),
                    owner: String::new(),
                    is_owner_inherited: false,
                    path: "src/features/ParentFeature/SubFeatureA".to_string(),
                    features: vec![],
                    meta: std::collections::BTreeMap::new(),
                    changes: vec![],
                    decisions: vec![],
                    stats: None,
                    dependencies: vec![],
                },
                Feature {
                    name: "SubFeatureB".to_string(),
                    description: String::new(),
                    owner: String::new(),
                    is_owner_inherited: false,
                    path: "src/features/ParentFeature/SubFeatureB".to_string(),
                    features: vec![],
                    meta: std::collections::BTreeMap::new(),
                    changes: vec![],
                    decisions: vec![],
                    stats: None,
                    dependencies: vec![],
                },
            ],
            meta: std::collections::BTreeMap::new(),
            changes: vec![],
            decisions: vec![],
            stats: None,
            dependencies: vec![],
        }];

        // File in SubFeatureA should match SubFeatureA (most specific)
        let result = find_feature_for_file(
            "src/features/ParentFeature/SubFeatureA/Component.tsx",
            &features,
            None,
        );
        assert_eq!(
            result,
            Some("src/features/ParentFeature/SubFeatureA".to_string())
        );

        // File in SubFeatureB should match SubFeatureB (most specific)
        let result = find_feature_for_file(
            "src/features/ParentFeature/SubFeatureB/index.tsx",
            &features,
            None,
        );
        assert_eq!(
            result,
            Some("src/features/ParentFeature/SubFeatureB".to_string())
        );

        // File in ParentFeature but not in any sub-feature should match ParentFeature
        let result = find_feature_for_file("src/features/ParentFeature/utils.tsx", &features, None);
        assert_eq!(result, Some("src/features/ParentFeature".to_string()));
    }
}