Skip to main content

_diffctx/edges/semantic/
css.rs

1use std::path::{Path, PathBuf};
2
3use once_cell::sync::Lazy;
4use regex::Regex;
5use rustc_hash::{FxHashMap, FxHashSet};
6
7use crate::config::weights::EDGE_WEIGHTS;
8use crate::types::Fragment;
9
10use super::super::EdgeDict;
11use super::super::base::{self, EdgeBuilder, discover_files_by_refs};
12
13fn is_css_file(path: &Path) -> bool {
14    let ext = base::file_ext(path);
15    matches!(ext.as_str(), ".css" | ".scss" | ".less" | ".sass")
16}
17
18static IMPORT_RE: Lazy<Regex> =
19    Lazy::new(|| Regex::new(r#"(?m)^\s*@(?:import|use|forward)\s+['"]([^'"]+)['"]"#).unwrap());
20
21fn extract_imports(content: &str) -> FxHashSet<String> {
22    IMPORT_RE
23        .captures_iter(content)
24        .map(|c| c[1].to_string())
25        .collect()
26}
27
28pub struct CssEdgeBuilder;
29
30impl EdgeBuilder for CssEdgeBuilder {
31    fn build(&self, fragments: &[Fragment], repo_root: Option<&Path>) -> EdgeDict {
32        let frags: Vec<&Fragment> = fragments
33            .iter()
34            .filter(|f| is_css_file(Path::new(f.path())))
35            .collect();
36        if frags.is_empty() {
37            return FxHashMap::default();
38        }
39
40        let import_w = EDGE_WEIGHTS["css_import"].forward;
41        let reverse_factor = EDGE_WEIGHTS["css_import"].reverse_factor;
42
43        let idx = base::FragmentIndex::new(fragments, repo_root);
44        let mut edges: EdgeDict = FxHashMap::default();
45
46        for f in &frags {
47            for imp in extract_imports(&f.content) {
48                base::link_by_name(&f.id, &imp, &idx, &mut edges, import_w, reverse_factor);
49            }
50        }
51        edges
52    }
53
54    fn discover_related_files(
55        &self,
56        changed: &[PathBuf],
57        candidates: &[PathBuf],
58        repo_root: Option<&Path>,
59        file_cache: Option<&FxHashMap<PathBuf, String>>,
60    ) -> Vec<PathBuf> {
61        let css_changed: Vec<&PathBuf> = changed.iter().filter(|f| is_css_file(f)).collect();
62        if css_changed.is_empty() {
63            return vec![];
64        }
65        let mut refs = FxHashSet::default();
66        for f in &css_changed {
67            if let Some(content) = base::read_file_cached(f, file_cache) {
68                refs.extend(extract_imports(&content));
69            }
70        }
71        discover_files_by_refs(&refs, changed, candidates, repo_root)
72    }
73}