Skip to main content

features_cli/
dependency_resolver.rs

1//! Module for resolving dependencies between features
2//!
3//! This module takes import statements and determines which features they belong to,
4//! and what type of relationship exists between features (parent, child, sibling).
5
6use crate::import_detector::{ImportStatement, resolve_import_path};
7use crate::models::{Dependency, DependencyType};
8use crate::skip_dirs::SKIPPED_DIRS;
9use std::collections::HashMap;
10use std::path::{Path, PathBuf};
11
12/// Represents a feature with its path for dependency resolution
13#[derive(Debug, Clone)]
14pub struct FeatureInfo {
15    pub name: String,
16    pub path: PathBuf,
17}
18
19/// Build a map of file paths to their containing features (using feature path as identifier)
20pub fn build_file_to_feature_map(
21    features: &[FeatureInfo],
22    base_path: &Path,
23) -> HashMap<PathBuf, String> {
24    let mut map = HashMap::new();
25
26    // Sort features by path length (longest first) to ensure more specific features
27    // take precedence over parent features when mapping files
28    let mut sorted_features = features.to_vec();
29    sorted_features.sort_by(|a, b| {
30        b.path
31            .to_string_lossy()
32            .len()
33            .cmp(&a.path.to_string_lossy().len())
34    });
35
36    for feature in sorted_features {
37        let feature_path = base_path.join(&feature.path);
38
39        // Map all files within this feature directory using the feature's path as identifier
40        if std::fs::read_dir(&feature_path).is_ok() {
41            map_directory_files(&feature_path, &feature.path.to_string_lossy(), &mut map);
42        }
43    }
44
45    map
46}
47
48/// Recursively map all files in a directory to a feature path
49/// Only maps files that haven't been mapped yet (most specific feature wins)
50fn map_directory_files(dir: &Path, feature_path: &str, map: &mut HashMap<PathBuf, String>) {
51    if let Ok(entries) = std::fs::read_dir(dir) {
52        for entry in entries.flatten() {
53            let path = entry.path();
54
55            if path.is_file() {
56                // Canonicalize the path to resolve .. and .
57                let canonical_path = if let Ok(canonical) = path.canonicalize() {
58                    canonical
59                } else {
60                    path.clone()
61                };
62
63                // Only insert if not already mapped (most specific feature takes precedence)
64                map.entry(canonical_path)
65                    .or_insert_with(|| feature_path.to_string());
66            } else if path.is_dir()
67                && let Some(dir_name) = path.file_name().and_then(|n| n.to_str())
68                && !should_skip_directory(dir_name)
69                && !is_nested_feature_directory(&path)
70            {
71                map_directory_files(&path, feature_path, map);
72            }
73        }
74    }
75}
76
77/// Check if a directory is a nested feature directory
78/// A directory is considered a feature if:
79/// 1. It's a direct child of a "features" directory, OR
80/// 2. It has a features.toml file
81fn is_nested_feature_directory(dir: &Path) -> bool {
82    // Check for features.toml
83    if dir.join("features.toml").exists() {
84        return true;
85    }
86
87    // Check if it's a direct child of a "features" directory
88    if let Some(parent) = dir.parent()
89        && let Some(parent_name) = parent.file_name()
90        && parent_name == "features"
91    {
92        return true;
93    }
94
95    false
96}
97
98/// Check if a directory should be skipped
99fn should_skip_directory(dir_name: &str) -> bool {
100    SKIPPED_DIRS.contains(&dir_name)
101        || matches!(
102            dir_name,
103            "target" | "dist" | "build" | ".git" | "__pycache__" | "coverage"
104        )
105}
106
107/// Determine the relationship type between two features based on their paths
108pub fn determine_dependency_type(
109    source_feature_path: &Path,
110    target_feature_path: &Path,
111) -> DependencyType {
112    // Check if target is a child (descendant) of source
113    if target_feature_path.starts_with(source_feature_path) {
114        return DependencyType::Child;
115    }
116
117    // Check if source is a child (descendant) of target
118    if source_feature_path.starts_with(target_feature_path) {
119        return DependencyType::Parent;
120    }
121
122    // Otherwise, they're siblings
123    DependencyType::Sibling
124}
125
126/// Resolve imports to dependencies for a specific feature
127pub fn resolve_feature_dependencies(
128    _feature_name: &str,
129    feature_path: &Path,
130    base_path: &Path,
131    imports: &[ImportStatement],
132    file_to_feature_map: &HashMap<PathBuf, String>,
133    feature_path_to_name_map: &HashMap<String, String>,
134    file_map: &HashMap<String, PathBuf>,
135) -> Vec<Dependency> {
136    let mut dependencies = Vec::new();
137    let mut seen = std::collections::HashSet::new();
138
139    for import in imports {
140        let source_file = Path::new(&import.file_path);
141
142        // Resolve the import to an actual file path
143        if let Some(resolved_path) =
144            resolve_import_path(&import.imported_path, source_file, base_path, file_map)
145        {
146            // Find which feature this file belongs to (returns feature path)
147            if let Some(target_feature_path_str) = file_to_feature_map.get(&resolved_path) {
148                // Skip if it's the same feature
149                if target_feature_path_str == feature_path.to_string_lossy().as_ref() {
150                    continue;
151                }
152
153                // Create a unique key to avoid duplicates
154                let dep_key = format!(
155                    "{}:{}:{}",
156                    resolved_path.display(),
157                    import.line_number,
158                    target_feature_path_str
159                );
160
161                if seen.contains(&dep_key) {
162                    continue;
163                }
164                seen.insert(dep_key);
165
166                // Get the target feature name from the path (for validation)
167                if feature_path_to_name_map
168                    .get(target_feature_path_str)
169                    .is_some()
170                {
171                    let target_path = PathBuf::from(target_feature_path_str);
172                    let full_target_path = base_path.join(&target_path);
173                    let full_source_path = base_path.join(feature_path);
174
175                    // Determine the dependency type
176                    let dependency_type =
177                        determine_dependency_type(&full_source_path, &full_target_path);
178
179                    // Convert source file path to be relative to base_path
180                    let relative_source_filename = if let Ok(canonical_base) =
181                        base_path.canonicalize()
182                    {
183                        let source_path = Path::new(&import.file_path);
184                        if let Ok(canonical_source) = source_path.canonicalize() {
185                            if let Ok(rel_path) = canonical_source.strip_prefix(&canonical_base) {
186                                rel_path.to_string_lossy().to_string()
187                            } else {
188                                import.file_path.clone()
189                            }
190                        } else {
191                            import.file_path.clone()
192                        }
193                    } else {
194                        import.file_path.clone()
195                    };
196
197                    // Convert target file path to be relative to base_path
198                    let relative_target_filename =
199                        if let Ok(canonical_base) = base_path.canonicalize() {
200                            if let Ok(rel_path) = resolved_path.strip_prefix(&canonical_base) {
201                                rel_path.to_string_lossy().to_string()
202                            } else {
203                                resolved_path.to_string_lossy().to_string()
204                            }
205                        } else {
206                            resolved_path.to_string_lossy().to_string()
207                        };
208
209                    // Create dependency
210                    dependencies.push(Dependency {
211                        source_filename: relative_source_filename,
212                        target_filename: relative_target_filename,
213                        line: import.line_number,
214                        content: import.line_content.clone(),
215                        feature_path: target_feature_path_str.to_string(),
216                        dependency_type,
217                    });
218                }
219            }
220        }
221    }
222
223    dependencies
224}
225
226/// Collect all feature information recursively
227pub fn collect_feature_info(
228    features: &[crate::models::Feature],
229    _parent_path: Option<&Path>,
230    result: &mut Vec<FeatureInfo>,
231) {
232    for feature in features {
233        // Feature paths are already relative to base, not to parent
234        let feature_path = PathBuf::from(&feature.path);
235
236        result.push(FeatureInfo {
237            name: feature.name.clone(),
238            path: feature_path.clone(),
239        });
240
241        // Recursively collect nested features (don't pass parent_path since paths are base-relative)
242        if !feature.features.is_empty() {
243            collect_feature_info(&feature.features, None, result);
244        }
245    }
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    #[test]
253    fn test_determine_dependency_type_child() {
254        let source = Path::new("/project/features/parent");
255        let target = Path::new("/project/features/parent/child");
256
257        assert!(matches!(
258            determine_dependency_type(source, target),
259            DependencyType::Child
260        ));
261    }
262
263    #[test]
264    fn test_determine_dependency_type_parent() {
265        let source = Path::new("/project/features/parent/child");
266        let target = Path::new("/project/features/parent");
267
268        assert!(matches!(
269            determine_dependency_type(source, target),
270            DependencyType::Parent
271        ));
272    }
273
274    #[test]
275    fn test_determine_dependency_type_sibling() {
276        let source = Path::new("/project/features/feature-a");
277        let target = Path::new("/project/features/feature-b");
278
279        assert!(matches!(
280            determine_dependency_type(source, target),
281            DependencyType::Sibling
282        ));
283    }
284}