Skip to main content

code_atlas/
model.rs

1use std::{
2    collections::{BTreeMap, HashMap},
3    fmt,
4    path::{Path, PathBuf},
5    str::FromStr,
6};
7
8use anyhow::{Result, bail};
9use serde::{Deserialize, Serialize};
10
11pub type NodeId = usize;
12
13#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
14pub struct Rect {
15    pub x0: f64,
16    pub y0: f64,
17    pub x1: f64,
18    pub y1: f64,
19}
20
21impl Rect {
22    pub fn width(self) -> f64 {
23        (self.x1 - self.x0).max(0.0)
24    }
25
26    pub fn height(self) -> f64 {
27        (self.y1 - self.y0).max(0.0)
28    }
29
30    pub fn area(self) -> f64 {
31        self.width() * self.height()
32    }
33
34    pub fn center(self) -> Point {
35        Point {
36            x: (self.x0 + self.x1) * 0.5,
37            y: (self.y0 + self.y1) * 0.5,
38        }
39    }
40
41    pub fn inset(self, amount: f64) -> Self {
42        let x = amount.min(self.width() * 0.22);
43        let y = amount.min(self.height() * 0.22);
44        Self {
45            x0: self.x0 + x,
46            y0: self.y0 + y,
47            x1: self.x1 - x,
48            y1: self.y1 - y,
49        }
50    }
51}
52
53#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
54pub struct Point {
55    pub x: f64,
56    pub y: f64,
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
60pub enum NodeKind {
61    Directory,
62    File,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct Node {
67    pub id: NodeId,
68    pub parent: Option<NodeId>,
69    pub children: Vec<NodeId>,
70    pub kind: NodeKind,
71    pub name: String,
72    pub path: String,
73    pub depth: usize,
74    pub bytes: u64,
75    pub loc: u64,
76    pub commits: u64,
77    pub weight: f64,
78    pub language: String,
79    pub rect: Rect,
80}
81
82impl Node {
83    pub fn is_file(&self) -> bool {
84        self.kind == NodeKind::File
85    }
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct Callsite {
90    pub id: u64,
91    pub source: NodeId,
92    pub source_line: u32,
93    pub target: NodeId,
94    pub target_line: Option<u32>,
95    pub callee: String,
96    pub kind: String,
97    pub analyzer: String,
98    pub confidence: f32,
99}
100
101#[derive(Debug, Clone, Default, Serialize, Deserialize)]
102pub struct AnalyzerReport {
103    pub elixir_files_traced: usize,
104    pub elixir_script_files_scanned: usize,
105    #[serde(default)]
106    pub erlang_files_scanned: usize,
107    pub typescript_files_scanned: usize,
108    pub gleam_files_scanned: usize,
109    pub rust_files_scanned: usize,
110    pub resolved_calls: usize,
111    pub unresolved_calls: usize,
112    pub rustler_calls: usize,
113    pub rust_calls: usize,
114    pub typescript_calls: usize,
115    pub gleam_calls: usize,
116    #[serde(default)]
117    pub erlang_calls: usize,
118    #[serde(default)]
119    pub same_file_calls_excluded: usize,
120    pub cache_hit: bool,
121    pub warnings: Vec<String>,
122    #[serde(default)]
123    pub language_coverage: BTreeMap<String, LanguageCoverage>,
124}
125
126#[derive(Debug, Clone, Default, Serialize, Deserialize)]
127pub struct LanguageCoverage {
128    pub provider: String,
129    pub fidelity: String,
130    pub files_discovered: usize,
131    pub files_analyzed: usize,
132    pub callsites_resolved: usize,
133    pub callsites_unresolved: usize,
134}
135
136#[derive(Debug, Clone, Default, Serialize, Deserialize)]
137pub struct BuildTimings {
138    pub scan_ms: u64,
139    pub analyze_ms: u64,
140}
141
142#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct Atlas {
144    pub root_path: PathBuf,
145    pub revision: String,
146    pub dirty: bool,
147    pub excluded_test_files: usize,
148    pub excluded_hidden_files: usize,
149    pub excluded_custom_files: usize,
150    pub excluded_paths: Vec<String>,
151    pub nodes: Vec<Node>,
152    pub calls: Vec<Callsite>,
153    pub path_to_id: HashMap<String, NodeId>,
154    pub report: AnalyzerReport,
155    pub timings: BuildTimings,
156}
157
158impl Atlas {
159    pub fn files(&self) -> impl Iterator<Item = &Node> {
160        self.nodes.iter().filter(|node| node.is_file())
161    }
162
163    pub fn total_loc(&self) -> u64 {
164        self.files().map(|node| node.loc).sum()
165    }
166
167    /// Retain calls matching repository-relative endpoint path filters.
168    ///
169    /// Values inside one filter group are ORed; non-empty groups are ANDed.
170    /// A prefix matches either one file exactly or every file below a directory.
171    pub fn filter_calls(&mut self, filters: &CallPathFilters) -> usize {
172        let before = self.calls.len();
173        self.calls.retain(|call| {
174            let source = &self.nodes[call.source].path;
175            let target = &self.nodes[call.target].path;
176            filters.matches(source, target)
177        });
178        before - self.calls.len()
179    }
180
181    pub fn hierarchy_path(&self, source: NodeId, target: NodeId) -> Vec<NodeId> {
182        let mut source_chain = Vec::new();
183        let mut current = Some(source);
184        while let Some(id) = current {
185            source_chain.push(id);
186            current = self.nodes[id].parent;
187        }
188
189        let mut target_chain = Vec::new();
190        current = Some(target);
191        while let Some(id) = current {
192            target_chain.push(id);
193            current = self.nodes[id].parent;
194        }
195
196        let target_positions: HashMap<NodeId, usize> = target_chain
197            .iter()
198            .copied()
199            .enumerate()
200            .map(|(index, id)| (id, index))
201            .collect();
202
203        let (source_lca_index, target_lca_index) = source_chain
204            .iter()
205            .enumerate()
206            .find_map(|(source_index, id)| {
207                target_positions
208                    .get(id)
209                    .copied()
210                    .map(|target_index| (source_index, target_index))
211            })
212            .unwrap_or((source_chain.len() - 1, target_chain.len() - 1));
213
214        let mut path = source_chain[..=source_lca_index].to_vec();
215        path.extend(target_chain[..target_lca_index].iter().rev().copied());
216        path
217    }
218}
219
220#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
221pub struct CallPathFilters {
222    pub sources: Vec<String>,
223    pub targets: Vec<String>,
224    pub paths: Vec<String>,
225}
226
227impl CallPathFilters {
228    pub fn new(sources: &[String], targets: &[String], paths: &[String]) -> Result<Self> {
229        Ok(Self {
230            sources: normalize_call_paths(sources)?,
231            targets: normalize_call_paths(targets)?,
232            paths: normalize_call_paths(paths)?,
233        })
234    }
235
236    pub fn is_empty(&self) -> bool {
237        self.sources.is_empty() && self.targets.is_empty() && self.paths.is_empty()
238    }
239
240    pub fn matches(&self, source: &str, target: &str) -> bool {
241        (self.sources.is_empty() || self.sources.iter().any(|path| path_matches(source, path)))
242            && (self.targets.is_empty()
243                || self.targets.iter().any(|path| path_matches(target, path)))
244            && (self.paths.is_empty()
245                || self
246                    .paths
247                    .iter()
248                    .any(|path| path_matches(source, path) || path_matches(target, path)))
249    }
250}
251
252fn normalize_call_paths(paths: &[String]) -> Result<Vec<String>> {
253    let mut normalized = Vec::new();
254    for path in paths {
255        let path = path.trim().replace('\\', "/");
256        let path = path.trim_matches('/');
257        if path.is_empty() {
258            bail!("call filter paths cannot be empty");
259        }
260        if Path::new(path).is_absolute()
261            || path
262                .split('/')
263                .any(|component| component == ".." || component.is_empty())
264        {
265            bail!("call filter {path:?} must be a repository-relative path");
266        }
267        if !normalized.iter().any(|existing| existing == path) {
268            normalized.push(path.to_owned());
269        }
270    }
271    normalized.sort();
272    Ok(normalized)
273}
274
275fn path_matches(path: &str, filter: &str) -> bool {
276    path == filter
277        || path
278            .strip_prefix(filter)
279            .is_some_and(|suffix| suffix.starts_with('/'))
280}
281
282#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283pub enum Metric {
284    Loc,
285    Bytes,
286    Commits,
287}
288
289impl Metric {
290    pub fn value(self, bytes: u64, loc: u64, commits: u64) -> f64 {
291        let raw = match self {
292            Self::Loc => loc,
293            Self::Bytes => bytes,
294            Self::Commits => commits,
295        };
296        (raw.max(1) as f64).sqrt()
297    }
298}
299
300impl fmt::Display for Metric {
301    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
302        formatter.write_str(match self {
303            Self::Loc => "loc",
304            Self::Bytes => "bytes",
305            Self::Commits => "commits",
306        })
307    }
308}
309
310impl FromStr for Metric {
311    type Err = anyhow::Error;
312
313    fn from_str(value: &str) -> Result<Self> {
314        match value {
315            "loc" => Ok(Self::Loc),
316            "bytes" => Ok(Self::Bytes),
317            "commits" => Ok(Self::Commits),
318            _ => bail!("unknown metric {value:?}; expected loc, bytes, or commits"),
319        }
320    }
321}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326
327    #[test]
328    fn call_path_filters_or_within_groups_and_across_groups() {
329        let filters = CallPathFilters::new(
330            &["apps/billing".to_owned(), "apps/payments".to_owned()],
331            &["lib/notifications.ex".to_owned()],
332            &[],
333        )
334        .unwrap();
335
336        assert!(filters.matches("apps/billing/invoice.ex", "lib/notifications.ex"));
337        assert!(filters.matches("apps/payments/card.ex", "lib/notifications.ex"));
338        assert!(!filters.matches("apps/search/query.ex", "lib/notifications.ex"));
339        assert!(!filters.matches("apps/billing/invoice.ex", "lib/audit.ex"));
340    }
341
342    #[test]
343    fn call_path_filter_matches_either_endpoint_on_component_boundaries() {
344        let filters = CallPathFilters::new(&[], &[], &["apps/pay".to_owned()]).unwrap();
345
346        assert!(filters.matches("apps/pay/source.ex", "lib/target.ex"));
347        assert!(filters.matches("lib/source.ex", "apps/pay/target.ex"));
348        assert!(!filters.matches("apps/payments/source.ex", "lib/target.ex"));
349    }
350}