Skip to main content

calcit_cli/
def_diff.rs

1use crate::program_diff::{
2  DiffNode, ProgramDiffStats, collect_stats, diff_code_entry, format_tree_node, git_root, git_show_file, parse_historical_snapshot,
3  parse_snapshot, repo_relative_path, resolve_input_path,
4};
5use calcit_core::snapshot::{CodeEntry, Snapshot};
6use calcit_core::util::string::extract_ns_def;
7use std::env;
8use std::fs;
9
10#[derive(Debug, Clone)]
11pub struct DefDiffResult {
12  pub target: String,
13  pub git_ref: String,
14  pub file_path: String,
15  pub root: DiffNode,
16  pub stats: ProgramDiffStats,
17}
18
19pub fn analyze_def_diff(target: &str, git_ref: &str, base_ref: Option<&str>, input_path: &str) -> Result<DefDiffResult, String> {
20  let cwd = env::current_dir().map_err(|e| format!("Failed to read current directory: {e}"))?;
21  let input_abs = resolve_input_path(&cwd, input_path)?;
22  let repo_search_dir = input_abs.parent().unwrap_or(cwd.as_path());
23  let repo_root = git_root(repo_search_dir)?;
24  let repo_rel_path = repo_relative_path(&input_abs, &repo_root)?;
25  let snapshot_path = repo_rel_path.to_string_lossy().to_string();
26
27  let (ns, def) = extract_ns_def(target)?;
28
29  let (old_snapshot, new_snapshot, ref_label) = match base_ref {
30    Some(base) => {
31      let base_content = git_show_file(&repo_root, base, &repo_rel_path)?;
32      let base_label = format!("{base}:{}", repo_rel_path.display());
33      let base_snapshot = parse_historical_snapshot(&base_content, &base_label, &snapshot_path)?;
34
35      let target_content = git_show_file(&repo_root, git_ref, &repo_rel_path)?;
36      let target_label = format!("{git_ref}:{}", repo_rel_path.display());
37      let target_snapshot = parse_historical_snapshot(&target_content, &target_label, &snapshot_path)?;
38
39      (base_snapshot, target_snapshot, format!("{base}..{git_ref}"))
40    }
41    None => {
42      let current_content = fs::read_to_string(&input_abs).map_err(|e| format!("Failed to read {}: {e}", input_abs.display()))?;
43      let current_snapshot = parse_snapshot(&current_content, input_path, &snapshot_path)?;
44
45      let historical_content = git_show_file(&repo_root, git_ref, &repo_rel_path)?;
46      let historical_label = format!("{git_ref}:{}", repo_rel_path.display());
47      let historical_snapshot = parse_historical_snapshot(&historical_content, &historical_label, &snapshot_path)?;
48
49      (historical_snapshot, current_snapshot, git_ref.to_string())
50    }
51  };
52
53  let old_entry = lookup_code_entry(&old_snapshot, &ns, &def);
54  let new_entry = lookup_code_entry(&new_snapshot, &ns, &def);
55
56  if old_entry.is_none() && new_entry.is_none() {
57    return Err(format!("Definition not found in file or refs: {target}"));
58  }
59
60  let mut root = diff_code_entry(&def, old_entry, new_entry);
61  root.label = target.to_string();
62  let stats = collect_stats(&root);
63
64  Ok(DefDiffResult {
65    target: target.to_string(),
66    git_ref: ref_label,
67    file_path: repo_rel_path.to_string_lossy().to_string(),
68    root,
69    stats,
70  })
71}
72
73pub fn format_def_diff(result: &DefDiffResult) -> String {
74  let mut output = String::new();
75  output.push_str("# Definition Diff\n\n");
76  output.push_str(&format!("- target: {}\n", result.target));
77  output.push_str(&format!("- ref: {}\n", result.git_ref));
78  output.push_str(&format!("- file: {}\n", result.file_path));
79  output.push_str(&format!(
80    "- changes: ~{} +{} -{} ={}\n\n",
81    result.stats.modified, result.stats.added, result.stats.removed, result.stats.unchanged
82  ));
83  output.push_str("## Tree Diff\n\n");
84  format_tree_node(&result.root, &mut output, "", true, true, true);
85  output
86}
87
88fn lookup_code_entry<'a>(snapshot: &'a Snapshot, ns: &str, def: &str) -> Option<&'a CodeEntry> {
89  snapshot.files.get(ns).and_then(|file| file.defs.get(def))
90}
91
92#[cfg(test)]
93mod tests {
94  use super::*;
95  use crate::program_diff::DiffStatus;
96  use calcit_core::calcit::CalcitTypeAnnotation;
97  use calcit_core::snapshot::{CodeEntry, FileInSnapShot, NsEntry};
98  use cirru_parser::Cirru;
99  use std::collections::HashMap;
100  use std::sync::Arc;
101
102  fn code_entry(doc: &str, schema: CalcitTypeAnnotation, code: &str) -> CodeEntry {
103    CodeEntry {
104      doc: doc.to_string(),
105      examples: vec![],
106      tests: vec![],
107      tags: std::collections::HashSet::new(),
108      code: Cirru::Leaf(Arc::from(code)),
109      schema: Arc::new(schema),
110      ffi: None,
111    }
112  }
113
114  fn snapshot_with_def(ns: &str, def: &str, entry: CodeEntry) -> Snapshot {
115    let mut snapshot = Snapshot::default();
116    let mut defs = HashMap::new();
117    defs.insert(def.to_string(), entry);
118    snapshot.files.insert(
119      ns.to_string(),
120      FileInSnapShot {
121        ns: NsEntry {
122          doc: String::new(),
123          code: Cirru::List(vec![]),
124        },
125        defs,
126      },
127    );
128    snapshot
129  }
130
131  #[test]
132  fn looks_up_definition_from_snapshot() {
133    let snapshot = snapshot_with_def("app.main", "foo", code_entry("doc", CalcitTypeAnnotation::Dynamic, "a"));
134    assert!(lookup_code_entry(&snapshot, "app.main", "foo").is_some());
135    assert!(lookup_code_entry(&snapshot, "app.main", "bar").is_none());
136  }
137
138  #[test]
139  fn diff_root_contains_doc_schema_and_code_changes() {
140    let old = code_entry("old doc", CalcitTypeAnnotation::Dynamic, "a");
141    let new = code_entry("new doc", CalcitTypeAnnotation::Number, "b");
142    let root = diff_code_entry("foo", Some(&old), Some(&new));
143    assert_eq!(root.status, DiffStatus::Modified);
144    assert!(
145      root
146        .children
147        .iter()
148        .any(|child| child.label == "doc" && child.status == DiffStatus::Modified)
149    );
150    assert!(
151      root
152        .children
153        .iter()
154        .any(|child| child.label == "schema" && child.status == DiffStatus::Modified)
155    );
156    assert!(
157      root
158        .children
159        .iter()
160        .any(|child| child.label == "code" && child.status == DiffStatus::Modified)
161    );
162  }
163}