Debian Codegraph @

src/tree.rs

raw
1 use libc::{c_char, c_int, c_void};
2 use std::cmp::Ordering;
3 use std::ffi::{CStr, CString};
4 use std::iter::FusedIterator;
5 use std::marker;
6 use std::mem;
7 use std::ops::Range;
8 use std::path::Path;
9 use std::ptr;
10 use std::str;
11
12 use crate::util::{c_cmp_to_ordering, path_to_repo_path, Binding};
13 use crate::{panic, raw, Error, Object, ObjectType, Oid, Repository};
14
15 /// A structure to represent a git [tree][1]
16 ///
17 /// [1]: http://git-scm.com/book/en/Git-Internals-Git-Objects
18 pub struct Tree<'repo> {
19 raw: *mut raw::git_tree,
20 _marker: marker::PhantomData<Object<'repo>>,
21 }
22
23 /// A structure representing an entry inside of a tree. An entry is borrowed
24 /// from a tree.
25 pub struct TreeEntry<'tree> {
26 raw: *mut raw::git_tree_entry,
27 owned: bool,
28 _marker: marker::PhantomData<&'tree raw::git_tree_entry>,
29 }
30
31 /// An iterator over the entries in a tree.
32 pub struct TreeIter<'tree> {
33 range: Range<usize>,
34 tree: &'tree Tree<'tree>,
35 }
36
37 /// A binary indicator of whether a tree walk should be performed in pre-order
38 /// or post-order.
39 #[derive(Clone, Copy)]
40 pub enum TreeWalkMode {
41 /// Runs the traversal in pre-order.
42 PreOrder = 0,
43 /// Runs the traversal in post-order.
44 PostOrder = 1,
45 }
46
47 /// Possible return codes for tree walking callback functions.
48 #[repr(i32)]
49 pub enum TreeWalkResult {
50 /// Continue with the traversal as normal.
51 Ok = 0,
52 /// Skip the current node (in pre-order mode).
53 Skip = 1,
54 /// Completely stop the traversal.
55 Abort = raw::GIT_EUSER,
56 }
57
58 impl Into<i32> for TreeWalkResult {
59 fn into(self) -> i32 {
60 self as i32
61 }
62 }
63
64 impl Into<raw::git_treewalk_mode> for TreeWalkMode {
65 #[cfg(target_env = "msvc")]
66 fn into(self) -> raw::git_treewalk_mode {
67 self as i32
68 }
69 #[cfg(not(target_env = "msvc"))]
70 fn into(self) -> raw::git_treewalk_mode {
71 self as u32
72 }
73 }
74
75 impl<'repo> Tree<'repo> {
76 /// Get the id (SHA1) of a repository object
77 pub fn id(&self) -> Oid {
78 unsafe { Binding::from_raw(raw::git_tree_id(&*self.raw)) }
79 }
80
81 /// Get the number of entries listed in this tree.
82 pub fn len(&self) -> usize {
83 unsafe { raw::git_tree_entrycount(&*self.raw) as usize }
84 }
85
86 /// Return `true` if there is not entry
87 pub fn is_empty(&self) -> bool {
88 self.len() == 0
89 }
90
91 /// Returns an iterator over the entries in this tree.
92 pub fn iter(&self) -> TreeIter<'_> {
93 TreeIter {
94 range: 0..self.len(),
95 tree: self,
96 }
97 }
98
99 /// Traverse the entries in a tree and its subtrees in post or pre-order.
100 /// The callback function will be run on each node of the tree that's
101 /// walked. The return code of this function will determine how the walk
102 /// continues.
103 ///
104 /// libgit2 requires that the callback be an integer, where 0 indicates a
105 /// successful visit, 1 skips the node, and -1 aborts the traversal completely.
106 /// You may opt to use the enum [`TreeWalkResult`] instead.
107 ///
108 /// ```ignore
109 /// let mut ct = 0;
110 /// tree.walk(TreeWalkMode::PreOrder, |_, entry| {
111 /// assert_eq!(entry.name(), Some("foo"));
112 /// ct += 1;
113 /// TreeWalkResult::Ok
114 /// }).unwrap();
115 /// assert_eq!(ct, 1);
116 /// ```
117 ///
118 /// See [libgit2 documentation][1] for more information.
119 ///
120 /// [1]: https://libgit2.org/libgit2/#HEAD/group/tree/git_tree_walk
121 pub fn walk<C, T>(&self, mode: TreeWalkMode, mut callback: C) -> Result<(), Error>
122 where
123 C: FnMut(&str, &TreeEntry<'_>) -> T,
124 T: Into<i32>,
125 {
126 unsafe {
127 let mut data = TreeWalkCbData {
128 callback: &mut callback,
129 };
130 try_call!(raw::git_tree_walk(
131 self.raw(),
132 mode as raw::git_treewalk_mode,
133 treewalk_cb::<T>,
134 &mut data as *mut _ as *mut c_void
135 ));
136 Ok(())
137 }
138 }
139
140 /// Lookup a tree entry by SHA value.
141 pub fn get_id(&self, id: Oid) -> Option<TreeEntry<'_>> {
142 unsafe {
143 let ptr = raw::git_tree_entry_byid(&*self.raw(), &*id.raw());
144 if ptr.is_null() {
145 None
146 } else {
147 Some(entry_from_raw_const(ptr))
148 }
149 }
150 }
151
152 /// Lookup a tree entry by its position in the tree
153 pub fn get(&self, n: usize) -> Option<TreeEntry<'_>> {
154 unsafe {
155 let ptr = raw::git_tree_entry_byindex(&*self.raw(), n as libc::size_t);
156 if ptr.is_null() {
157 None
158 } else {
159 Some(entry_from_raw_const(ptr))
160 }
161 }
162 }
163
164 /// Lookup a tree entry by its filename
165 pub fn get_name(&self, filename: &str) -> Option<TreeEntry<'_>> {
166 self.get_name_bytes(filename.as_bytes())
167 }
168
169 /// Lookup a tree entry by its filename, specified as bytes.
170 ///
171 /// This allows for non-UTF-8 filenames.
172 pub fn get_name_bytes(&self, filename: &[u8]) -> Option<TreeEntry<'_>> {
173 let filename = CString::new(filename).unwrap();
174 unsafe {
175 let ptr = call!(raw::git_tree_entry_byname(&*self.raw(), filename));
176 if ptr.is_null() {
177 None
178 } else {
179 Some(entry_from_raw_const(ptr))
180 }
181 }
182 }
183
184 /// Retrieve a tree entry contained in a tree or in any of its subtrees,
185 /// given its relative path.
186 pub fn get_path(&self, path: &Path) -> Result<TreeEntry<'static>, Error> {
187 let path = path_to_repo_path(path)?;
188 let mut ret = ptr::null_mut();
189 unsafe {
190 try_call!(raw::git_tree_entry_bypath(&mut ret, &*self.raw(), path));
191 Ok(Binding::from_raw(ret))
192 }
193 }
194
195 /// Casts this Tree to be usable as an `Object`
196 pub fn as_object(&self) -> &Object<'repo> {
197 unsafe { &*(self as *const _ as *const Object<'repo>) }
198 }
199
200 /// Consumes this Tree to be returned as an `Object`
201 pub fn into_object(self) -> Object<'repo> {
202 assert_eq!(mem::size_of_val(&self), mem::size_of::<Object<'_>>());
203 unsafe { mem::transmute(self) }
204 }
205 }
206
207 type TreeWalkCb<'a, T> = dyn FnMut(&str, &TreeEntry<'_>) -> T + 'a;
208
209 struct TreeWalkCbData<'a, T> {
210 callback: &'a mut TreeWalkCb<'a, T>,
211 }
212
213 extern "C" fn treewalk_cb<T: Into<i32>>(
214 root: *const c_char,
215 entry: *const raw::git_tree_entry,
216 payload: *mut c_void,
217 ) -> c_int {
218 match panic::wrap(|| unsafe {
219 let root = match CStr::from_ptr(root).to_str() {
220 Ok(value) => value,
221 _ => return -1,
222 };
223 let entry = entry_from_raw_const(entry);
224 let payload = &mut *(payload as *mut TreeWalkCbData<'_, T>);
225 let callback = &mut payload.callback;
226 callback(root, &entry).into()
227 }) {
228 Some(value) => value,
229 None => -1,
230 }
231 }
232
233 impl<'repo> Binding for Tree<'repo> {
234 type Raw = *mut raw::git_tree;
235
236 unsafe fn from_raw(raw: *mut raw::git_tree) -> Tree<'repo> {
237 Tree {
238 raw,
239 _marker: marker::PhantomData,
240 }
241 }
242 fn raw(&self) -> *mut raw::git_tree {
243 self.raw
244 }
245 }
246
247 impl<'repo> std::fmt::Debug for Tree<'repo> {
248 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
249 f.debug_struct("Tree").field("id", &self.id()).finish()
250 }
251 }
252
253 impl<'repo> Clone for Tree<'repo> {
254 fn clone(&self) -> Self {
255 self.as_object().clone().into_tree().ok().unwrap()
256 }
257 }
258
259 impl<'repo> Drop for Tree<'repo> {
260 fn drop(&mut self) {
261 unsafe { raw::git_tree_free(self.raw) }
262 }
263 }
264
265 impl<'repo, 'iter> IntoIterator for &'iter Tree<'repo> {
266 type Item = TreeEntry<'iter>;
267 type IntoIter = TreeIter<'iter>;
268 fn into_iter(self) -> Self::IntoIter {
269 self.iter()
270 }
271 }
272
273 /// Create a new tree entry from the raw pointer provided.
274 ///
275 /// The lifetime of the entry is tied to the tree provided and the function
276 /// is unsafe because the validity of the pointer cannot be guaranteed.
277 pub unsafe fn entry_from_raw_const<'tree>(raw: *const raw::git_tree_entry) -> TreeEntry<'tree> {
278 TreeEntry {
279 raw: raw as *mut raw::git_tree_entry,
280 owned: false,
281 _marker: marker::PhantomData,
282 }
283 }
284
285 impl<'tree> TreeEntry<'tree> {
286 /// Get the id of the object pointed by the entry
287 pub fn id(&self) -> Oid {
288 unsafe { Binding::from_raw(raw::git_tree_entry_id(&*self.raw)) }
289 }
290
291 /// Get the filename of a tree entry
292 pub fn name(&self) -> Result<&str, Error> {
293 str::from_utf8(self.name_bytes()).map_err(|e| e.into())
294 }
295
296 /// Get the filename of a tree entry
297 pub fn name_bytes(&self) -> &[u8] {
298 unsafe { crate::opt_bytes(self, raw::git_tree_entry_name(&*self.raw())).unwrap() }
299 }
300
301 /// Convert a tree entry to the object it points to.
302 pub fn to_object<'a>(&self, repo: &'a Repository) -> Result<Object<'a>, Error> {
303 let mut ret = ptr::null_mut();
304 unsafe {
305 try_call!(raw::git_tree_entry_to_object(
306 &mut ret,
307 repo.raw(),
308 &*self.raw()
309 ));
310 Ok(Binding::from_raw(ret))
311 }
312 }
313
314 /// Get the type of the object pointed by the entry
315 pub fn kind(&self) -> Option<ObjectType> {
316 ObjectType::from_raw(unsafe { raw::git_tree_entry_type(&*self.raw) })
317 }
318
319 /// Get the UNIX file attributes of a tree entry
320 pub fn filemode(&self) -> i32 {
321 unsafe { raw::git_tree_entry_filemode(&*self.raw) as i32 }
322 }
323
324 /// Get the raw UNIX file attributes of a tree entry
325 pub fn filemode_raw(&self) -> i32 {
326 unsafe { raw::git_tree_entry_filemode_raw(&*self.raw) as i32 }
327 }
328
329 /// Convert this entry of any lifetime into an owned signature with a static
330 /// lifetime.
331 ///
332 /// This will use the `Clone::clone` implementation under the hood.
333 pub fn to_owned(&self) -> TreeEntry<'static> {
334 unsafe {
335 let me = mem::transmute::<&TreeEntry<'tree>, &TreeEntry<'static>>(self);
336 me.clone()
337 }
338 }
339 }
340
341 impl<'a> Binding for TreeEntry<'a> {
342 type Raw = *mut raw::git_tree_entry;
343 unsafe fn from_raw(raw: *mut raw::git_tree_entry) -> TreeEntry<'a> {
344 TreeEntry {
345 raw,
346 owned: true,
347 _marker: marker::PhantomData,
348 }
349 }
350 fn raw(&self) -> *mut raw::git_tree_entry {
351 self.raw
352 }
353 }
354
355 impl<'a> Clone for TreeEntry<'a> {
356 fn clone(&self) -> TreeEntry<'a> {
357 let mut ret = ptr::null_mut();
358 unsafe {
359 assert_eq!(raw::git_tree_entry_dup(&mut ret, &*self.raw()), 0);
360 Binding::from_raw(ret)
361 }
362 }
363 }
364
365 impl<'a> PartialOrd for TreeEntry<'a> {
366 fn partial_cmp(&self, other: &TreeEntry<'a>) -> Option<Ordering> {
367 Some(self.cmp(other))
368 }
369 }
370 impl<'a> Ord for TreeEntry<'a> {
371 fn cmp(&self, other: &TreeEntry<'a>) -> Ordering {
372 c_cmp_to_ordering(unsafe { raw::git_tree_entry_cmp(&*self.raw(), &*other.raw()) })
373 }
374 }
375
376 impl<'a> PartialEq for TreeEntry<'a> {
377 fn eq(&self, other: &TreeEntry<'a>) -> bool {
378 self.cmp(other) == Ordering::Equal
379 }
380 }
381 impl<'a> Eq for TreeEntry<'a> {}
382
383 impl<'a> Drop for TreeEntry<'a> {
384 fn drop(&mut self) {
385 if self.owned {
386 unsafe { raw::git_tree_entry_free(self.raw) }
387 }
388 }
389 }
390
391 impl<'tree> Iterator for TreeIter<'tree> {
392 type Item = TreeEntry<'tree>;
393 fn next(&mut self) -> Option<TreeEntry<'tree>> {
394 self.range.next().and_then(|i| self.tree.get(i))
395 }
396 fn size_hint(&self) -> (usize, Option<usize>) {
397 self.range.size_hint()
398 }
399 fn nth(&mut self, n: usize) -> Option<TreeEntry<'tree>> {
400 self.range.nth(n).and_then(|i| self.tree.get(i))
401 }
402 }
403 impl<'tree> DoubleEndedIterator for TreeIter<'tree> {
404 fn next_back(&mut self) -> Option<TreeEntry<'tree>> {
405 self.range.next_back().and_then(|i| self.tree.get(i))
406 }
407 }
408 impl<'tree> FusedIterator for TreeIter<'tree> {}
409 impl<'tree> ExactSizeIterator for TreeIter<'tree> {}
410
411 #[cfg(test)]
412 mod tests {
413 use super::{TreeWalkMode, TreeWalkResult};
414 use crate::{Object, ObjectType, Repository, Tree, TreeEntry};
415 use std::fs::File;
416 use std::io::prelude::*;
417 use std::path::Path;
418 use tempfile::TempDir;
419
420 pub struct TestTreeIter<'a> {
421 entries: Vec<TreeEntry<'a>>,
422 repo: &'a Repository,
423 }
424
425 impl<'a> Iterator for TestTreeIter<'a> {
426 type Item = TreeEntry<'a>;
427
428 fn next(&mut self) -> Option<TreeEntry<'a>> {
429 if self.entries.is_empty() {
430 None
431 } else {
432 let entry = self.entries.remove(0);
433
434 match entry.kind() {
435 Some(ObjectType::Tree) => {
436 let obj: Object<'a> = entry.to_object(self.repo).unwrap();
437
438 let tree: &Tree<'a> = obj.as_tree().unwrap();
439
440 for entry in tree.iter() {
441 self.entries.push(entry.to_owned());
442 }
443 }
444 _ => {}
445 }
446
447 Some(entry)
448 }
449 }
450 }
451
452 fn tree_iter<'repo>(tree: &Tree<'repo>, repo: &'repo Repository) -> TestTreeIter<'repo> {
453 let mut initial = vec![];
454
455 for entry in tree.iter() {
456 initial.push(entry.to_owned());
457 }
458
459 TestTreeIter {
460 entries: initial,
461 repo: repo,
462 }
463 }
464
465 #[test]
466 fn smoke_tree_iter() {
467 let (td, repo) = crate::test::repo_init();
468
469 setup_repo(&td, &repo);
470
471 let head = repo.head().unwrap();
472 let target = head.target().unwrap();
473 let commit = repo.find_commit(target).unwrap();
474
475 let tree = repo.find_tree(commit.tree_id()).unwrap();
476 assert_eq!(tree.id(), commit.tree_id());
477 assert_eq!(tree.len(), 8);
478
479 for entry in tree_iter(&tree, &repo) {
480 println!("iter entry {:?}", entry.name());
481 }
482 }
483
484 #[test]
485 fn smoke_tree_nth() {
486 let (td, repo) = crate::test::repo_init();
487
488 setup_repo(&td, &repo);
489
490 let head = repo.head().unwrap();
491 let target = head.target().unwrap();
492 let commit = repo.find_commit(target).unwrap();
493
494 let tree = repo.find_tree(commit.tree_id()).unwrap();
495 assert_eq!(tree.id(), commit.tree_id());
496 assert_eq!(tree.len(), 8);
497 let mut it = tree.iter();
498 let e = it.nth(4).unwrap();
499 assert_eq!(e.name(), Ok("f4"));
500 }
501
502 fn setup_repo(td: &TempDir, repo: &Repository) {
503 let mut index = repo.index().unwrap();
504 for n in 0..8 {
505 let name = format!("f{n}");
506 File::create(&td.path().join(&name))
507 .unwrap()
508 .write_all(name.as_bytes())
509 .unwrap();
510 index.add_path(Path::new(&name)).unwrap();
511 }
512 let id = index.write_tree().unwrap();
513 let sig = repo.signature().unwrap();
514 let tree = repo.find_tree(id).unwrap();
515 let parent = repo
516 .find_commit(repo.head().unwrap().target().unwrap())
517 .unwrap();
518 repo.commit(
519 Some("HEAD"),
520 &sig,
521 &sig,
522 "another commit",
523 &tree,
524 &[&parent],
525 )
526 .unwrap();
527 }
528
529 #[test]
530 fn smoke() {
531 let (td, repo) = crate::test::repo_init();
532
533 setup_repo(&td, &repo);
534
535 let head = repo.head().unwrap();
536 let target = head.target().unwrap();
537 let commit = repo.find_commit(target).unwrap();
538
539 let tree = repo.find_tree(commit.tree_id()).unwrap();
540 assert_eq!(tree.id(), commit.tree_id());
541 assert_eq!(tree.len(), 8);
542 {
543 let e0 = tree.get(0).unwrap();
544 assert!(e0 == tree.get_id(e0.id()).unwrap());
545 assert!(e0 == tree.get_name("f0").unwrap());
546 assert!(e0 == tree.get_name_bytes(b"f0").unwrap());
547 assert!(e0 == tree.get_path(Path::new("f0")).unwrap());
548 assert_eq!(e0.name(), Ok("f0"));
549 e0.to_object(&repo).unwrap();
550
551 let e1 = tree.get(1).unwrap();
552 assert!(e1 == tree.get_id(e1.id()).unwrap());
553 assert!(e1 == tree.get_name("f1").unwrap());
554 assert!(e1 == tree.get_name_bytes(b"f1").unwrap());
555 assert!(e1 == tree.get_path(Path::new("f1")).unwrap());
556 assert_eq!(e1.name(), Ok("f1"));
557 e1.to_object(&repo).unwrap();
558 }
559 tree.into_object();
560
561 repo.find_object(commit.tree_id(), None)
562 .unwrap()
563 .as_tree()
564 .unwrap();
565 repo.find_object(commit.tree_id(), None)
566 .unwrap()
567 .into_tree()
568 .ok()
569 .unwrap();
570 }
571
572 #[test]
573 fn tree_walk() {
574 let (td, repo) = crate::test::repo_init();
575
576 setup_repo(&td, &repo);
577
578 let head = repo.head().unwrap();
579 let target = head.target().unwrap();
580 let commit = repo.find_commit(target).unwrap();
581 let tree = repo.find_tree(commit.tree_id()).unwrap();
582
583 let mut ct = 0;
584 tree.walk(TreeWalkMode::PreOrder, |_, entry| {
585 assert_eq!(entry.name(), Ok(format!("f{ct}").as_str()));
586 ct += 1;
587 0
588 })
589 .unwrap();
590 assert_eq!(ct, 8);
591
592 let mut ct = 0;
593 tree.walk(TreeWalkMode::PreOrder, |_, entry| {
594 assert_eq!(entry.name(), Ok(format!("f{ct}").as_str()));
595 ct += 1;
596 TreeWalkResult::Ok
597 })
598 .unwrap();
599 assert_eq!(ct, 8);
600 }
601
602 #[test]
603 fn tree_walk_error() {
604 let (td, repo) = crate::test::repo_init();
605
606 setup_repo(&td, &repo);
607
608 let head = repo.head().unwrap();
609 let target = head.target().unwrap();
610 let commit = repo.find_commit(target).unwrap();
611 let tree = repo.find_tree(commit.tree_id()).unwrap();
612 let e = tree.walk(TreeWalkMode::PreOrder, |_, _| -1).unwrap_err();
613 assert_eq!(e.class(), crate::ErrorClass::Callback);
614 }
615 }