_diffctx/edges/semantic/
nix.rs1use 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_nix_file(path: &Path) -> bool {
14 base::file_ext(path) == ".nix"
15}
16
17static IMPORT_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"import\s+([\./][\w./-]+)").unwrap());
18static CALL_PACKAGE_RE: Lazy<Regex> =
19 Lazy::new(|| Regex::new(r"callPackage\s+([\./][\w./-]+)").unwrap());
20static FILE_REF_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r#"\./[\w./-]+"#).unwrap());
21
22fn extract_refs(content: &str) -> FxHashSet<String> {
23 let mut refs = FxHashSet::default();
24 refs.extend(IMPORT_RE.captures_iter(content).map(|c| c[1].to_string()));
25 refs.extend(
26 CALL_PACKAGE_RE
27 .captures_iter(content)
28 .map(|c| c[1].to_string()),
29 );
30 for m in FILE_REF_RE.find_iter(content) {
31 refs.insert(m.as_str().to_string());
32 }
33 refs
34}
35
36pub struct NixEdgeBuilder;
37
38impl EdgeBuilder for NixEdgeBuilder {
39 fn build(&self, fragments: &[Fragment], repo_root: Option<&Path>) -> EdgeDict {
40 let frags: Vec<&Fragment> = fragments
41 .iter()
42 .filter(|f| is_nix_file(Path::new(f.path())))
43 .collect();
44 if frags.is_empty() {
45 return FxHashMap::default();
46 }
47
48 let import_w = EDGE_WEIGHTS["nix_import"].forward;
49 let reverse_factor = EDGE_WEIGHTS["nix_import"].reverse_factor;
50
51 let idx = base::FragmentIndex::new(fragments, repo_root);
52 let mut edges: EdgeDict = FxHashMap::default();
53
54 for f in &frags {
55 for r in extract_refs(&f.content) {
56 base::link_by_name(&f.id, &r, &idx, &mut edges, import_w, reverse_factor);
57 }
58 }
59 edges
60 }
61
62 fn discover_related_files(
63 &self,
64 changed: &[PathBuf],
65 candidates: &[PathBuf],
66 repo_root: Option<&Path>,
67 file_cache: Option<&FxHashMap<PathBuf, String>>,
68 ) -> Vec<PathBuf> {
69 let nix_changed: Vec<&PathBuf> = changed.iter().filter(|f| is_nix_file(f)).collect();
70 if nix_changed.is_empty() {
71 return vec![];
72 }
73 let mut refs = FxHashSet::default();
74 for f in &nix_changed {
75 if let Some(content) = base::read_file_cached(f, file_cache) {
76 refs.extend(extract_refs(&content));
77 }
78 }
79 discover_files_by_refs(&refs, changed, candidates, repo_root)
80 }
81}