Skip to main content

gix_commitgraph/file/
commit.rs

1//! Low-level operations on individual commits.
2use crate::{
3    File, Position,
4    file::{self, EXTENDED_EDGES_MASK, LAST_EXTENDED_EDGE_MASK, NO_PARENT},
5};
6use gix_error::{OptionExt, Result, bail, corruption, message};
7use std::{
8    fmt::{Debug, Formatter},
9    slice::Iter,
10};
11
12/// A commit as stored in a [`File`].
13#[derive(Copy, Clone)]
14pub struct Commit<'a> {
15    file: &'a File,
16    pos: file::Position,
17    // We can parse the below fields lazily if needed.
18    commit_timestamp: u64,
19    generation: u32,
20    parent1: ParentEdge,
21    parent2: ParentEdge,
22    root_tree_id: &'a gix_hash::oid,
23}
24
25#[inline]
26fn read_u32(b: &[u8]) -> u32 {
27    u32::from_be_bytes(b.try_into().unwrap())
28}
29
30impl<'a> Commit<'a> {
31    pub(crate) fn new(file: &'a File, pos: file::Position) -> Self {
32        let bytes = file.commit_data_bytes(pos);
33        Commit {
34            file,
35            pos,
36            root_tree_id: gix_hash::oid::from_bytes_unchecked(&bytes[..file.hash_len]),
37            parent1: ParentEdge::from_raw(read_u32(&bytes[file.hash_len..][..4])),
38            parent2: ParentEdge::from_raw(read_u32(&bytes[file.hash_len + 4..][..4])),
39            generation: read_u32(&bytes[file.hash_len + 8..][..4]) >> 2,
40            commit_timestamp: u64::from_be_bytes(bytes[file.hash_len + 8..][..8].try_into().unwrap())
41                & 0x0003_ffff_ffff,
42        }
43    }
44
45    /// Returns the committer timestamp of this commit.
46    ///
47    /// The value is the number of seconds since 1970-01-01 00:00:00 UTC.
48    pub fn committer_timestamp(&self) -> u64 {
49        self.commit_timestamp
50    }
51
52    /// Returns the generation number of this commit.
53    ///
54    /// Commits without parents have generation number 1. Commits with parents have a generation
55    /// number that is the max of their parents' generation numbers + 1.
56    pub fn generation(&self) -> u32 {
57        self.generation
58    }
59
60    /// Return the corrected commit date, if this file contains generation numbers version 2.
61    ///
62    /// This is the maximum of one, the commit timestamp, and each parent's corrected date plus one.
63    /// It preserves topological order even when timestamps go backwards. Check
64    /// [`Graph::corrected_commit_dates_available()`][crate::Graph::corrected_commit_dates_available]
65    /// before comparing dates from different files in a split graph.
66    /// Malformed overflow offsets, zero dates, and dates that overflow `u64` are reported as corruption.
67    pub fn corrected_commit_date(&self) -> Result<Option<u64>> {
68        let Some(start) = self.file.generation_data_offset else {
69            return Ok(None);
70        };
71        let offset = read_u32(&self.file.data[start + self.pos.0 as usize * 4..][..4]);
72        let offset = if offset & 0x8000_0000 == 0 {
73            u64::from(offset)
74        } else {
75            let data = self
76                .file
77                .generation_overflow_range
78                .as_ref()
79                .map(|range| &self.file.data[range.clone()])
80                .ok_or_raise(|| corruption("Commit-graph requires missing generation overflow data"))?;
81            let position = (offset & 0x7fff_ffff) as usize;
82            if position >= data.len() / 8 {
83                bail!(corruption("Commit-graph generation overflow position is out of bounds"));
84            }
85            u64::from_be_bytes(data[position * 8..][..8].try_into().expect("eight bytes"))
86        };
87        let date = self
88            .commit_timestamp
89            .checked_add(offset)
90            .ok_or_raise(|| corruption("Commit-graph corrected commit date overflows u64"))?;
91        if date == 0 {
92            bail!(corruption("Commit-graph corrected commit date must be positive"));
93        }
94        Ok(Some(date))
95    }
96
97    /// Returns an iterator over the parent positions for lookup in the owning [Graph][crate::Graph].
98    ///
99    /// Out-of-range parents are reported as corruption, and iteration stops after the first error.
100    /// For standalone split files, only the format's maximum position can be checked until they are
101    /// assembled into a [`Graph`][crate::Graph].
102    pub fn iter_parents(self) -> Parents<'a> {
103        // I didn't find a combinator approach that a) was as strict as ParentIterator, b) supported
104        // fuse-after-first-error behavior, and b) was significantly shorter or more understandable
105        // than ParentIterator. So here we are.
106        Parents {
107            commit_data: self,
108            state: ParentIteratorState::First,
109        }
110    }
111
112    /// Returns the hash of this commit.
113    pub fn id(&self) -> &'a gix_hash::oid {
114        self.file.id_at(self.pos)
115    }
116
117    /// Returns the first parent of this commit.
118    pub fn parent1(&self) -> Result<Option<Position>> {
119        self.iter_parents().next().transpose()
120    }
121
122    /// Returns the position at which this commit is stored in the parent [File].
123    pub fn position(&self) -> file::Position {
124        self.pos
125    }
126
127    /// Return the hash of the tree this commit points to.
128    pub fn root_tree_id(&self) -> &gix_hash::oid {
129        self.root_tree_id
130    }
131}
132
133impl Debug for Commit<'_> {
134    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
135        write!(
136            f,
137            "Commit {{ id: {}, lex_pos: {}, generation: {}, root_tree_id: {}, parent1: {:?}, parent2: {:?} }}",
138            self.id(),
139            self.pos,
140            self.generation(),
141            self.root_tree_id(),
142            self.parent1,
143            self.parent2,
144        )
145    }
146}
147
148impl Eq for Commit<'_> {}
149
150impl PartialEq for Commit<'_> {
151    fn eq(&self, other: &Self) -> bool {
152        std::ptr::eq(self.file, other.file) && self.pos == other.pos
153    }
154}
155
156/// An iterator over parents of a [`Commit`].
157pub struct Parents<'a> {
158    commit_data: Commit<'a>,
159    state: ParentIteratorState<'a>,
160}
161
162impl Iterator for Parents<'_> {
163    type Item = Result<Position>;
164
165    fn next(&mut self) -> Option<Self::Item> {
166        let state = std::mem::replace(&mut self.state, ParentIteratorState::Exhausted);
167        let parent = match state {
168            ParentIteratorState::First => match self.commit_data.parent1 {
169                ParentEdge::None => match self.commit_data.parent2 {
170                    ParentEdge::None => None,
171                    _ => Some(Err(message!(
172                        "commit {} has a second parent but not a first parent",
173                        self.commit_data.id()
174                    )
175                    .corrupted_error())),
176                },
177                ParentEdge::GraphPosition(pos) => {
178                    self.state = ParentIteratorState::Second;
179                    Some(Ok(pos))
180                }
181                ParentEdge::ExtraEdgeIndex(_) => Some(Err(message!(
182                    "commit {}'s first parent is an extra edge index, which is invalid",
183                    self.commit_data.id(),
184                )
185                .corrupted_error())),
186            },
187            ParentIteratorState::Second => match self.commit_data.parent2 {
188                ParentEdge::None => None,
189                ParentEdge::GraphPosition(pos) => Some(Ok(pos)),
190                ParentEdge::ExtraEdgeIndex(extra_edge_index) => {
191                    if let Some(extra_edges_list) = self.commit_data.file.extra_edges_data() {
192                        let tail = usize::try_from(extra_edge_index)
193                            .ok()
194                            .and_then(|index| index.checked_mul(4))
195                            .and_then(|start_offset| extra_edges_list.get(start_offset..));
196                        if let Some(tail) = tail {
197                            self.state = ParentIteratorState::Extra(tail.as_chunks::<4>().0.iter());
198                            // This recursive call is what blocks me from replacing ParentIterator
199                            // with a std::iter::from_fn closure.
200                            self.next()
201                        } else {
202                            Some(Err(message!(
203                                "commit {}'s extra edges overflows the commit-graph file's extra edges list",
204                                self.commit_data.id()
205                            )
206                            .corrupted_error()))
207                        }
208                    } else {
209                        Some(Err(message!(
210                            "commit {} has extra edges, but commit-graph file has no extra edges list",
211                            self.commit_data.id()
212                        )
213                        .corrupted_error()))
214                    }
215                }
216            },
217            ParentIteratorState::Extra(mut chunks) => {
218                if let Some(chunk) = chunks.next() {
219                    let extra_edge = read_u32(chunk);
220                    match ExtraEdge::from_raw(extra_edge) {
221                        ExtraEdge::Internal(pos) => {
222                            self.state = ParentIteratorState::Extra(chunks);
223                            Some(Ok(pos))
224                        }
225                        ExtraEdge::Last(pos) => Some(Ok(pos)),
226                    }
227                } else {
228                    Some(Err(message!(
229                        "commit {}'s extra edges overflows the commit-graph file's extra edges list",
230                        self.commit_data.id()
231                    )
232                    .corrupted_error()))
233                }
234            }
235            ParentIteratorState::Exhausted => None,
236        };
237        if let Some(Ok(pos)) = &parent
238            && pos.0 >= self.commit_data.file.parent_position_limit
239        {
240            self.state = ParentIteratorState::Exhausted;
241            return Some(Err(message!(
242                "Commit {} has parent position {pos} that is out of range (should be less than {})",
243                self.commit_data.id(),
244                self.commit_data.file.parent_position_limit
245            )
246            .corrupted_error()));
247        }
248        parent
249    }
250
251    fn size_hint(&self) -> (usize, Option<usize>) {
252        match (&self.state, self.commit_data.parent1, self.commit_data.parent2) {
253            (ParentIteratorState::First, ParentEdge::None, ParentEdge::None) => (0, Some(0)),
254            (ParentIteratorState::First, ParentEdge::None, _) => (1, Some(1)),
255            (ParentIteratorState::First, ParentEdge::GraphPosition(_), ParentEdge::None) => (1, Some(1)),
256            (ParentIteratorState::First, ParentEdge::GraphPosition(_), ParentEdge::GraphPosition(_)) => (1, Some(2)),
257            (ParentIteratorState::First, ParentEdge::GraphPosition(_), ParentEdge::ExtraEdgeIndex(_)) => (1, None),
258            (ParentIteratorState::First, ParentEdge::ExtraEdgeIndex(_), _) => (1, Some(1)),
259            (ParentIteratorState::Second, _, ParentEdge::None) => (0, Some(0)),
260            (ParentIteratorState::Second, _, ParentEdge::GraphPosition(_)) => (1, Some(1)),
261            (ParentIteratorState::Second, _, ParentEdge::ExtraEdgeIndex(_)) => (1, None),
262            (ParentIteratorState::Extra(_), _, _) => (1, None),
263            (ParentIteratorState::Exhausted, _, _) => (0, Some(0)),
264        }
265    }
266}
267
268#[derive(Debug)]
269enum ParentIteratorState<'a> {
270    /// Read the first inline parent edge, or finish if both inline edges indicate no parents.
271    First,
272    /// Read the second inline parent edge, which may point to a parent or into the EDGE chunk.
273    Second,
274    /// Read remaining big-endian parent entries from the EDGE chunk until the last-edge marker.
275    /// Reaching the end of the slice without that marker is corruption.
276    Extra(Iter<'a, [u8; 4]>),
277    /// Yield no further items after the last parent, the absence of a parent, or an error.
278    Exhausted,
279}
280
281#[derive(Clone, Copy, Debug)]
282enum ParentEdge {
283    None,
284    GraphPosition(Position),
285    ExtraEdgeIndex(u32),
286}
287
288impl ParentEdge {
289    pub fn from_raw(raw: u32) -> ParentEdge {
290        if raw == NO_PARENT {
291            return ParentEdge::None;
292        }
293        if raw & EXTENDED_EDGES_MASK != 0 {
294            ParentEdge::ExtraEdgeIndex(raw & !EXTENDED_EDGES_MASK)
295        } else {
296            ParentEdge::GraphPosition(Position(raw))
297        }
298    }
299}
300
301enum ExtraEdge {
302    Internal(Position),
303    Last(Position),
304}
305
306impl ExtraEdge {
307    pub fn from_raw(raw: u32) -> Self {
308        if raw & LAST_EXTENDED_EDGE_MASK != 0 {
309            Self::Last(Position(raw & !LAST_EXTENDED_EDGE_MASK))
310        } else {
311            Self::Internal(Position(raw))
312        }
313    }
314}