Debian Codegraph @

src/commit.rs

raw
1 use std::iter::FusedIterator;
2 use std::marker;
3 use std::mem;
4 use std::ops::Range;
5 use std::ptr;
6 use std::str;
7
8 use crate::util::Binding;
9 use crate::{raw, signature, Buf, Error, IntoCString, Mailmap, Object, Oid, Signature, Time, Tree};
10
11 /// A structure to represent a git [commit][1]
12 ///
13 /// [1]: http://git-scm.com/book/en/Git-Internals-Git-Objects
14 pub struct Commit<'repo> {
15 raw: *mut raw::git_commit,
16 _marker: marker::PhantomData<Object<'repo>>,
17 }
18
19 /// An iterator over the parent commits of a commit.
20 ///
21 /// Aborts iteration when a commit cannot be found
22 pub struct Parents<'commit, 'repo> {
23 range: Range<usize>,
24 commit: &'commit Commit<'repo>,
25 }
26
27 /// An iterator over the parent commits' ids of a commit.
28 ///
29 /// Aborts iteration when a commit cannot be found
30 pub struct ParentIds<'commit> {
31 range: Range<usize>,
32 commit: &'commit Commit<'commit>,
33 }
34
35 impl<'repo> Commit<'repo> {
36 /// Get the id (SHA1) of a repository commit
37 pub fn id(&self) -> Oid {
38 unsafe { Binding::from_raw(raw::git_commit_id(&*self.raw)) }
39 }
40
41 /// Get the id of the tree pointed to by this commit.
42 ///
43 /// No attempts are made to fetch an object from the ODB.
44 pub fn tree_id(&self) -> Oid {
45 unsafe { Binding::from_raw(raw::git_commit_tree_id(&*self.raw)) }
46 }
47
48 /// Get the tree pointed to by a commit.
49 pub fn tree(&self) -> Result<Tree<'repo>, Error> {
50 let mut ret = ptr::null_mut();
51 unsafe {
52 try_call!(raw::git_commit_tree(&mut ret, &*self.raw));
53 Ok(Binding::from_raw(ret))
54 }
55 }
56
57 /// Get access to the underlying raw pointer.
58 pub fn raw(&self) -> *mut raw::git_commit {
59 self.raw
60 }
61
62 /// Get the full message of a commit.
63 ///
64 /// The returned message will be slightly prettified by removing any
65 /// potential leading newlines.
66 pub fn message(&self) -> Result<&str, Error> {
67 str::from_utf8(self.message_bytes()).map_err(|e| e.into())
68 }
69
70 /// Get the full message of a commit as a byte slice.
71 ///
72 /// The returned message will be slightly prettified by removing any
73 /// potential leading newlines.
74 pub fn message_bytes(&self) -> &[u8] {
75 unsafe { crate::opt_bytes(self, raw::git_commit_message(&*self.raw)).unwrap() }
76 }
77
78 /// Get the encoding for the message of a commit, as a string representing a
79 /// standard encoding name.
80 ///
81 /// `Ok(None)` will be returned if the encoding is not known
82 pub fn message_encoding(&self) -> Result<Option<&str>, Error> {
83 let bytes = unsafe { crate::opt_bytes(self, raw::git_commit_message_encoding(&*self.raw)) };
84 match bytes {
85 Some(b) => str::from_utf8(b).map(|s| Some(s)).map_err(|e| e.into()),
86 None => Ok(None),
87 }
88 }
89
90 /// Get the full raw message of a commit.
91 pub fn message_raw(&self) -> Result<&str, Error> {
92 str::from_utf8(self.message_raw_bytes()).map_err(|e| e.into())
93 }
94
95 /// Get the full raw message of a commit.
96 pub fn message_raw_bytes(&self) -> &[u8] {
97 unsafe { crate::opt_bytes(self, raw::git_commit_message_raw(&*self.raw)).unwrap() }
98 }
99
100 /// Get the full raw text of the commit header.
101 pub fn raw_header(&self) -> Result<&str, Error> {
102 str::from_utf8(self.raw_header_bytes()).map_err(|e| e.into())
103 }
104
105 /// Get an arbitrary header field.
106 pub fn header_field_bytes<T: IntoCString>(&self, field: T) -> Result<Buf, Error> {
107 let buf = Buf::new();
108 let raw_field = field.into_c_string()?;
109 unsafe {
110 try_call!(raw::git_commit_header_field(
111 buf.raw(),
112 &*self.raw,
113 raw_field
114 ));
115 }
116 Ok(buf)
117 }
118
119 /// Get the full raw text of the commit header.
120 pub fn raw_header_bytes(&self) -> &[u8] {
121 unsafe { crate::opt_bytes(self, raw::git_commit_raw_header(&*self.raw)).unwrap() }
122 }
123
124 /// Get the short "summary" of the git commit message.
125 ///
126 /// The returned message is the summary of the commit, comprising the first
127 /// paragraph of the message with whitespace trimmed and squashed.
128 ///
129 /// `Ok(None)` may be returned if there is no summary
130 pub fn summary(&self) -> Result<Option<&str>, Error> {
131 match self.summary_bytes() {
132 Some(sb) => str::from_utf8(sb).map(|s| Some(s)).map_err(|e| e.into()),
133 None => Ok(None),
134 }
135 }
136
137 /// Get the short "summary" of the git commit message.
138 ///
139 /// The returned message is the summary of the commit, comprising the first
140 /// paragraph of the message with whitespace trimmed and squashed.
141 ///
142 /// `None` may be returned if an error occurs
143 pub fn summary_bytes(&self) -> Option<&[u8]> {
144 unsafe { crate::opt_bytes(self, raw::git_commit_summary(self.raw)) }
145 }
146
147 /// Get the long "body" of the git commit message.
148 ///
149 /// The returned message is the body of the commit, comprising everything
150 /// but the first paragraph of the message. Leading and trailing whitespaces
151 /// are trimmed.
152 ///
153 /// `Ok(None)` may be returned if there is no body.
154 pub fn body(&self) -> Result<Option<&str>, Error> {
155 match self.body_bytes() {
156 Some(sb) => str::from_utf8(sb).map(|s| Some(s)).map_err(|e| e.into()),
157 None => Ok(None),
158 }
159 }
160
161 /// Get the long "body" of the git commit message.
162 ///
163 /// The returned message is the body of the commit, comprising everything
164 /// but the first paragraph of the message. Leading and trailing whitespaces
165 /// are trimmed.
166 ///
167 /// `None` may be returned if an error occurs.
168 pub fn body_bytes(&self) -> Option<&[u8]> {
169 unsafe { crate::opt_bytes(self, raw::git_commit_body(self.raw)) }
170 }
171
172 /// Get the commit time (i.e. committer time) of a commit.
173 ///
174 /// The first element of the tuple is the time, in seconds, since the epoch.
175 /// The second element is the offset, in minutes, of the time zone of the
176 /// committer's preferred time zone.
177 pub fn time(&self) -> Time {
178 unsafe {
179 Time::new(
180 raw::git_commit_time(&*self.raw) as i64,
181 raw::git_commit_time_offset(&*self.raw) as i32,
182 )
183 }
184 }
185
186 /// Creates a new iterator over the parents of this commit.
187 pub fn parents<'a>(&'a self) -> Parents<'a, 'repo> {
188 Parents {
189 range: 0..self.parent_count(),
190 commit: self,
191 }
192 }
193
194 /// Creates a new iterator over the parents of this commit.
195 pub fn parent_ids(&self) -> ParentIds<'_> {
196 ParentIds {
197 range: 0..self.parent_count(),
198 commit: self,
199 }
200 }
201
202 /// Get the author of this commit.
203 pub fn author(&self) -> Signature<'_> {
204 unsafe {
205 let ptr = raw::git_commit_author(&*self.raw);
206 signature::from_raw_const(self, ptr)
207 }
208 }
209
210 /// Get the author of this commit, using the mailmap to map names and email
211 /// addresses to canonical real names and email addresses.
212 pub fn author_with_mailmap(&self, mailmap: &Mailmap) -> Result<Signature<'static>, Error> {
213 let mut ret = ptr::null_mut();
214 unsafe {
215 try_call!(raw::git_commit_author_with_mailmap(
216 &mut ret,
217 &*self.raw,
218 &*mailmap.raw()
219 ));
220 Ok(Binding::from_raw(ret))
221 }
222 }
223
224 /// Get the committer of this commit.
225 pub fn committer(&self) -> Signature<'_> {
226 unsafe {
227 let ptr = raw::git_commit_committer(&*self.raw);
228 signature::from_raw_const(self, ptr)
229 }
230 }
231
232 /// Get the committer of this commit, using the mailmap to map names and email
233 /// addresses to canonical real names and email addresses.
234 pub fn committer_with_mailmap(&self, mailmap: &Mailmap) -> Result<Signature<'static>, Error> {
235 let mut ret = ptr::null_mut();
236 unsafe {
237 try_call!(raw::git_commit_committer_with_mailmap(
238 &mut ret,
239 &*self.raw,
240 &*mailmap.raw()
241 ));
242 Ok(Binding::from_raw(ret))
243 }
244 }
245
246 /// Amend this existing commit with all non-`None` values
247 ///
248 /// This creates a new commit that is exactly the same as the old commit,
249 /// except that any non-`None` values will be updated. The new commit has
250 /// the same parents as the old commit.
251 ///
252 /// For information about `update_ref`, see [`Repository::commit`].
253 ///
254 /// [`Repository::commit`]: struct.Repository.html#method.commit
255 pub fn amend(
256 &self,
257 update_ref: Option<&str>,
258 author: Option<&Signature<'_>>,
259 committer: Option<&Signature<'_>>,
260 message_encoding: Option<&str>,
261 message: Option<&str>,
262 tree: Option<&Tree<'repo>>,
263 ) -> Result<Oid, Error> {
264 let mut raw = crate::util::zeroed_raw_oid();
265 let update_ref = crate::opt_cstr(update_ref)?;
266 let encoding = crate::opt_cstr(message_encoding)?;
267 let message = crate::opt_cstr(message)?;
268 unsafe {
269 try_call!(raw::git_commit_amend(
270 &mut raw,
271 self.raw(),
272 update_ref,
273 author.map(|s| s.raw()),
274 committer.map(|s| s.raw()),
275 encoding,
276 message,
277 tree.map(|t| t.raw())
278 ));
279 Ok(Binding::from_raw(&raw as *const _))
280 }
281 }
282
283 /// Get the number of parents of this commit.
284 ///
285 /// Use the `parents` iterator to return an iterator over all parents.
286 pub fn parent_count(&self) -> usize {
287 unsafe { raw::git_commit_parentcount(&*self.raw) as usize }
288 }
289
290 /// Get the specified parent of the commit.
291 ///
292 /// Use the `parents` iterator to return an iterator over all parents.
293 pub fn parent(&self, i: usize) -> Result<Commit<'repo>, Error> {
294 unsafe {
295 let mut raw = ptr::null_mut();
296 try_call!(raw::git_commit_parent(
297 &mut raw,
298 &*self.raw,
299 i as libc::c_uint
300 ));
301 Ok(Binding::from_raw(raw))
302 }
303 }
304
305 /// Get the specified parent id of the commit.
306 ///
307 /// This is different from `parent`, which will attempt to load the
308 /// parent commit from the ODB.
309 ///
310 /// Use the `parent_ids` iterator to return an iterator over all parents.
311 pub fn parent_id(&self, i: usize) -> Result<Oid, Error> {
312 unsafe {
313 let id = raw::git_commit_parent_id(self.raw, i as libc::c_uint);
314 if id.is_null() {
315 Err(Error::from_str("parent index out of bounds"))
316 } else {
317 Ok(Binding::from_raw(id))
318 }
319 }
320 }
321
322 /// Casts this Commit to be usable as an `Object`
323 pub fn as_object(&self) -> &Object<'repo> {
324 unsafe { &*(self as *const _ as *const Object<'repo>) }
325 }
326
327 /// Consumes Commit to be returned as an `Object`
328 pub fn into_object(self) -> Object<'repo> {
329 assert_eq!(mem::size_of_val(&self), mem::size_of::<Object<'_>>());
330 unsafe { mem::transmute(self) }
331 }
332 }
333
334 impl<'repo> Binding for Commit<'repo> {
335 type Raw = *mut raw::git_commit;
336 unsafe fn from_raw(raw: *mut raw::git_commit) -> Commit<'repo> {
337 Commit {
338 raw,
339 _marker: marker::PhantomData,
340 }
341 }
342 fn raw(&self) -> *mut raw::git_commit {
343 self.raw
344 }
345 }
346
347 impl<'repo> std::fmt::Debug for Commit<'repo> {
348 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
349 let mut ds = f.debug_struct("Commit");
350 ds.field("id", &self.id());
351 if let Ok(Some(summary)) = self.summary() {
352 ds.field("summary", &summary);
353 }
354 ds.finish()
355 }
356 }
357
358 /// Aborts iteration when a commit cannot be found
359 impl<'repo, 'commit> Iterator for Parents<'commit, 'repo> {
360 type Item = Commit<'repo>;
361 fn next(&mut self) -> Option<Commit<'repo>> {
362 self.range.next().and_then(|i| self.commit.parent(i).ok())
363 }
364 fn size_hint(&self) -> (usize, Option<usize>) {
365 self.range.size_hint()
366 }
367 }
368
369 /// Aborts iteration when a commit cannot be found
370 impl<'repo, 'commit> DoubleEndedIterator for Parents<'commit, 'repo> {
371 fn next_back(&mut self) -> Option<Commit<'repo>> {
372 self.range
373 .next_back()
374 .and_then(|i| self.commit.parent(i).ok())
375 }
376 }
377
378 impl<'repo, 'commit> FusedIterator for Parents<'commit, 'repo> {}
379
380 impl<'repo, 'commit> ExactSizeIterator for Parents<'commit, 'repo> {}
381
382 /// Aborts iteration when a commit cannot be found
383 impl<'commit> Iterator for ParentIds<'commit> {
384 type Item = Oid;
385 fn next(&mut self) -> Option<Oid> {
386 self.range
387 .next()
388 .and_then(|i| self.commit.parent_id(i).ok())
389 }
390 fn size_hint(&self) -> (usize, Option<usize>) {
391 self.range.size_hint()
392 }
393 }
394
395 /// Aborts iteration when a commit cannot be found
396 impl<'commit> DoubleEndedIterator for ParentIds<'commit> {
397 fn next_back(&mut self) -> Option<Oid> {
398 self.range
399 .next_back()
400 .and_then(|i| self.commit.parent_id(i).ok())
401 }
402 }
403
404 impl<'commit> FusedIterator for ParentIds<'commit> {}
405
406 impl<'commit> ExactSizeIterator for ParentIds<'commit> {}
407
408 impl<'repo> Clone for Commit<'repo> {
409 fn clone(&self) -> Self {
410 self.as_object().clone().into_commit().ok().unwrap()
411 }
412 }
413
414 impl<'repo> Drop for Commit<'repo> {
415 fn drop(&mut self) {
416 unsafe { raw::git_commit_free(self.raw) }
417 }
418 }
419
420 #[cfg(test)]
421 mod tests {
422 #[test]
423 fn smoke() {
424 let (_td, repo) = crate::test::repo_init();
425 let head = repo.head().unwrap();
426 let target = head.target().unwrap();
427 let commit = repo.find_commit(target).unwrap();
428 assert_eq!(commit.message(), Ok("initial\n\nbody"));
429 assert_eq!(commit.body(), Ok(Some("body")));
430 assert_eq!(commit.id(), target);
431 commit.message_raw().unwrap();
432 commit.raw_header().unwrap();
433 commit.message_encoding().expect("Should not be invalid");
434 commit.summary().unwrap();
435 commit.body().unwrap();
436 commit.tree_id();
437 commit.tree().unwrap();
438 assert_eq!(commit.parents().count(), 0);
439
440 let tree_header_bytes = commit.header_field_bytes("tree").unwrap();
441 assert_eq!(
442 crate::Oid::from_str(tree_header_bytes.as_str().unwrap()).unwrap(),
443 commit.tree_id()
444 );
445 let tree_oid = {
446 let str = tree_header_bytes.as_str().unwrap();
447 crate::Oid::from_str_ext(str, repo.object_format()).unwrap()
448 };
449 assert_eq!(tree_oid, commit.tree_id());
450 assert_eq!(commit.author().name(), Ok("name"));
451 assert_eq!(commit.author().email(), Ok("email"));
452 assert_eq!(commit.committer().name(), Ok("name"));
453 assert_eq!(commit.committer().email(), Ok("email"));
454
455 let sig = repo.signature().unwrap();
456 let tree = repo.find_tree(commit.tree_id()).unwrap();
457 let id = repo
458 .commit(Some("HEAD"), &sig, &sig, "bar", &tree, &[&commit])
459 .unwrap();
460 let head = repo.find_commit(id).unwrap();
461
462 let new_head = head
463 .amend(Some("HEAD"), None, None, None, Some("new message"), None)
464 .unwrap();
465 let new_head = repo.find_commit(new_head).unwrap();
466 assert_eq!(new_head.message(), Ok("new message"));
467 new_head.into_object();
468
469 repo.find_object(target, None).unwrap().as_commit().unwrap();
470 repo.find_object(target, None)
471 .unwrap()
472 .into_commit()
473 .ok()
474 .unwrap();
475 }
476
477 #[test]
478 #[cfg(feature = "unstable-sha256")]
479 fn smoke_sha256() {
480 let (_td, repo) = crate::test::repo_init_sha256();
481 let head = repo.head().unwrap();
482 let target = head.target().unwrap();
483 let commit = repo.find_commit(target).unwrap();
484
485 // Verify SHA256 OID (32 bytes)
486 assert_eq!(commit.id().as_bytes().len(), 32);
487 assert_eq!(commit.tree_id().as_bytes().len(), 32);
488
489 assert_eq!(commit.message(), Ok("initial\n\nbody"));
490 assert_eq!(commit.body(), Ok(Some("body")));
491 assert_eq!(commit.id(), target);
492 commit.summary().unwrap();
493 commit.tree().unwrap();
494 assert_eq!(commit.parents().count(), 0);
495
496 let tree_header_bytes = commit.header_field_bytes("tree").unwrap();
497 let tree_oid = {
498 let str = tree_header_bytes.as_str().unwrap();
499 let oid = crate::Oid::from_str_ext(str, repo.object_format()).unwrap();
500 oid
501 };
502 assert_eq!(tree_oid, commit.tree_id());
503
504 // Create child commit with parent
505 let sig = repo.signature().unwrap();
506 let tree = repo.find_tree(commit.tree_id()).unwrap();
507 let id = repo
508 .commit(Some("HEAD"), &sig, &sig, "bar", &tree, &[&commit])
509 .unwrap();
510 let head = repo.find_commit(id).unwrap();
511
512 // Verify child commit ID is also SHA256
513 assert_eq!(head.id().as_bytes().len(), 32);
514 assert_eq!(head.parent_count(), 1);
515 assert_eq!(head.parent_id(0).unwrap(), commit.id());
516 }
517 }