Skip to main content

features_cli/
import_detector.rs

1//! Module for detecting imports/dependencies in source code files
2//!
3//! This module scans source files for import statements and resolves them
4//! to their actual file paths to detect cross-feature dependencies.
5
6use anyhow::Result;
7use std::collections::HashMap;
8use std::fs;
9use std::path::{Path, PathBuf};
10use walkdir::WalkDir;
11
12use crate::skip_dirs::is_non_source_dir;
13
14#[derive(Debug, Clone)]
15pub struct ImportStatement {
16    pub file_path: String,
17    pub line_number: usize,
18    pub line_content: String,
19    pub imported_path: String,
20}
21
22/// Represents language-specific import patterns
23#[derive(Debug, Clone)]
24enum ImportPattern {
25    /// Rust: use statements
26    Rust,
27    /// JavaScript/TypeScript: import/require/export from
28    JavaScript,
29    /// Python: import/from...import
30    Python,
31    /// Go: import statements
32    Go,
33    /// Java/C#/Kotlin: import/using statements
34    JavaLike,
35    /// C/C++: #include statements
36    CStyle,
37    /// Ruby: require/require_relative
38    Ruby,
39    /// PHP: use/require/include
40    Php,
41    /// Shell: source/.
42    Shell,
43    /// CSS/SCSS/Less: @import
44    Css,
45}
46
47/// Get import pattern for a file extension
48fn get_import_pattern(extension: &str) -> Option<ImportPattern> {
49    match extension {
50        "rs" => Some(ImportPattern::Rust),
51        "js" | "jsx" | "ts" | "tsx" | "mjs" | "cjs" => Some(ImportPattern::JavaScript),
52        "py" => Some(ImportPattern::Python),
53        "go" => Some(ImportPattern::Go),
54        "java" | "kt" | "scala" => Some(ImportPattern::JavaLike),
55        "cs" => Some(ImportPattern::JavaLike),
56        "c" | "cpp" | "cc" | "cxx" | "h" | "hpp" => Some(ImportPattern::CStyle),
57        "rb" => Some(ImportPattern::Ruby),
58        "php" => Some(ImportPattern::Php),
59        "sh" | "bash" => Some(ImportPattern::Shell),
60        "css" | "scss" | "less" => Some(ImportPattern::Css),
61        _ => None,
62    }
63}
64
65/// Extract import path from a Rust use statement
66fn extract_rust_import(line: &str) -> Option<String> {
67    let trimmed = line.trim();
68
69    // Remove "use " prefix and trailing semicolon
70    let import_part = trimmed.strip_prefix("use ")?.trim_end_matches(';').trim();
71
72    // Handle 'use crate::' or 'use super::' or 'use self::'
73    if import_part.starts_with("crate::")
74        || import_part.starts_with("super::")
75        || import_part.starts_with("self::")
76    {
77        // Extract the module path (remove use blocks like {Type1, Type2})
78        let path = if let Some(brace_pos) = import_part.find('{') {
79            import_part[..brace_pos].trim()
80        } else if let Some(as_pos) = import_part.find(" as ") {
81            import_part[..as_pos].trim()
82        } else {
83            import_part
84        };
85
86        return Some(path.to_string());
87    }
88
89    None
90}
91
92/// Extract import path from JavaScript/TypeScript import/require
93fn extract_javascript_import(line: &str) -> Option<String> {
94    let trimmed = line.trim();
95
96    // import ... from "path" or import ... from 'path'
97    if trimmed.starts_with("import ") {
98        if let Some(from_pos) = trimmed.find(" from ") {
99            let after_from = &trimmed[from_pos + 6..].trim();
100            return extract_quoted_string(after_from);
101        }
102        // import "path" or import 'path'
103        if let Some(quote_pos) = trimmed.find(['"', '\'']) {
104            return extract_quoted_string(&trimmed[quote_pos..]);
105        }
106    }
107
108    // export ... from "path"
109    if trimmed.starts_with("export ")
110        && trimmed.contains(" from ")
111        && let Some(from_pos) = trimmed.find(" from ")
112    {
113        let after_from = &trimmed[from_pos + 6..].trim();
114        return extract_quoted_string(after_from);
115    }
116
117    // require("path") or require('path')
118    if trimmed.contains("require(")
119        && let Some(paren_pos) = trimmed.find("require(")
120    {
121        let after_paren = &trimmed[paren_pos + 8..];
122        return extract_quoted_string(after_paren);
123    }
124
125    None
126}
127
128/// Extract import path from Python import statements
129fn extract_python_import(line: &str) -> Option<String> {
130    let trimmed = line.trim();
131
132    // from ... import ...
133    if trimmed.starts_with("from ")
134        && let Some(import_pos) = trimmed.find(" import ")
135    {
136        let module_path = trimmed[5..import_pos].trim();
137        // Only consider relative imports (starting with .)
138        if module_path.starts_with('.') {
139            return Some(module_path.to_string());
140        }
141    }
142
143    // import ... (relative imports only)
144    if let Some(import_part) = trimmed.strip_prefix("import ") {
145        let import_part = import_part.trim();
146        let module_path = if let Some(as_pos) = import_part.find(" as ") {
147            &import_part[..as_pos]
148        } else {
149            import_part
150        };
151
152        // Only consider relative imports
153        if module_path.starts_with('.') {
154            return Some(module_path.trim().to_string());
155        }
156    }
157
158    None
159}
160
161/// Extract import path from Go import statements
162fn extract_go_import(line: &str) -> Option<String> {
163    let trimmed = line.trim();
164    let after_import = trimmed.strip_prefix("import ")?.trim();
165    extract_quoted_string(after_import)
166}
167
168/// Extract import path from Java-like languages (Java, C#, Kotlin, Scala)
169fn extract_javalike_import(line: &str) -> Option<String> {
170    let trimmed = line.trim();
171
172    // Java/Kotlin: import package.name
173    if let Some(import_part) = trimmed.strip_prefix("import ") {
174        let import_part = import_part.trim().trim_end_matches(';');
175        // Skip static imports
176        if import_part.starts_with("static ") {
177            return None;
178        }
179        return Some(import_part.to_string());
180    }
181
182    // C#: using namespace
183    if !trimmed.contains('=')
184        && let Some(import_part) = trimmed.strip_prefix("using ")
185    {
186        let import_part = import_part.trim().trim_end_matches(';');
187        return Some(import_part.to_string());
188    }
189
190    None
191}
192
193/// Extract include path from C/C++ #include statements
194fn extract_c_include(line: &str) -> Option<String> {
195    let trimmed = line.trim();
196    let after_include = trimmed.strip_prefix("#include ")?.trim();
197
198    // #include "file.h" (local include)
199    if let Some(path) = extract_quoted_string(after_include) {
200        return Some(path);
201    }
202
203    // #include <file.h> (system include - we'll skip these)
204    // But if it starts with a relative path marker, keep it
205    if after_include.starts_with('<')
206        && after_include.contains('/')
207        && let Some(end) = after_include.find('>')
208    {
209        return Some(after_include[1..end].to_string());
210    }
211
212    None
213}
214
215/// Extract require path from Ruby
216fn extract_ruby_require(line: &str) -> Option<String> {
217    let trimmed = line.trim();
218
219    // require_relative "path" or require_relative 'path'
220    if let Some(after_require) = trimmed.strip_prefix("require_relative ") {
221        return extract_quoted_string(after_require.trim());
222    }
223
224    // require "path" or require 'path' (only relative paths with ./)
225    if let Some(after_require) = trimmed.strip_prefix("require ")
226        && let Some(path) = extract_quoted_string(after_require.trim())
227        && path.starts_with('.')
228    {
229        return Some(path);
230    }
231
232    None
233}
234
235/// Extract require/include path from PHP
236fn extract_php_include(line: &str) -> Option<String> {
237    let trimmed = line.trim();
238
239    for keyword in ["require", "require_once", "include", "include_once"] {
240        if let Some(after_keyword) = trimmed.strip_prefix(keyword) {
241            let after_keyword = after_keyword.trim();
242            if let Some(path) = extract_quoted_string(after_keyword) {
243                return Some(path);
244            }
245        }
246    }
247
248    None
249}
250
251/// Extract source path from Shell scripts
252fn extract_shell_source(line: &str) -> Option<String> {
253    let trimmed = line.trim();
254
255    // source path or . path
256    if let Some(path) = trimmed.strip_prefix("source ") {
257        let path = path.trim();
258        return extract_quoted_string(path).or_else(|| Some(path.to_string()));
259    }
260
261    if let Some(path) = trimmed.strip_prefix(". ")
262        && !trimmed.starts_with("..")
263    {
264        let path = path.trim();
265        return extract_quoted_string(path).or_else(|| Some(path.to_string()));
266    }
267
268    None
269}
270
271/// Extract @import path from CSS/SCSS/Less
272fn extract_css_import(line: &str) -> Option<String> {
273    let trimmed = line.trim();
274    let after_import = trimmed.strip_prefix("@import ")?.trim();
275    extract_quoted_string(after_import)
276}
277
278/// Extract a quoted string (single or double quotes)
279fn extract_quoted_string(s: &str) -> Option<String> {
280    let trimmed = s.trim();
281    let first_char = trimmed.chars().next()?;
282
283    // Check for quote characters
284    if ['"', '\'', '`'].contains(&first_char)
285        && let Some(end) = trimmed[1..].find(first_char)
286    {
287        return Some(trimmed[1..end + 1].to_string());
288    }
289
290    None
291}
292
293/// Extract import statement based on language pattern
294fn extract_import(line: &str, pattern: &ImportPattern) -> Option<String> {
295    match pattern {
296        ImportPattern::Rust => extract_rust_import(line),
297        ImportPattern::JavaScript => extract_javascript_import(line),
298        ImportPattern::Python => extract_python_import(line),
299        ImportPattern::Go => extract_go_import(line),
300        ImportPattern::JavaLike => extract_javalike_import(line),
301        ImportPattern::CStyle => extract_c_include(line),
302        ImportPattern::Ruby => extract_ruby_require(line),
303        ImportPattern::Php => extract_php_include(line),
304        ImportPattern::Shell => extract_shell_source(line),
305        ImportPattern::Css => extract_css_import(line),
306    }
307}
308
309/// Scan a single file for import statements
310pub fn scan_file_for_imports(file_path: &Path) -> Result<Vec<ImportStatement>> {
311    let mut imports = Vec::new();
312
313    let extension = file_path.extension().and_then(|e| e.to_str()).unwrap_or("");
314    let pattern = match get_import_pattern(extension) {
315        Some(p) => p,
316        None => return Ok(imports), // Unsupported file type
317    };
318
319    let content = fs::read_to_string(file_path)?;
320
321    for (line_number, line) in content.lines().enumerate() {
322        if let Some(imported_path) = extract_import(line, &pattern) {
323            imports.push(ImportStatement {
324                file_path: file_path.to_string_lossy().to_string(),
325                line_number: line_number + 1, // 1-based
326                line_content: line.trim().to_string(),
327                imported_path,
328            });
329        }
330    }
331
332    Ok(imports)
333}
334
335/// Build a map of all files in the project for quick lookup
336pub fn build_file_map(base_path: &Path) -> HashMap<String, PathBuf> {
337    let mut file_map = HashMap::new();
338
339    for entry in WalkDir::new(base_path)
340        .into_iter()
341        .filter_entry(|e| {
342            if e.file_type().is_dir() {
343                let dir_name = e.file_name().to_string_lossy();
344                !is_non_source_dir(&dir_name)
345            } else {
346                true
347            }
348        })
349        .filter_map(|e| e.ok())
350    {
351        if entry.file_type().is_file() {
352            let path = entry.path();
353            if let Ok(relative_path) = path.strip_prefix(base_path) {
354                let key = relative_path.to_string_lossy().to_string();
355                file_map.insert(key, path.to_path_buf());
356            }
357        }
358    }
359
360    file_map
361}
362
363/// Resolve an import path to an actual file path
364pub fn resolve_import_path(
365    import_path: &str,
366    source_file: &Path,
367    base_path: &Path,
368    file_map: &HashMap<String, PathBuf>,
369) -> Option<PathBuf> {
370    let source_dir = source_file.parent()?;
371
372    // Handle different types of imports
373    if import_path.starts_with('.') {
374        // Relative import (./file or ../file)
375        resolve_relative_import(import_path, source_dir, base_path)
376    } else if import_path.contains("::") {
377        // Rust-style module path (crate::module::submodule)
378        resolve_rust_module_path(import_path, source_file, base_path, file_map)
379    } else if import_path.contains('/') {
380        // Path-like import
381        resolve_path_import(import_path, base_path, file_map)
382    } else {
383        // Package/module name - we'll skip these as they're external
384        None
385    }
386}
387
388/// Resolve relative imports like ./file or ../file
389fn resolve_relative_import(
390    import_path: &str,
391    source_dir: &Path,
392    base_path: &Path,
393) -> Option<PathBuf> {
394    let _import_path_clean = import_path
395        .trim_start_matches("./")
396        .trim_start_matches("../");
397
398    // Try to resolve from source directory
399    let candidate = source_dir.join(import_path);
400
401    // First, check if the path is a directory and try index files
402    // This handles: import foo from './folder' -> './folder/index.ts'
403    if candidate.is_dir() {
404        for index_name in ["index", "mod", "__init__"] {
405            for idx_ext in ["ts", "tsx", "js", "jsx", "rs", "py"] {
406                let index_path = candidate.join(format!("{}.{}", index_name, idx_ext));
407                if index_path.exists() && index_path.starts_with(base_path) {
408                    // Canonicalize to resolve .. and . in the path
409                    if let Ok(canonical) = index_path.canonicalize() {
410                        return Some(canonical);
411                    }
412                    return Some(index_path);
413                }
414            }
415        }
416    }
417
418    // Try common extensions if no extension provided
419    let extensions = [
420        "", ".ts", ".tsx", ".js", ".jsx", ".rs", ".py", ".go", ".java", ".rb", ".php",
421    ];
422
423    for ext in extensions {
424        let path_with_ext = if ext.is_empty() {
425            candidate.clone()
426        } else {
427            // Append extension to the path
428            let mut path_str = candidate.to_string_lossy().to_string();
429            path_str.push_str(ext);
430            PathBuf::from(path_str)
431        };
432
433        if path_with_ext.exists() && path_with_ext.starts_with(base_path) {
434            // Canonicalize to resolve .. and . in the path
435            if let Ok(canonical) = path_with_ext.canonicalize() {
436                return Some(canonical);
437            }
438            return Some(path_with_ext);
439        }
440
441        // Also check if path with extension is a directory with index file
442        // This handles edge cases like './folder.component' -> './folder.component/index.ts'
443        if path_with_ext.is_dir() {
444            for index_name in ["index", "mod", "__init__"] {
445                for idx_ext in ["ts", "tsx", "js", "jsx", "rs", "py"] {
446                    let index_path = path_with_ext.join(format!("{}.{}", index_name, idx_ext));
447                    if index_path.exists() && index_path.starts_with(base_path) {
448                        return Some(index_path);
449                    }
450                }
451            }
452        }
453    }
454
455    None
456}
457
458/// Resolve Rust module paths like crate::module::submodule
459fn resolve_rust_module_path(
460    import_path: &str,
461    source_file: &Path,
462    base_path: &Path,
463    _file_map: &HashMap<String, PathBuf>,
464) -> Option<PathBuf> {
465    // Convert crate::module::submodule to module/submodule.rs or module/submodule/mod.rs
466    let path_str = if let Some(stripped) = import_path.strip_prefix("crate::") {
467        stripped
468    } else if let Some(stripped) = import_path.strip_prefix("super::") {
469        // Handle super:: by going up one directory
470        return resolve_super_path(stripped, source_file, base_path);
471    } else {
472        import_path.strip_prefix("self::")?
473    };
474
475    // Convert :: to /
476    let path_parts: Vec<&str> = path_str.split("::").collect();
477
478    // Find src directory
479    let src_dir = find_src_directory(base_path)?;
480
481    // Try module/file.rs
482    let mut module_path = src_dir.clone();
483    for part in &path_parts {
484        module_path = module_path.join(part);
485    }
486
487    if module_path.with_extension("rs").exists() {
488        return Some(module_path.with_extension("rs"));
489    }
490
491    // Try module/mod.rs
492    let mod_path = module_path.join("mod.rs");
493    if mod_path.exists() {
494        return Some(mod_path);
495    }
496
497    None
498}
499
500/// Resolve super:: paths in Rust
501fn resolve_super_path(
502    remaining_path: &str,
503    source_file: &Path,
504    base_path: &Path,
505) -> Option<PathBuf> {
506    let source_dir = source_file.parent()?;
507    let parent_dir = source_dir.parent()?;
508
509    if !parent_dir.starts_with(base_path) {
510        return None;
511    }
512
513    let path_parts: Vec<&str> = remaining_path.split("::").collect();
514    let mut module_path = parent_dir.to_path_buf();
515
516    for part in &path_parts {
517        module_path = module_path.join(part);
518    }
519
520    if module_path.with_extension("rs").exists() {
521        return Some(module_path.with_extension("rs"));
522    }
523
524    let mod_path = module_path.join("mod.rs");
525    if mod_path.exists() {
526        return Some(mod_path);
527    }
528
529    None
530}
531
532/// Find the src directory in a Rust project
533fn find_src_directory(base_path: &Path) -> Option<PathBuf> {
534    let src_dir = base_path.join("src");
535    if src_dir.is_dir() {
536        return Some(src_dir);
537    }
538
539    // Look for src in subdirectories
540    for entry in (fs::read_dir(base_path).ok()?).flatten() {
541        let path = entry.path();
542        if path.is_dir() {
543            let nested_src = path.join("src");
544            if nested_src.is_dir() {
545                return Some(nested_src);
546            }
547        }
548    }
549
550    None
551}
552
553/// Resolve path-based imports
554fn resolve_path_import(
555    import_path: &str,
556    _base_path: &Path,
557    file_map: &HashMap<String, PathBuf>,
558) -> Option<PathBuf> {
559    // Try direct lookup
560    if let Some(path) = file_map.get(import_path) {
561        return Some(path.clone());
562    }
563
564    // Try with common extensions
565    for ext in [
566        "ts", "tsx", "js", "jsx", "rs", "py", "go", "java", "rb", "php",
567    ] {
568        let with_ext = format!("{}.{}", import_path, ext);
569        if let Some(path) = file_map.get(&with_ext) {
570            return Some(path.clone());
571        }
572    }
573
574    // Try as directory with index
575    for index_name in ["index", "mod", "__init__"] {
576        for ext in ["ts", "tsx", "js", "jsx", "rs", "py"] {
577            let index_path = format!("{}/{}.{}", import_path, index_name, ext);
578            if let Some(path) = file_map.get(&index_path) {
579                return Some(path.clone());
580            }
581        }
582    }
583
584    None
585}
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590
591    #[test]
592    fn test_extract_rust_import() {
593        assert_eq!(
594            extract_rust_import("use crate::models::Feature;"),
595            Some("crate::models::Feature".to_string())
596        );
597        assert_eq!(
598            extract_rust_import("use super::helper;"),
599            Some("super::helper".to_string())
600        );
601        assert_eq!(
602            extract_rust_import("use self::utils;"),
603            Some("self::utils".to_string())
604        );
605    }
606
607    #[test]
608    fn test_extract_javascript_import() {
609        assert_eq!(
610            extract_javascript_import("import { Feature } from './models';"),
611            Some("./models".to_string())
612        );
613        assert_eq!(
614            extract_javascript_import("const x = require('../utils');"),
615            Some("../utils".to_string())
616        );
617        assert_eq!(
618            extract_javascript_import("export { Feature } from './models';"),
619            Some("./models".to_string())
620        );
621    }
622
623    #[test]
624    fn test_extract_python_import() {
625        assert_eq!(
626            extract_python_import("from .models import Feature"),
627            Some(".models".to_string())
628        );
629        assert_eq!(
630            extract_python_import("from ..utils import helper"),
631            Some("..utils".to_string())
632        );
633    }
634
635    #[test]
636    fn test_extract_quoted_string() {
637        assert_eq!(
638            extract_quoted_string("\"./path/to/file\""),
639            Some("./path/to/file".to_string())
640        );
641        assert_eq!(
642            extract_quoted_string("'./path/to/file'"),
643            Some("./path/to/file".to_string())
644        );
645    }
646}