Skip to main content

cha_core/plugins/
inappropriate_intimacy.rs

1use std::collections::HashMap;
2
3use crate::{AnalysisContext, Finding, Location, Plugin, Severity, SmellCategory};
4
5/// Detect bidirectional imports between files (inappropriate intimacy).
6/// Requires multi-file context: accumulates import data across files.
7pub struct InappropriateIntimacyAnalyzer;
8
9impl Default for InappropriateIntimacyAnalyzer {
10    fn default() -> Self {
11        Self
12    }
13}
14
15impl Plugin for InappropriateIntimacyAnalyzer {
16    fn name(&self) -> &str {
17        "inappropriate_intimacy"
18    }
19
20    fn description(&self) -> &str {
21        "Bidirectional imports between files"
22    }
23
24    fn analyze(&self, ctx: &AnalysisContext) -> Vec<Finding> {
25        let current = normalize_path(&ctx.file.path.to_string_lossy());
26        let mut checked: HashMap<String, Vec<String>> = HashMap::new();
27        ctx.model
28            .imports
29            .iter()
30            .filter_map(|imp| {
31                let target = resolve_import(&ctx.file.path.to_string_lossy(), &imp.source);
32                if target.is_empty() {
33                    return None;
34                }
35                let reverse = checked
36                    .entry(target.clone())
37                    .or_insert_with(|| read_file_imports(&target));
38                let has_cycle = reverse
39                    .iter()
40                    .any(|ri| normalize_path(&resolve_import(&target, ri)) == current);
41                has_cycle.then(|| make_finding(ctx, imp, &current))
42            })
43            .collect()
44    }
45}
46
47fn make_finding(ctx: &AnalysisContext, imp: &crate::ImportInfo, current: &str) -> Finding {
48    Finding {
49        smell_name: "inappropriate_intimacy".into(),
50        category: SmellCategory::Couplers,
51        severity: Severity::Warning,
52        location: Location {
53            path: ctx.file.path.clone(),
54            start_line: imp.line,
55            end_line: imp.line,
56            name: None,
57        },
58        message: format!(
59            "Bidirectional dependency between `{}` and `{}`, consider Move Method or Hide Delegate",
60            current, imp.source
61        ),
62        suggested_refactorings: vec!["Move Method".into(), "Hide Delegate".into()],
63        ..Default::default()
64    }
65}
66
67fn normalize_path(p: &str) -> String {
68    p.replace('\\', "/").trim_start_matches("./").to_string()
69}
70
71fn normalize_import(source: &str) -> String {
72    source
73        .trim_matches('"')
74        .trim_matches('\'')
75        .replace('\\', "/")
76        .to_string()
77}
78
79/// Resolve a relative import path against a base file path.
80fn resolve_import(base: &str, import: &str) -> String {
81    if !import.starts_with('.') {
82        return String::new(); // skip non-relative imports
83    }
84    let base_dir = std::path::Path::new(base)
85        .parent()
86        .unwrap_or(std::path::Path::new(""));
87    let resolved = base_dir.join(import);
88    // Try common extensions
89    for ext in &["", ".ts", ".tsx", ".rs"] {
90        let with_ext = format!("{}{}", resolved.to_string_lossy(), ext);
91        if std::path::Path::new(&with_ext).exists() {
92            return normalize_path(&with_ext);
93        }
94    }
95    normalize_path(&resolved.to_string_lossy())
96}
97
98/// Read import sources from a file (lightweight grep, no full parse).
99fn read_file_imports(path: &str) -> Vec<String> {
100    let content = match std::fs::read_to_string(path) {
101        Ok(c) => c,
102        Err(_) => return vec![],
103    };
104    content
105        .lines()
106        .filter_map(|line| {
107            let trimmed = line.trim();
108            // Match: import ... from "..." or use ...;
109            if trimmed.starts_with("import")
110                && let Some(from_idx) = trimmed.find("from")
111            {
112                let rest = trimmed[from_idx + 4..].trim().trim_matches(';');
113                return Some(normalize_import(rest));
114            }
115            None
116        })
117        .collect()
118}