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::{Result, message};
7use std::{
8    fmt::{Debug, Formatter},
9    slice::Chunks,
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            // TODO: Add support for corrected commit date offset overflow.
40            //      See https://github.com/git/git/commit/e8b63005c48696a26f976f5f9b0ccaf1983e439d and
41            //          https://github.com/git/git/commit/f90fca638e99a031dce8e3aca72427b2f9b4bb38 for more details and hints at a test.
42            generation: read_u32(&bytes[file.hash_len + 8..][..4]) >> 2,
43            commit_timestamp: u64::from_be_bytes(bytes[file.hash_len + 8..][..8].try_into().unwrap())
44                & 0x0003_ffff_ffff,
45        }
46    }
47
48    /// Returns the committer timestamp of this commit.
49    ///
50    /// The value is the number of seconds since 1970-01-01 00:00:00 UTC.
51    pub fn committer_timestamp(&self) -> u64 {
52        self.commit_timestamp
53    }
54
55    /// Returns the generation number of this commit.
56    ///
57    /// Commits without parents have generation number 1. Commits with parents have a generation
58    /// number that is the max of their parents' generation numbers + 1.
59    pub fn generation(&self) -> u32 {
60        self.generation
61    }
62
63    /// Returns an iterator over the parent positions for lookup in the owning [Graph][crate::Graph].
64    pub fn iter_parents(self) -> Parents<'a> {
65        // I didn't find a combinator approach that a) was as strict as ParentIterator, b) supported
66        // fuse-after-first-error behavior, and b) was significantly shorter or more understandable
67        // than ParentIterator. So here we are.
68        Parents {
69            commit_data: self,
70            state: ParentIteratorState::First,
71        }
72    }
73
74    /// Returns the hash of this commit.
75    pub fn id(&self) -> &'a gix_hash::oid {
76        self.file.id_at(self.pos)
77    }
78
79    /// Returns the first parent of this commit.
80    pub fn parent1(&self) -> Result<Option<Position>> {
81        self.iter_parents().next().transpose()
82    }
83
84    /// Returns the position at which this commit is stored in the parent [File].
85    pub fn position(&self) -> file::Position {
86        self.pos
87    }
88
89    /// Return the hash of the tree this commit points to.
90    pub fn root_tree_id(&self) -> &gix_hash::oid {
91        self.root_tree_id
92    }
93}
94
95impl Debug for Commit<'_> {
96    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
97        write!(
98            f,
99            "Commit {{ id: {}, lex_pos: {}, generation: {}, root_tree_id: {}, parent1: {:?}, parent2: {:?} }}",
100            self.id(),
101            self.pos,
102            self.generation(),
103            self.root_tree_id(),
104            self.parent1,
105            self.parent2,
106        )
107    }
108}
109
110impl Eq for Commit<'_> {}
111
112impl PartialEq for Commit<'_> {
113    fn eq(&self, other: &Self) -> bool {
114        std::ptr::eq(self.file, other.file) && self.pos == other.pos
115    }
116}
117
118/// An iterator over parents of a [`Commit`].
119pub struct Parents<'a> {
120    commit_data: Commit<'a>,
121    state: ParentIteratorState<'a>,
122}
123
124impl Iterator for Parents<'_> {
125    type Item = Result<Position>;
126
127    fn next(&mut self) -> Option<Self::Item> {
128        let state = std::mem::replace(&mut self.state, ParentIteratorState::Exhausted);
129        match state {
130            ParentIteratorState::First => match self.commit_data.parent1 {
131                ParentEdge::None => match self.commit_data.parent2 {
132                    ParentEdge::None => None,
133                    _ => Some(Err(message!(
134                        "commit {} has a second parent but not a first parent",
135                        self.commit_data.id()
136                    )
137                    .corrupted_error())),
138                },
139                ParentEdge::GraphPosition(pos) => {
140                    self.state = ParentIteratorState::Second;
141                    Some(Ok(pos))
142                }
143                ParentEdge::ExtraEdgeIndex(_) => Some(Err(message!(
144                    "commit {}'s first parent is an extra edge index, which is invalid",
145                    self.commit_data.id(),
146                )
147                .corrupted_error())),
148            },
149            ParentIteratorState::Second => match self.commit_data.parent2 {
150                ParentEdge::None => None,
151                ParentEdge::GraphPosition(pos) => Some(Ok(pos)),
152                ParentEdge::ExtraEdgeIndex(extra_edge_index) => {
153                    if let Some(extra_edges_list) = self.commit_data.file.extra_edges_data() {
154                        let start_offset: usize = extra_edge_index
155                            .try_into()
156                            .expect("an architecture able to hold 32 bits of integer");
157                        let start_offset = start_offset
158                            .checked_mul(4)
159                            .expect("an extended edge index small enough to fit in usize");
160                        if let Some(tail) = extra_edges_list.get(start_offset..) {
161                            self.state = ParentIteratorState::Extra(tail.chunks(4));
162                            // This recursive call is what blocks me from replacing ParentIterator
163                            // with a std::iter::from_fn closure.
164                            self.next()
165                        } else {
166                            Some(Err(message!(
167                                "commit {}'s extra edges overflows the commit-graph file's extra edges list",
168                                self.commit_data.id()
169                            )
170                            .corrupted_error()))
171                        }
172                    } else {
173                        Some(Err(message!(
174                            "commit {} has extra edges, but commit-graph file has no extra edges list",
175                            self.commit_data.id()
176                        )
177                        .corrupted_error()))
178                    }
179                }
180            },
181            ParentIteratorState::Extra(mut chunks) => {
182                if let Some(chunk) = chunks.next() {
183                    let extra_edge = read_u32(chunk);
184                    match ExtraEdge::from_raw(extra_edge) {
185                        ExtraEdge::Internal(pos) => {
186                            self.state = ParentIteratorState::Extra(chunks);
187                            Some(Ok(pos))
188                        }
189                        ExtraEdge::Last(pos) => Some(Ok(pos)),
190                    }
191                } else {
192                    Some(Err(message!(
193                        "commit {}'s extra edges overflows the commit-graph file's extra edges list",
194                        self.commit_data.id()
195                    )
196                    .corrupted_error()))
197                }
198            }
199            ParentIteratorState::Exhausted => None,
200        }
201    }
202
203    fn size_hint(&self) -> (usize, Option<usize>) {
204        match (&self.state, self.commit_data.parent1, self.commit_data.parent2) {
205            (ParentIteratorState::First, ParentEdge::None, ParentEdge::None) => (0, Some(0)),
206            (ParentIteratorState::First, ParentEdge::None, _) => (1, Some(1)),
207            (ParentIteratorState::First, ParentEdge::GraphPosition(_), ParentEdge::None) => (1, Some(1)),
208            (ParentIteratorState::First, ParentEdge::GraphPosition(_), ParentEdge::GraphPosition(_)) => (2, Some(2)),
209            (ParentIteratorState::First, ParentEdge::GraphPosition(_), ParentEdge::ExtraEdgeIndex(_)) => (3, None),
210            (ParentIteratorState::First, ParentEdge::ExtraEdgeIndex(_), _) => (1, Some(1)),
211            (ParentIteratorState::Second, _, ParentEdge::None) => (0, Some(0)),
212            (ParentIteratorState::Second, _, ParentEdge::GraphPosition(_)) => (1, Some(1)),
213            (ParentIteratorState::Second, _, ParentEdge::ExtraEdgeIndex(_)) => (2, None),
214            (ParentIteratorState::Extra(_), _, _) => (1, None),
215            (ParentIteratorState::Exhausted, _, _) => (0, Some(0)),
216        }
217    }
218}
219
220#[derive(Debug)]
221enum ParentIteratorState<'a> {
222    First,
223    Second,
224    Extra(Chunks<'a, u8>),
225    Exhausted,
226}
227
228#[derive(Clone, Copy, Debug)]
229enum ParentEdge {
230    None,
231    GraphPosition(Position),
232    ExtraEdgeIndex(u32),
233}
234
235impl ParentEdge {
236    pub fn from_raw(raw: u32) -> ParentEdge {
237        if raw == NO_PARENT {
238            return ParentEdge::None;
239        }
240        if raw & EXTENDED_EDGES_MASK != 0 {
241            ParentEdge::ExtraEdgeIndex(raw & !EXTENDED_EDGES_MASK)
242        } else {
243            ParentEdge::GraphPosition(Position(raw))
244        }
245    }
246}
247
248enum ExtraEdge {
249    Internal(Position),
250    Last(Position),
251}
252
253impl ExtraEdge {
254    pub fn from_raw(raw: u32) -> Self {
255        if raw & LAST_EXTENDED_EDGE_MASK != 0 {
256            Self::Last(Position(raw & !LAST_EXTENDED_EDGE_MASK))
257        } else {
258            Self::Internal(Position(raw))
259        }
260    }
261}