Skip to main content

calcit_cli/
call_graph_diff.rs

1use crate::call_tree::{self, CallTreeNode};
2use crate::cli_args::CallGraphDiffCommand;
3use crate::program_diff::{DiffStatus, parse_historical_snapshot};
4use calcit_core::program::{self, PROGRAM_CODE_DATA};
5use calcit_core::snapshot::{CodeEntry, Snapshot, load_snapshot_data};
6use calcit_core::util::string::strip_shebang;
7use cirru_edn::Edn;
8use colored::Colorize;
9use std::collections::{HashMap, HashSet};
10use std::env;
11use std::fs;
12use std::path::{Path, PathBuf};
13use std::process::Command;
14
15#[derive(Debug, Clone)]
16pub struct CallGraphDiffNode {
17  pub fqn: String,
18  pub status: DiffStatus,
19  pub code_changed: bool,
20  pub detail: Option<String>,
21  pub children: Vec<CallGraphDiffNode>,
22}
23
24#[derive(Debug, Clone, Default)]
25pub struct CallGraphDiffStats {
26  pub unchanged: usize,
27  pub added: usize,
28  pub removed: usize,
29  pub modified: usize,
30  pub code_changed: usize,
31}
32
33#[derive(Debug, Clone)]
34pub struct CallGraphDiffResult {
35  pub git_ref: String,
36  pub file_path: String,
37  pub entry: String,
38  pub root: CallGraphDiffNode,
39  pub stats: CallGraphDiffStats,
40}
41
42pub fn analyze_call_graph_diff(cmd: &CallGraphDiffCommand, input_path: &str) -> Result<CallGraphDiffResult, String> {
43  let cwd = env::current_dir().map_err(|e| format!("Failed to read current directory: {e}"))?;
44  let input_abs = resolve_input_path(&cwd, input_path)?;
45  let repo_search_dir = input_abs.parent().unwrap_or(cwd.as_path());
46  let repo_root = git_root(repo_search_dir)?;
47  let repo_rel_path = repo_relative_path(&input_abs, &repo_root)?;
48  let snapshot_path = repo_rel_path.to_string_lossy().to_string();
49
50  let base_dir = input_abs.parent().unwrap_or(cwd.as_path());
51  let module_folder = calcit_core::project_module_folder(base_dir);
52  let core_snapshot = calcit_core::load_core_snapshot()?;
53
54  let current_content = fs::read_to_string(&input_abs).map_err(|e| format!("Failed to read {}: {e}", input_abs.display()))?;
55  let mut current_snapshot = parse_snapshot(&current_content, input_path, &snapshot_path)?;
56  attach_modules_and_core(&mut current_snapshot, base_dir, &module_folder, &core_snapshot)?;
57
58  let historical_content = git_show_file(&repo_root, &cmd.git_ref, &repo_rel_path)?;
59  let historical_label = format!("{}:{}", cmd.git_ref, repo_rel_path.display());
60  let mut historical_snapshot = parse_historical_snapshot(&historical_content, &historical_label, &snapshot_path)?;
61  attach_modules_and_core(&mut historical_snapshot, base_dir, &module_folder, &core_snapshot)?;
62
63  let (entry_ns, entry_def) = resolve_entry_point(&current_snapshot, cmd.root.as_deref())?;
64  let entry = format!("{entry_ns}/{entry_def}");
65
66  let old_graph = analyze_snapshot_call_graph(&historical_snapshot, &entry_ns, &entry_def, cmd)?;
67  let new_graph = analyze_snapshot_call_graph(&current_snapshot, &entry_ns, &entry_def, cmd)?;
68  let changed_defs = collect_changed_definitions(&historical_snapshot, &current_snapshot);
69
70  let root = diff_call_graph_node(&old_graph.tree, &new_graph.tree, &changed_defs);
71  let stats = collect_stats(&root);
72
73  Ok(CallGraphDiffResult {
74    git_ref: cmd.git_ref.to_string(),
75    file_path: repo_rel_path.to_string_lossy().to_string(),
76    entry,
77    root,
78    stats,
79  })
80}
81
82pub fn format_call_graph_diff(result: &CallGraphDiffResult) -> String {
83  let mut output = String::new();
84  output.push_str("# Call Graph Diff\n\n");
85  output.push_str(&format!("- ref: {}\n", result.git_ref));
86  output.push_str(&format!("- file: {}\n", result.file_path));
87  output.push_str(&format!("- entry: {}\n", result.entry));
88  output.push_str(&format!(
89    "- graph changes: ~{} +{} -{} ={}\n",
90    result.stats.modified, result.stats.added, result.stats.removed, result.stats.unchanged
91  ));
92  output.push_str(&format!("- code-changed reachable defs: {}\n\n", result.stats.code_changed));
93  output.push_str("## Graph Diff\n\n");
94  format_tree_node(&result.root, &mut output, "", true, true, true);
95  output
96}
97
98fn analyze_snapshot_call_graph(
99  snapshot: &Snapshot,
100  entry_ns: &str,
101  entry_def: &str,
102  cmd: &CallGraphDiffCommand,
103) -> Result<call_tree::CallTreeResult, String> {
104  let program_data = program::extract_program_data(snapshot)?;
105  {
106    let mut program = PROGRAM_CODE_DATA.write().map_err(|e| format!("Failed to open program data: {e}"))?;
107    *program = program_data;
108  }
109
110  call_tree::analyze_call_graph(
111    entry_ns,
112    entry_def,
113    cmd.include_core,
114    cmd.max_depth,
115    false,
116    Some(snapshot.package.to_string()),
117    cmd.ns_prefix.clone(),
118  )
119}
120
121fn attach_modules_and_core(
122  snapshot: &mut Snapshot,
123  base_dir: &Path,
124  module_folder: &Path,
125  core_snapshot: &Snapshot,
126) -> Result<(), String> {
127  let module_paths = snapshot.active_entry()?.modules.to_vec();
128  for module_path in &module_paths {
129    let module_data = calcit_core::load_module(module_path, base_dir, module_folder)?;
130    calcit_core::merge_project_module_files(snapshot, &module_data, module_path)?;
131  }
132
133  for (ns, file) in &core_snapshot.files {
134    snapshot.files.insert(ns.to_owned(), file.to_owned());
135  }
136
137  Ok(())
138}
139
140fn resolve_entry_point(snapshot: &Snapshot, root: Option<&str>) -> Result<(String, String), String> {
141  let entry = root.unwrap_or(snapshot.active_entry()?.init_fn.as_str());
142  let (ns, def) = entry
143    .split_once('/')
144    .ok_or_else(|| format!("Expected entry definition in format ns/def, got: {entry}"))?;
145  Ok((ns.to_string(), def.to_string()))
146}
147
148fn collect_changed_definitions(old: &Snapshot, new: &Snapshot) -> HashSet<String> {
149  let mut changed = HashSet::new();
150
151  for (ns, old_file) in &old.files {
152    if let Some(new_file) = new.files.get(ns) {
153      for (def, old_entry) in &old_file.defs {
154        if let Some(new_entry) = new_file.defs.get(def)
155          && code_entry_changed(old_entry, new_entry)
156        {
157          changed.insert(format!("{ns}/{def}"));
158        }
159      }
160    }
161  }
162
163  changed
164}
165
166fn code_entry_changed(old: &CodeEntry, new: &CodeEntry) -> bool {
167  old.code != new.code
168}
169
170fn diff_call_graph_node(old: &CallTreeNode, new: &CallTreeNode, changed_defs: &HashSet<String>) -> CallGraphDiffNode {
171  let children = diff_children(&old.calls, &new.calls, changed_defs);
172  let meta_changed = old.circular != new.circular || old.seen != new.seen || old.source != new.source;
173  let status = if meta_changed || children.iter().any(|child| child.status != DiffStatus::Unchanged) {
174    DiffStatus::Modified
175  } else {
176    DiffStatus::Unchanged
177  };
178
179  CallGraphDiffNode {
180    fqn: new.fqn.to_string(),
181    status,
182    code_changed: changed_defs.contains(&new.fqn),
183    detail: build_detail(Some(old), Some(new)),
184    children,
185  }
186}
187
188fn diff_children(
189  old_children: &[CallTreeNode],
190  new_children: &[CallTreeNode],
191  changed_defs: &HashSet<String>,
192) -> Vec<CallGraphDiffNode> {
193  let new_lookup = new_children
194    .iter()
195    .enumerate()
196    .map(|(idx, node)| (node.fqn.as_str(), idx))
197    .collect::<HashMap<_, _>>();
198  let old_lookup = old_children
199    .iter()
200    .enumerate()
201    .map(|(idx, node)| (node.fqn.as_str(), idx))
202    .collect::<HashMap<_, _>>();
203
204  let mut children = Vec::new();
205  let mut used_new = HashSet::new();
206
207  for old_child in old_children {
208    if let Some(&new_idx) = new_lookup.get(old_child.fqn.as_str()) {
209      children.push(diff_call_graph_node(old_child, &new_children[new_idx], changed_defs));
210      used_new.insert(new_idx);
211    } else {
212      children.push(build_call_graph_subtree(old_child, DiffStatus::Removed));
213    }
214  }
215
216  for (idx, new_child) in new_children.iter().enumerate() {
217    if !used_new.contains(&idx) && !old_lookup.contains_key(new_child.fqn.as_str()) {
218      children.push(build_call_graph_subtree(new_child, DiffStatus::Added));
219    }
220  }
221
222  children
223}
224
225fn build_call_graph_subtree(node: &CallTreeNode, status: DiffStatus) -> CallGraphDiffNode {
226  let children = node.calls.iter().map(|child| build_call_graph_subtree(child, status)).collect();
227  CallGraphDiffNode {
228    fqn: node.fqn.to_string(),
229    status,
230    code_changed: false,
231    detail: build_detail(None, Some(node)),
232    children,
233  }
234}
235
236fn build_detail(old: Option<&CallTreeNode>, new: Option<&CallTreeNode>) -> Option<String> {
237  match (old, new) {
238    (Some(old), Some(new)) => {
239      let old_tags = node_tags(old);
240      let new_tags = node_tags(new);
241      if old_tags == new_tags {
242        render_tags(&new_tags)
243      } else {
244        Some(format!("{} -> {}", render_tags_or_dash(&old_tags), render_tags_or_dash(&new_tags)))
245      }
246    }
247    (_, Some(node)) => render_tags(&node_tags(node)),
248    (Some(node), None) => render_tags(&node_tags(node)),
249    (None, None) => None,
250  }
251}
252
253fn node_tags(node: &CallTreeNode) -> Vec<&'static str> {
254  let mut tags = Vec::new();
255  if node.circular {
256    tags.push("CIRCULAR");
257  }
258  if node.seen {
259    tags.push("seen");
260  }
261  match node.source.as_str() {
262    "core" => tags.push("core"),
263    "external" => tags.push("ext"),
264    _ => {}
265  }
266  tags
267}
268
269fn render_tags(tags: &[&'static str]) -> Option<String> {
270  if tags.is_empty() {
271    None
272  } else {
273    Some(format!("[{}]", tags.join(", ")))
274  }
275}
276
277fn render_tags_or_dash(tags: &[&'static str]) -> String {
278  render_tags(tags).unwrap_or_else(|| "-".to_string())
279}
280
281fn collect_stats(root: &CallGraphDiffNode) -> CallGraphDiffStats {
282  fn walk(node: &CallGraphDiffNode, stats: &mut CallGraphDiffStats) {
283    match node.status {
284      DiffStatus::Unchanged => stats.unchanged += 1,
285      DiffStatus::Added => stats.added += 1,
286      DiffStatus::Removed => stats.removed += 1,
287      DiffStatus::Modified => stats.modified += 1,
288    }
289    if node.code_changed {
290      stats.code_changed += 1;
291    }
292    for child in &node.children {
293      walk(child, stats);
294    }
295  }
296
297  let mut stats = CallGraphDiffStats::default();
298  walk(root, &mut stats);
299  stats
300}
301
302fn format_tree_node(node: &CallGraphDiffNode, output: &mut String, prefix: &str, is_last: bool, expand: bool, is_root: bool) {
303  let connector = if is_root {
304    ""
305  } else if is_last {
306    "└── "
307  } else {
308    "├── "
309  };
310
311  let mut suffix = String::new();
312  if let Some(detail) = &node.detail {
313    suffix.push(' ');
314    suffix.push_str(detail);
315  }
316  if !expand && !node.children.is_empty() {
317    suffix.push_str(&format!(" {}", format!("({} folded)", descendant_count(node)).dimmed()));
318  }
319
320  let mut line = format!("{} {}", status_badge(node.status), status_paint(node.status, node.fqn.to_string()));
321  if !suffix.is_empty() {
322    line.push_str(&status_paint(node.status, suffix));
323  }
324  if node.code_changed {
325    line.push(' ');
326    line.push_str(&modified_marker());
327  }
328
329  output.push_str(&format!("{prefix}{connector}{line}\n"));
330
331  if !expand {
332    return;
333  }
334
335  let child_prefix = if is_root {
336    String::new()
337  } else {
338    format!("{}{}   ", prefix, if is_last { " " } else { "│" })
339  };
340
341  for (idx, child) in node.children.iter().enumerate() {
342    let child_expand = child.status != DiffStatus::Unchanged || has_code_changes(child);
343    format_tree_node(child, output, &child_prefix, idx + 1 == node.children.len(), child_expand, false);
344  }
345}
346
347fn has_code_changes(node: &CallGraphDiffNode) -> bool {
348  node.code_changed || node.children.iter().any(has_code_changes)
349}
350
351fn descendant_count(node: &CallGraphDiffNode) -> usize {
352  node.children.iter().map(|child| 1 + descendant_count(child)).sum()
353}
354
355fn status_badge(status: DiffStatus) -> String {
356  match status {
357    DiffStatus::Unchanged => "=".dimmed().to_string(),
358    DiffStatus::Added => "[+]".black().on_green().bold().to_string(),
359    DiffStatus::Removed => "[-]".black().on_bright_blue().bold().to_string(),
360    DiffStatus::Modified => "~".dimmed().to_string(),
361  }
362}
363
364fn status_paint(status: DiffStatus, text: String) -> String {
365  match status {
366    DiffStatus::Unchanged => text.dimmed().to_string(),
367    DiffStatus::Added => text.green().to_string(),
368    DiffStatus::Removed => text.cyan().to_string(),
369    DiffStatus::Modified => text.dimmed().to_string(),
370  }
371}
372
373fn modified_marker() -> String {
374  "[MODIFIED]".black().on_yellow().bold().to_string()
375}
376
377fn resolve_input_path(cwd: &Path, input_path: &str) -> Result<PathBuf, String> {
378  let input = Path::new(input_path);
379  let full_path = if input.is_absolute() {
380    input.to_path_buf()
381  } else {
382    cwd.join(input)
383  };
384  calcit_core::validate_snapshot_path(&full_path)?;
385  full_path
386    .canonicalize()
387    .map_err(|e| format!("Failed to resolve input path '{}': {e}", full_path.display()))
388}
389
390fn git_root(cwd: &Path) -> Result<PathBuf, String> {
391  let output = Command::new("git")
392    .current_dir(cwd)
393    .args(["rev-parse", "--show-toplevel"])
394    .output()
395    .map_err(|e| format!("Failed to run git rev-parse: {e}"))?;
396
397  if !output.status.success() {
398    let stderr = String::from_utf8_lossy(&output.stderr);
399    return Err(format!("Failed to locate git repository root: {}", stderr.trim()));
400  }
401
402  let stdout = String::from_utf8(output.stdout).map_err(|e| format!("Failed to decode git output: {e}"))?;
403  Ok(PathBuf::from(stdout.trim()))
404}
405
406fn repo_relative_path(input_abs: &Path, repo_root: &Path) -> Result<PathBuf, String> {
407  input_abs.strip_prefix(repo_root).map(|path| path.to_path_buf()).map_err(|_| {
408    format!(
409      "Input file '{}' is not inside git repository '{}'",
410      input_abs.display(),
411      repo_root.display()
412    )
413  })
414}
415
416fn git_show_file(repo_root: &Path, git_ref: &str, repo_rel_path: &Path) -> Result<String, String> {
417  let git_path = repo_rel_path.to_string_lossy().replace('\\', "/");
418  let object = format!("{git_ref}:{git_path}");
419  let output = Command::new("git")
420    .current_dir(repo_root)
421    .args(["show", &object])
422    .output()
423    .map_err(|e| format!("Failed to run git show for '{object}': {e}"))?;
424
425  if !output.status.success() {
426    let stderr = String::from_utf8_lossy(&output.stderr);
427    return Err(format!("Failed to load '{git_path}' from ref '{git_ref}': {}", stderr.trim()));
428  }
429
430  String::from_utf8(output.stdout).map_err(|e| format!("Failed to decode git show output: {e}"))
431}
432
433fn parse_snapshot(content: &str, error_label: &str, snapshot_path: &str) -> Result<Snapshot, String> {
434  let mut content = content.to_string();
435  strip_shebang(&mut content);
436  let parsed: Edn = cirru_edn::parse(&content).map_err(|e| format!("Failed to parse '{error_label}' as Cirru EDN: {e}"))?;
437  load_snapshot_data(&parsed, snapshot_path).map_err(|e| format!("Failed to load snapshot '{error_label}': {e}"))
438}
439
440#[cfg(test)]
441mod tests {
442  use super::*;
443
444  fn node(fqn: &str, calls: Vec<CallGraphDiffNode>) -> CallGraphDiffNode {
445    CallGraphDiffNode {
446      fqn: fqn.to_string(),
447      status: DiffStatus::Unchanged,
448      code_changed: false,
449      detail: None,
450      children: calls,
451    }
452  }
453
454  fn tree(fqn: &str, calls: Vec<CallTreeNode>) -> CallTreeNode {
455    let (ns, def) = fqn.split_once('/').unwrap();
456    CallTreeNode {
457      ns: ns.to_string(),
458      def: def.to_string(),
459      fqn: fqn.to_string(),
460      doc: None,
461      calls,
462      circular: false,
463      seen: false,
464      source: "project".to_string(),
465    }
466  }
467
468  #[test]
469  fn marks_code_changed_without_graph_change() {
470    colored::control::set_override(false);
471    let old = tree("app.main/main", vec![tree("app.util/helper", vec![])]);
472    let new = tree("app.main/main", vec![tree("app.util/helper", vec![])]);
473    let changed = HashSet::from(["app.util/helper".to_string()]);
474
475    let diff = diff_call_graph_node(&old, &new, &changed);
476    assert_eq!(diff.status, DiffStatus::Unchanged);
477    assert!(diff.children[0].code_changed);
478  }
479
480  #[test]
481  fn marks_added_and_removed_children() {
482    let old = tree("app.main/main", vec![tree("app.old/gone", vec![])]);
483    let new = tree("app.main/main", vec![tree("app.new/here", vec![])]);
484    let diff = diff_call_graph_node(&old, &new, &HashSet::new());
485
486    assert_eq!(diff.status, DiffStatus::Modified);
487    assert_eq!(diff.children[0].status, DiffStatus::Removed);
488    assert_eq!(diff.children[1].status, DiffStatus::Added);
489  }
490
491  #[test]
492  fn formats_code_change_badge() {
493    colored::control::set_override(false);
494    let mut root = node("app.main/main", vec![node("app.util/helper", vec![])]);
495    root.children[0].code_changed = true;
496
497    let mut output = String::new();
498    format_tree_node(&root, &mut output, "", true, true, true);
499    assert!(output.contains("[MODIFIED]"));
500  }
501}