gix_commitgraph/
verify.rs1use gix_error::Result;
3use std::{
4 cmp::{max, min},
5 collections::BTreeMap,
6};
7
8use gix_error::{ResultExt, bail};
9
10use crate::{
11 GENERATION_NUMBER_MAX, Graph,
12 file::{self},
13};
14
15#[derive(Clone, Debug, Eq, PartialEq)]
17#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
18pub struct Outcome {
19 pub longest_path_length: Option<u32>,
25 pub num_commits: u32,
27 pub parent_counts: BTreeMap<u32, u32>,
29}
30
31impl Graph {
32 pub fn verify_integrity<E>(
36 &self,
37 mut processor: impl FnMut(&file::Commit<'_>) -> std::result::Result<(), E>,
38 ) -> Result<Outcome>
39 where
40 E: std::error::Error + Send + Sync + 'static,
41 {
42 let mut stats = Outcome {
43 longest_path_length: None,
44 num_commits: 0,
45 parent_counts: BTreeMap::new(),
46 };
47 let mut max_generation = 0u32;
48
49 for (file_index, file) in self.files.iter().enumerate() {
53 if usize::from(file.base_graph_count()) != file_index {
54 bail!(
55 "\"{}\" should have {} base graphs, but claims {} base graphs".corrupted(),
56 file.path().display(),
57 file_index,
58 file.base_graph_count()
59 );
60 }
61
62 for (base_graph_index, (expected, actual)) in self
63 .files
64 .iter()
65 .take(file_index)
66 .map(crate::File::checksum)
67 .zip(file.iter_base_graph_ids())
68 .enumerate()
69 {
70 if actual != expected {
71 bail!(
72 "\"{}\" base graph at index {} should have ID {} but is {}".corrupted(),
73 file.path().display(),
74 base_graph_index,
75 expected,
76 actual
77 );
78 }
79 }
80
81 let file_stats = file.traverse(|commit| {
82 let mut max_parent_generation = 0u32;
83 let mut has_uncomputed_parent_generation = false;
84 for parent_pos in commit.iter_parents() {
85 let parent_pos = parent_pos?;
86 let parent = self.commit_at(parent_pos);
87 max_parent_generation = max(max_parent_generation, parent.generation());
88 has_uncomputed_parent_generation |= parent.generation() == 0;
89 }
90
91 if commit.generation() == 0 || has_uncomputed_parent_generation {
93 bail!(
94 "Cannot verify generation numbers for commit {} because it or a parent has an uncomputed generation".unsupported(),
95 commit.id()
96 );
97 }
98
99 let expected_generation = min(max_parent_generation + 1, GENERATION_NUMBER_MAX);
102 if commit.generation() != expected_generation {
103 bail!(
104 "Commit {}'s generation should be {expected_generation} but is {}".corrupted(),
105 commit.id(),
106 commit.generation()
107 );
108 }
109
110 processor(commit).or_error()?;
111
112 Ok(())
113 })?;
114
115 max_generation = max(max_generation, file_stats.max_generation);
116 stats.num_commits += file_stats.num_commits;
117 for (key, value) in file_stats.parent_counts.into_iter() {
118 *stats.parent_counts.entry(key).or_insert(0) += value;
119 }
120 }
121
122 stats.longest_path_length = if max_generation < GENERATION_NUMBER_MAX {
123 Some(max_generation.saturating_sub(1))
124 } else {
125 None
126 };
127 Ok(stats)
128 }
129}