1#![expect(missing_docs)]
16
17use std::cmp::Ordering;
18use std::fmt::Debug;
19use std::fmt::Error;
20use std::fmt::Formatter;
21use std::hash::Hash;
22use std::hash::Hasher;
23use std::sync::Arc;
24
25use futures::future::try_join_all;
26use itertools::Itertools as _;
27use pollster::FutureExt as _;
28
29use crate::backend;
30use crate::backend::BackendError;
31use crate::backend::BackendResult;
32use crate::backend::ChangeId;
33use crate::backend::CommitId;
34use crate::backend::Signature;
35use crate::backend::TreeId;
36use crate::conflict_labels::ConflictLabels;
37use crate::index::IndexResult;
38use crate::merge::Merge;
39use crate::merged_tree::MergedTree;
40use crate::repo::Repo;
41use crate::rewrite::merge_commit_trees;
42use crate::signing::SignResult;
43use crate::signing::Verification;
44use crate::store::Store;
45
46#[derive(Clone, serde::Serialize)]
47pub struct Commit {
48 #[serde(skip)]
49 store: Arc<Store>,
50 #[serde(rename = "commit_id")]
51 id: CommitId,
52 #[serde(flatten)]
53 data: Arc<backend::Commit>,
54}
55
56impl Debug for Commit {
57 fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
58 f.debug_struct("Commit").field("id", &self.id).finish()
59 }
65}
66
67impl PartialEq for Commit {
68 fn eq(&self, other: &Self) -> bool {
69 self.id == other.id
70 }
71}
72
73impl Eq for Commit {}
74
75impl Ord for Commit {
76 fn cmp(&self, other: &Self) -> Ordering {
77 self.id.cmp(&other.id)
78 }
79}
80
81impl PartialOrd for Commit {
82 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
83 Some(self.cmp(other))
84 }
85}
86
87impl Hash for Commit {
88 fn hash<H: Hasher>(&self, state: &mut H) {
89 self.id.hash(state);
90 }
91}
92
93impl Commit {
94 pub fn new(store: Arc<Store>, id: CommitId, data: Arc<backend::Commit>) -> Self {
95 Self { store, id, data }
96 }
97
98 pub fn store(&self) -> &Arc<Store> {
99 &self.store
100 }
101
102 pub fn id(&self) -> &CommitId {
103 &self.id
104 }
105
106 pub fn parent_ids(&self) -> &[CommitId] {
107 &self.data.parents
108 }
109
110 pub async fn parents(&self) -> BackendResult<Vec<Self>> {
111 try_join_all(
112 self.data
113 .parents
114 .iter()
115 .map(|id| self.store.get_commit_async(id)),
116 )
117 .await
118 }
119
120 pub fn tree(&self) -> MergedTree {
121 MergedTree::new(
122 self.store.clone(),
123 self.data.root_tree.clone(),
124 ConflictLabels::from_merge(self.data.conflict_labels.clone()),
125 )
126 }
127
128 pub fn tree_ids(&self) -> &Merge<TreeId> {
129 &self.data.root_tree
130 }
131
132 pub async fn parent_tree(&self, repo: &dyn Repo) -> BackendResult<MergedTree> {
135 if is_commit_empty_by_index(repo, &self.id)? == Some(true) {
139 return Ok(self.tree());
140 }
141 let parents = self.parents().await?;
142 merge_commit_trees(repo, &parents).await
143 }
144
145 pub fn is_empty(&self, repo: &dyn Repo) -> BackendResult<bool> {
148 if let Some(empty) = is_commit_empty_by_index(repo, &self.id)? {
149 return Ok(empty);
150 }
151 is_backend_commit_empty(repo, &self.store, &self.data)
152 }
153
154 pub fn has_conflict(&self) -> bool {
155 !self.tree_ids().is_resolved()
156 }
157
158 pub fn change_id(&self) -> &ChangeId {
159 &self.data.change_id
160 }
161
162 pub fn store_commit(&self) -> &Arc<backend::Commit> {
163 &self.data
164 }
165
166 pub fn description(&self) -> &str {
167 &self.data.description
168 }
169
170 pub fn author(&self) -> &Signature {
171 &self.data.author
172 }
173
174 pub fn committer(&self) -> &Signature {
175 &self.data.committer
176 }
177
178 pub fn is_hidden(&self, repo: &dyn Repo) -> IndexResult<bool> {
180 let maybe_targets = repo.resolve_change_id(self.change_id())?;
181 Ok(maybe_targets.is_none_or(|targets| !targets.has_visible(&self.id)))
182 }
183
184 pub fn is_discardable(&self, repo: &dyn Repo) -> BackendResult<bool> {
187 Ok(self.description().is_empty() && self.is_empty(repo)?)
188 }
189
190 pub fn is_signed(&self) -> bool {
192 self.data.secure_sig.is_some()
193 }
194
195 pub fn verification(&self) -> SignResult<Option<Verification>> {
197 self.data
198 .secure_sig
199 .as_ref()
200 .map(|sig| self.store.signer().verify(&self.id, &sig.data, &sig.sig))
201 .transpose()
202 }
203
204 pub fn conflict_label(&self) -> String {
207 if let Some(subject) = self.description().lines().next() {
208 format!(
210 "{} \"{}\"",
211 self.conflict_label_short(),
212 subject.trim().replace(char::is_control, "")
216 )
217 } else {
218 self.conflict_label_short()
219 }
220 }
221
222 fn conflict_label_short(&self) -> String {
225 format!("{:.8} {:.8}", self.change_id(), self.id())
227 }
228
229 pub async fn parents_conflict_label(&self) -> BackendResult<String> {
231 let parents = self.parents().await?;
232 Ok(conflict_label_for_commits(&parents))
233 }
234}
235
236pub fn conflict_label_for_commits(commits: &[Commit]) -> String {
240 if commits.len() == 1 {
241 commits[0].conflict_label()
242 } else {
243 commits.iter().map(Commit::conflict_label_short).join(", ")
244 }
245}
246
247pub(crate) fn is_backend_commit_empty(
248 repo: &dyn Repo,
249 store: &Arc<Store>,
250 commit: &backend::Commit,
251) -> BackendResult<bool> {
252 if let [parent_id] = &*commit.parents {
253 return Ok(commit.root_tree == *store.get_commit(parent_id)?.tree_ids());
254 }
255 let parents: Vec<_> = commit
256 .parents
257 .iter()
258 .map(|id| store.get_commit(id))
259 .try_collect()?;
260 let parent_tree = merge_commit_trees(repo, &parents).block_on()?;
261 Ok(commit.root_tree == *parent_tree.tree_ids())
262}
263
264fn is_commit_empty_by_index(repo: &dyn Repo, id: &CommitId) -> BackendResult<Option<bool>> {
265 let maybe_paths = repo
266 .index()
267 .changed_paths_in_commit(id)
268 .map_err(|err| BackendError::Other(err.into()))?;
270 Ok(maybe_paths.map(|mut paths| paths.next().is_none()))
271}
272
273pub trait CommitIteratorExt<'c, I> {
274 fn ids(self) -> impl Iterator<Item = &'c CommitId>;
275}
276
277impl<'c, I> CommitIteratorExt<'c, I> for I
278where
279 I: Iterator<Item = &'c Commit>,
280{
281 fn ids(self) -> impl Iterator<Item = &'c CommitId> {
282 self.map(|commit| commit.id())
283 }
284}
285
286#[derive(Clone, Debug, Eq, Hash, PartialEq)]
288pub(crate) struct CommitByCommitterTimestamp(pub Commit);
289
290impl Ord for CommitByCommitterTimestamp {
291 fn cmp(&self, other: &Self) -> Ordering {
292 let self_timestamp = &self.0.committer().timestamp.timestamp;
293 let other_timestamp = &other.0.committer().timestamp.timestamp;
294 self_timestamp
295 .cmp(other_timestamp)
296 .then_with(|| self.0.cmp(&other.0)) }
298}
299
300impl PartialOrd for CommitByCommitterTimestamp {
301 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
302 Some(self.cmp(other))
303 }
304}