1use crate::{CommitId, GitError, Repository};
2
3pub(crate) const SECONDS_PER_DAY: i64 = 86_400;
4pub(crate) const TIMESTAMP_SKEW_WINDOW_SECONDS: i64 = 14 * SECONDS_PER_DAY;
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub(crate) enum WalkDecision {
8 Include,
9 Skip,
10 Stop,
11}
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum CommitRange {
15 Latest(usize),
16 CommittedSince { unix_seconds: i64 },
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct HistoryCommit {
21 pub commit: CommitId,
22 pub committed_at_unix_seconds: i64,
23}
24
25impl CommitRange {
26 pub(crate) fn decide(
27 self,
28 included_commits: usize,
29 committed_at_unix_seconds: i64,
30 ) -> WalkDecision {
31 match self {
32 CommitRange::Latest(count) => {
33 if included_commits < count {
34 WalkDecision::Include
35 } else {
36 WalkDecision::Stop
37 }
38 }
39 CommitRange::CommittedSince { unix_seconds } => {
40 if committed_at_unix_seconds >= unix_seconds {
41 WalkDecision::Include
42 } else if committed_at_unix_seconds
43 >= unix_seconds.saturating_sub(TIMESTAMP_SKEW_WINDOW_SECONDS)
44 {
45 WalkDecision::Skip
46 } else {
47 WalkDecision::Stop
48 }
49 }
50 }
51 }
52}
53
54impl Repository {
55 pub fn first_parent_history(&self, range: CommitRange) -> Result<Vec<HistoryCommit>, GitError> {
56 let head = self.repository.head_id().map_err(GitError::NoHistory)?;
57 let shallow_boundary = self
58 .repository
59 .shallow_commits()
60 .map_err(GitError::NoHistory)?;
61 let mut newest_first = Vec::new();
62 let mut next = Some(head.detach());
63 while let Some(id) = next {
64 let commit = CommitId(id);
65 let history_error = |source| GitError::History { commit, source };
66 let found = self.repository.find_commit(id).map_err(history_error)?;
67 let committed_at_unix_seconds = found.time().map_err(history_error)?.seconds;
68 match range.decide(newest_first.len(), committed_at_unix_seconds) {
69 WalkDecision::Stop => break,
70 WalkDecision::Include => {
71 newest_first.push(HistoryCommit {
72 commit,
73 committed_at_unix_seconds,
74 });
75 }
76 WalkDecision::Skip => {}
77 }
78 let beyond_shallow_boundary = shallow_boundary
79 .as_ref()
80 .is_some_and(|boundary| boundary.contains(&id));
81 next = if beyond_shallow_boundary {
82 None
83 } else {
84 found.parent_ids().next().map(|parent| parent.detach())
85 };
86 }
87 newest_first.reverse();
88 Ok(newest_first)
89 }
90}