Skip to main content

docgen_diff/
git_refs.rs

1//! Base-ref selection — a faithful port of `git-refs.ts`.
2
3/// The well-known git empty-tree object id. Used as the diff base for a
4/// parentless (first) commit, so its full content shows up as additions.
5pub const EMPTY_TREE_REF: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
6
7/// The diff base for a commit given its space-separated parent hashes:
8/// the first parent for normal and merge commits, or the empty tree when
9/// there are no parents. The `_hash` arg is unused (parity with the original).
10pub fn base_ref_for_commit_parents(_hash: &str, parents: &str) -> String {
11    parents
12        .split_whitespace()
13        .next()
14        .map(|s| s.to_string())
15        .unwrap_or_else(|| EMPTY_TREE_REF.to_string())
16}
17
18/// The diff base for a commit given its structured parent hashes: the first
19/// parent, or the empty tree when parentless. Prefer this over
20/// [`base_ref_for_commit_parents`] when the parents are already a slice — it
21/// avoids a join/split round-trip. The string variant remains the port shim for
22/// the CLI-output path that receives space-separated parents.
23pub fn base_ref_for_parents(parents: &[String]) -> String {
24    parents
25        .first()
26        .cloned()
27        .unwrap_or_else(|| EMPTY_TREE_REF.to_string())
28}
29
30#[cfg(test)]
31mod tests {
32    use super::*;
33
34    #[test]
35    fn empty_tree_for_parentless() {
36        assert_eq!(base_ref_for_commit_parents("abc123", ""), EMPTY_TREE_REF);
37    }
38
39    #[test]
40    fn first_parent_for_normal_and_merge() {
41        assert_eq!(base_ref_for_commit_parents("abc123", "parent1"), "parent1");
42        assert_eq!(
43            base_ref_for_commit_parents("abc123", "parent1 parent2"),
44            "parent1"
45        );
46    }
47
48    #[test]
49    fn base_ref_for_parents_slice() {
50        assert_eq!(base_ref_for_parents(&[]), EMPTY_TREE_REF);
51        assert_eq!(base_ref_for_parents(&["p1".to_string()]), "p1");
52        assert_eq!(
53            base_ref_for_parents(&["p1".to_string(), "p2".to_string()]),
54            "p1"
55        );
56    }
57}