Debian Codegraph @

src/odb.rs

raw
1 use std::io;
2 use std::marker;
3 use std::ptr;
4 use std::slice;
5
6 use std::ffi::CString;
7
8 use libc::{c_char, c_int, c_uint, c_void, size_t};
9
10 use crate::panic;
11 use crate::util::Binding;
12 use crate::ObjectFormat;
13 use crate::{
14 raw, Error, IndexerProgress, Mempack, Object, ObjectType, OdbLookupFlags, Oid, Progress,
15 };
16
17 /// A structure to represent a git object database
18 pub struct Odb<'repo> {
19 raw: *mut raw::git_odb,
20 _marker: marker::PhantomData<Object<'repo>>,
21 }
22
23 // `git_odb` uses locking and atomics internally.
24 unsafe impl<'repo> Send for Odb<'repo> {}
25 unsafe impl<'repo> Sync for Odb<'repo> {}
26
27 impl<'repo> Binding for Odb<'repo> {
28 type Raw = *mut raw::git_odb;
29
30 unsafe fn from_raw(raw: *mut raw::git_odb) -> Odb<'repo> {
31 Odb {
32 raw,
33 _marker: marker::PhantomData,
34 }
35 }
36 fn raw(&self) -> *mut raw::git_odb {
37 self.raw
38 }
39 }
40
41 impl<'repo> Drop for Odb<'repo> {
42 fn drop(&mut self) {
43 unsafe { raw::git_odb_free(self.raw) }
44 }
45 }
46
47 impl<'repo> Odb<'repo> {
48 /// Creates an object database without any backends.
49 ///
50 /// This always creates a SHA1 object database.
51 /// Use [`Odb::new_ext`] to create one with a specific object format.
52 pub fn new<'a>() -> Result<Odb<'a>, Error> {
53 Self::new_ext(ObjectFormat::Sha1)
54 }
55
56 /// Creates an object database without any backends,
57 /// with a specific object format.
58 ///
59 /// See [`Odb::new`] for more details.
60 pub fn new_ext<'a>(format: ObjectFormat) -> Result<Odb<'a>, Error> {
61 crate::init();
62 unsafe {
63 let mut out = ptr::null_mut();
64 #[cfg(not(feature = "unstable-sha256"))]
65 {
66 let _ = format;
67 try_call!(raw::git_odb_new(&mut out));
68 }
69 #[cfg(feature = "unstable-sha256")]
70 {
71 let mut opts: raw::git_odb_options = std::mem::zeroed();
72 opts.version = raw::GIT_ODB_OPTIONS_VERSION;
73 opts.oid_type = format.raw();
74 try_call!(raw::git_odb_new(&mut out, &opts));
75 }
76 Ok(Odb::from_raw(out))
77 }
78 }
79
80 /// Create object database reading stream.
81 ///
82 /// Note that most backends do not support streaming reads because they store their objects as compressed/delta'ed blobs.
83 /// If the backend does not support streaming reads, use the `read` method instead.
84 pub fn reader(&self, oid: Oid) -> Result<(OdbReader<'_>, usize, ObjectType), Error> {
85 let mut out = ptr::null_mut();
86 let mut size = 0usize;
87 let mut otype: raw::git_object_t = ObjectType::Any.raw();
88 unsafe {
89 try_call!(raw::git_odb_open_rstream(
90 &mut out,
91 &mut size,
92 &mut otype,
93 self.raw,
94 oid.raw()
95 ));
96 Ok((
97 OdbReader::from_raw(out),
98 size,
99 ObjectType::from_raw(otype).unwrap(),
100 ))
101 }
102 }
103
104 /// Create object database writing stream.
105 ///
106 /// The type and final length of the object must be specified when opening the stream.
107 /// If the backend does not support streaming writes, use the `write` method instead.
108 pub fn writer(&self, size: usize, obj_type: ObjectType) -> Result<OdbWriter<'_>, Error> {
109 let mut out = ptr::null_mut();
110 unsafe {
111 try_call!(raw::git_odb_open_wstream(
112 &mut out,
113 self.raw,
114 size as raw::git_object_size_t,
115 obj_type.raw()
116 ));
117 Ok(OdbWriter::from_raw(out))
118 }
119 }
120
121 /// Iterate over all objects in the object database.s
122 pub fn foreach<C>(&self, mut callback: C) -> Result<(), Error>
123 where
124 C: FnMut(&Oid) -> bool,
125 {
126 unsafe {
127 let mut data = ForeachCbData {
128 callback: &mut callback,
129 };
130 let cb: raw::git_odb_foreach_cb = Some(foreach_cb);
131 try_call!(raw::git_odb_foreach(
132 self.raw(),
133 cb,
134 &mut data as *mut _ as *mut _
135 ));
136 Ok(())
137 }
138 }
139
140 /// Read an object from the database.
141 pub fn read(&self, oid: Oid) -> Result<OdbObject<'_>, Error> {
142 let mut out = ptr::null_mut();
143 unsafe {
144 try_call!(raw::git_odb_read(&mut out, self.raw, oid.raw()));
145 Ok(OdbObject::from_raw(out))
146 }
147 }
148
149 /// Reads the header of an object from the database
150 /// without reading the full content.
151 pub fn read_header(&self, oid: Oid) -> Result<(usize, ObjectType), Error> {
152 let mut size: usize = 0;
153 let mut kind_id: i32 = ObjectType::Any.raw();
154
155 unsafe {
156 try_call!(raw::git_odb_read_header(
157 &mut size as *mut size_t,
158 &mut kind_id as *mut raw::git_object_t,
159 self.raw,
160 oid.raw()
161 ));
162
163 Ok((size, ObjectType::from_raw(kind_id).unwrap()))
164 }
165 }
166
167 /// Write an object to the database.
168 pub fn write(&self, kind: ObjectType, data: &[u8]) -> Result<Oid, Error> {
169 unsafe {
170 let mut out = crate::util::zeroed_raw_oid();
171 try_call!(raw::git_odb_write(
172 &mut out,
173 self.raw,
174 data.as_ptr() as *const c_void,
175 data.len(),
176 kind.raw()
177 ));
178 Ok(Oid::from_raw(&mut out))
179 }
180 }
181
182 /// Create stream for writing a pack file to the ODB
183 pub fn packwriter(&self) -> Result<OdbPackwriter<'_>, Error> {
184 let mut out = ptr::null_mut();
185 let progress_cb: raw::git_indexer_progress_cb = Some(write_pack_progress_cb);
186 let progress_payload = Box::new(OdbPackwriterCb { cb: None });
187 let progress_payload_ptr = Box::into_raw(progress_payload);
188
189 unsafe {
190 try_call!(raw::git_odb_write_pack(
191 &mut out,
192 self.raw,
193 progress_cb,
194 progress_payload_ptr as *mut c_void
195 ));
196 }
197
198 Ok(OdbPackwriter {
199 raw: out,
200 progress: Default::default(),
201 progress_payload_ptr,
202 })
203 }
204
205 /// Checks if the object database has an object.
206 pub fn exists(&self, oid: Oid) -> bool {
207 unsafe { raw::git_odb_exists(self.raw, oid.raw()) != 0 }
208 }
209
210 /// Checks if the object database has an object, with extended flags.
211 pub fn exists_ext(&self, oid: Oid, flags: OdbLookupFlags) -> bool {
212 unsafe { raw::git_odb_exists_ext(self.raw, oid.raw(), flags.bits() as c_uint) != 0 }
213 }
214
215 /// Potentially finds an object that starts with the given prefix.
216 pub fn exists_prefix(&self, short_oid: Oid, len: usize) -> Result<Oid, Error> {
217 unsafe {
218 let mut out = crate::util::zeroed_raw_oid();
219 try_call!(raw::git_odb_exists_prefix(
220 &mut out,
221 self.raw,
222 short_oid.raw(),
223 len
224 ));
225 Ok(Oid::from_raw(&out))
226 }
227 }
228
229 /// Refresh the object database.
230 /// This should never be needed, and is
231 /// provided purely for convenience.
232 /// The object database will automatically
233 /// refresh when an object is not found when
234 /// requested.
235 pub fn refresh(&self) -> Result<(), Error> {
236 unsafe {
237 try_call!(raw::git_odb_refresh(self.raw));
238 Ok(())
239 }
240 }
241
242 /// Adds an alternate disk backend to the object database.
243 pub fn add_disk_alternate(&self, path: &str) -> Result<(), Error> {
244 unsafe {
245 let path = CString::new(path)?;
246 try_call!(raw::git_odb_add_disk_alternate(self.raw, path));
247 Ok(())
248 }
249 }
250
251 /// Create a new mempack backend, and add it to this odb with the given
252 /// priority. Higher values give the backend higher precedence. The default
253 /// loose and pack backends have priorities 1 and 2 respectively (hard-coded
254 /// in libgit2). A reference to the new mempack backend is returned on
255 /// success. The lifetime of the backend must be contained within the
256 /// lifetime of this odb, since deletion of the odb will also result in
257 /// deletion of the mempack backend.
258 ///
259 /// Here is an example that fails to compile because it tries to hold the
260 /// mempack reference beyond the Odb's lifetime:
261 ///
262 /// ```compile_fail
263 /// use git2::Odb;
264 /// let mempack = {
265 /// #[cfg(not(feature = "unstable-sha256"))]
266 /// let odb = Odb::new().unwrap();
267 /// #[cfg(feature = "unstable-sha256")]
268 /// let odb = Odb::new_ext(git2::ObjectFormat::Sha1).unwrap();
269 /// odb.add_new_mempack_backend(1000).unwrap()
270 /// };
271 /// ```
272 pub fn add_new_mempack_backend<'odb>(
273 &'odb self,
274 priority: i32,
275 ) -> Result<Mempack<'odb>, Error> {
276 unsafe {
277 let mut mempack = ptr::null_mut();
278 // The mempack backend object in libgit2 is only ever freed by an
279 // odb that has the backend in its list. So to avoid potentially
280 // leaking the mempack backend, this API ensures that the backend
281 // is added to the odb before returning it. The lifetime of the
282 // mempack is also bound to the lifetime of the odb, so that users
283 // can't end up with a dangling reference to a mempack object that
284 // was actually freed when the odb was destroyed.
285 try_call!(raw::git_mempack_new(&mut mempack));
286 try_call!(raw::git_odb_add_backend(
287 self.raw,
288 mempack,
289 priority as c_int
290 ));
291 Ok(Mempack::from_raw(mempack))
292 }
293 }
294 }
295
296 /// An object from the Object Database.
297 pub struct OdbObject<'a> {
298 raw: *mut raw::git_odb_object,
299 _marker: marker::PhantomData<Object<'a>>,
300 }
301
302 impl<'a> Binding for OdbObject<'a> {
303 type Raw = *mut raw::git_odb_object;
304
305 unsafe fn from_raw(raw: *mut raw::git_odb_object) -> OdbObject<'a> {
306 OdbObject {
307 raw,
308 _marker: marker::PhantomData,
309 }
310 }
311
312 fn raw(&self) -> *mut raw::git_odb_object {
313 self.raw
314 }
315 }
316
317 impl<'a> Drop for OdbObject<'a> {
318 fn drop(&mut self) {
319 unsafe { raw::git_odb_object_free(self.raw) }
320 }
321 }
322
323 impl<'a> OdbObject<'a> {
324 /// Get the object type.
325 pub fn kind(&self) -> ObjectType {
326 unsafe { ObjectType::from_raw(raw::git_odb_object_type(self.raw)).unwrap() }
327 }
328
329 /// Get the object size.
330 pub fn len(&self) -> usize {
331 unsafe { raw::git_odb_object_size(self.raw) }
332 }
333
334 /// Get the object data.
335 pub fn data(&self) -> &[u8] {
336 unsafe {
337 let size = self.len();
338 let ptr: *const u8 = raw::git_odb_object_data(self.raw) as *const u8;
339 let buffer = slice::from_raw_parts(ptr, size);
340 return buffer;
341 }
342 }
343
344 /// Get the object id.
345 pub fn id(&self) -> Oid {
346 unsafe { Oid::from_raw(raw::git_odb_object_id(self.raw)) }
347 }
348 }
349
350 /// A structure to represent a git ODB rstream
351 pub struct OdbReader<'repo> {
352 raw: *mut raw::git_odb_stream,
353 _marker: marker::PhantomData<Object<'repo>>,
354 }
355
356 // `git_odb_stream` is not thread-safe internally, so it can't use `Sync`, but moving it to another
357 // thread and continuing to read will work.
358 unsafe impl<'repo> Send for OdbReader<'repo> {}
359
360 impl<'repo> Binding for OdbReader<'repo> {
361 type Raw = *mut raw::git_odb_stream;
362
363 unsafe fn from_raw(raw: *mut raw::git_odb_stream) -> OdbReader<'repo> {
364 OdbReader {
365 raw,
366 _marker: marker::PhantomData,
367 }
368 }
369 fn raw(&self) -> *mut raw::git_odb_stream {
370 self.raw
371 }
372 }
373
374 impl<'repo> Drop for OdbReader<'repo> {
375 fn drop(&mut self) {
376 unsafe { raw::git_odb_stream_free(self.raw) }
377 }
378 }
379
380 impl<'repo> io::Read for OdbReader<'repo> {
381 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
382 unsafe {
383 let ptr = buf.as_ptr() as *mut c_char;
384 let len = buf.len();
385 let res = raw::git_odb_stream_read(self.raw, ptr, len);
386 if res < 0 {
387 Err(io::Error::new(io::ErrorKind::Other, "Read error"))
388 } else {
389 Ok(res as _)
390 }
391 }
392 }
393 }
394
395 /// A structure to represent a git ODB wstream
396 pub struct OdbWriter<'repo> {
397 raw: *mut raw::git_odb_stream,
398 _marker: marker::PhantomData<Object<'repo>>,
399 }
400
401 // `git_odb_stream` is not thread-safe internally, so it can't use `Sync`, but moving it to another
402 // thread and continuing to write will work.
403 unsafe impl<'repo> Send for OdbWriter<'repo> {}
404
405 impl<'repo> OdbWriter<'repo> {
406 /// Finish writing to an ODB stream
407 ///
408 /// This method can be used to finalize writing object to the database and get an identifier.
409 /// The object will take its final name and will be available to the odb.
410 /// This method will fail if the total number of received bytes differs from the size declared with odb_writer()
411 /// Attempting write after finishing will be ignored.
412 pub fn finalize(&mut self) -> Result<Oid, Error> {
413 let mut raw = crate::util::zeroed_raw_oid();
414 unsafe {
415 try_call!(raw::git_odb_stream_finalize_write(&mut raw, self.raw));
416 Ok(Binding::from_raw(&raw as *const _))
417 }
418 }
419 }
420
421 impl<'repo> Binding for OdbWriter<'repo> {
422 type Raw = *mut raw::git_odb_stream;
423
424 unsafe fn from_raw(raw: *mut raw::git_odb_stream) -> OdbWriter<'repo> {
425 OdbWriter {
426 raw,
427 _marker: marker::PhantomData,
428 }
429 }
430 fn raw(&self) -> *mut raw::git_odb_stream {
431 self.raw
432 }
433 }
434
435 impl<'repo> Drop for OdbWriter<'repo> {
436 fn drop(&mut self) {
437 unsafe { raw::git_odb_stream_free(self.raw) }
438 }
439 }
440
441 impl<'repo> io::Write for OdbWriter<'repo> {
442 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
443 unsafe {
444 let ptr = buf.as_ptr() as *const c_char;
445 let len = buf.len();
446 let res = raw::git_odb_stream_write(self.raw, ptr, len);
447 if res < 0 {
448 Err(io::Error::new(io::ErrorKind::Other, "Write error"))
449 } else {
450 Ok(buf.len())
451 }
452 }
453 }
454 fn flush(&mut self) -> io::Result<()> {
455 Ok(())
456 }
457 }
458
459 pub(crate) struct OdbPackwriterCb<'repo> {
460 pub(crate) cb: Option<Box<IndexerProgress<'repo>>>,
461 }
462
463 /// A stream to write a packfile to the ODB
464 pub struct OdbPackwriter<'repo> {
465 raw: *mut raw::git_odb_writepack,
466 progress: raw::git_indexer_progress,
467 progress_payload_ptr: *mut OdbPackwriterCb<'repo>,
468 }
469
470 impl<'repo> OdbPackwriter<'repo> {
471 /// Finish writing the packfile
472 pub fn commit(&mut self) -> Result<i32, Error> {
473 unsafe {
474 let writepack = &*self.raw;
475 let res = match writepack.commit {
476 Some(commit) => commit(self.raw, &mut self.progress),
477 None => -1,
478 };
479
480 if res < 0 {
481 Err(Error::last_error(res))
482 } else {
483 Ok(res)
484 }
485 }
486 }
487
488 /// The callback through which progress is monitored. Be aware that this is
489 /// called inline, so performance may be affected.
490 pub fn progress<F>(&mut self, cb: F) -> &mut OdbPackwriter<'repo>
491 where
492 F: FnMut(Progress<'_>) -> bool + 'repo,
493 {
494 let progress_payload =
495 unsafe { &mut *(self.progress_payload_ptr as *mut OdbPackwriterCb<'_>) };
496
497 progress_payload.cb = Some(Box::new(cb) as Box<IndexerProgress<'repo>>);
498 self
499 }
500 }
501
502 impl<'repo> io::Write for OdbPackwriter<'repo> {
503 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
504 unsafe {
505 let ptr = buf.as_ptr() as *mut c_void;
506 let len = buf.len();
507
508 let writepack = &*self.raw;
509 let res = match writepack.append {
510 Some(append) => append(self.raw, ptr, len, &mut self.progress),
511 None => -1,
512 };
513
514 if res < 0 {
515 Err(io::Error::new(io::ErrorKind::Other, "Write error"))
516 } else {
517 Ok(buf.len())
518 }
519 }
520 }
521 fn flush(&mut self) -> io::Result<()> {
522 Ok(())
523 }
524 }
525
526 impl<'repo> Drop for OdbPackwriter<'repo> {
527 fn drop(&mut self) {
528 unsafe {
529 let writepack = &*self.raw;
530 match writepack.free {
531 Some(free) => free(self.raw),
532 None => (),
533 };
534
535 drop(Box::from_raw(self.progress_payload_ptr));
536 }
537 }
538 }
539
540 pub type ForeachCb<'a> = dyn FnMut(&Oid) -> bool + 'a;
541
542 struct ForeachCbData<'a> {
543 pub callback: &'a mut ForeachCb<'a>,
544 }
545
546 extern "C" fn foreach_cb(id: *const raw::git_oid, payload: *mut c_void) -> c_int {
547 panic::wrap(|| unsafe {
548 let data = &mut *(payload as *mut ForeachCbData<'_>);
549 let res = {
550 let callback = &mut data.callback;
551 callback(&Binding::from_raw(id))
552 };
553
554 if res {
555 0
556 } else {
557 1
558 }
559 })
560 .unwrap_or(1)
561 }
562
563 pub(crate) extern "C" fn write_pack_progress_cb(
564 stats: *const raw::git_indexer_progress,
565 payload: *mut c_void,
566 ) -> c_int {
567 let ok = panic::wrap(|| unsafe {
568 let payload = &mut *(payload as *mut OdbPackwriterCb<'_>);
569
570 let callback = match payload.cb {
571 Some(ref mut cb) => cb,
572 None => return true,
573 };
574
575 let progress: Progress<'_> = Binding::from_raw(stats);
576 callback(progress)
577 });
578 if ok == Some(true) {
579 0
580 } else {
581 -1
582 }
583 }
584
585 #[cfg(test)]
586 mod tests {
587 use crate::{Buf, ObjectType, Oid, Repository};
588 use std::io::prelude::*;
589 use tempfile::TempDir;
590
591 #[test]
592 fn read() {
593 let td = TempDir::new().unwrap();
594 let repo = Repository::init(td.path()).unwrap();
595 let dat = [4, 3, 5, 6, 9];
596 let id = repo.blob(&dat).unwrap();
597 let db = repo.odb().unwrap();
598 let obj = db.read(id).unwrap();
599 let data = obj.data();
600 let size = obj.len();
601 assert_eq!(size, 5);
602 assert_eq!(dat, data);
603 assert_eq!(id, obj.id());
604 }
605
606 #[test]
607 fn read_header() {
608 let td = TempDir::new().unwrap();
609 let repo = Repository::init(td.path()).unwrap();
610 let dat = [4, 3, 5, 6, 9];
611 let id = repo.blob(&dat).unwrap();
612 let db = repo.odb().unwrap();
613 let (size, kind) = db.read_header(id).unwrap();
614
615 assert_eq!(size, 5);
616 assert_eq!(kind, ObjectType::Blob);
617 }
618
619 #[test]
620 fn write() {
621 let td = TempDir::new().unwrap();
622 let repo = Repository::init(td.path()).unwrap();
623 let dat = [4, 3, 5, 6, 9];
624 let db = repo.odb().unwrap();
625 let id = db.write(ObjectType::Blob, &dat).unwrap();
626 let blob = repo.find_blob(id).unwrap();
627 assert_eq!(blob.content(), dat);
628 }
629
630 #[test]
631 fn writer() {
632 let td = TempDir::new().unwrap();
633 let repo = Repository::init(td.path()).unwrap();
634 let dat = [4, 3, 5, 6, 9];
635 let db = repo.odb().unwrap();
636 let mut ws = db.writer(dat.len(), ObjectType::Blob).unwrap();
637 let wl = ws.write(&dat[0..3]).unwrap();
638 assert_eq!(wl, 3);
639 let wl = ws.write(&dat[3..5]).unwrap();
640 assert_eq!(wl, 2);
641 let id = ws.finalize().unwrap();
642 let blob = repo.find_blob(id).unwrap();
643 assert_eq!(blob.content(), dat);
644 }
645
646 #[test]
647 fn exists() {
648 let td = TempDir::new().unwrap();
649 let repo = Repository::init(td.path()).unwrap();
650 let dat = [4, 3, 5, 6, 9];
651 let db = repo.odb().unwrap();
652 let id = db.write(ObjectType::Blob, &dat).unwrap();
653 assert!(db.exists(id));
654 }
655
656 #[test]
657 fn exists_prefix() {
658 let td = TempDir::new().unwrap();
659 let repo = Repository::init(td.path()).unwrap();
660 let dat = [4, 3, 5, 6, 9];
661 let db = repo.odb().unwrap();
662 let id = db.write(ObjectType::Blob, &dat).unwrap();
663 let id_prefix_str = &id.to_string()[0..10];
664 let id_prefix = Oid::from_str_ext(id_prefix_str, repo.object_format()).unwrap();
665 let found_oid = db.exists_prefix(id_prefix, 10).unwrap();
666 assert_eq!(found_oid, id);
667 }
668
669 #[test]
670 fn packwriter() {
671 let (_td, repo_source) = crate::test::repo_init();
672 let (_td, repo_target) = crate::test::repo_init();
673 let mut builder = t!(repo_source.packbuilder());
674 let mut buf = Buf::new();
675 let (commit_source_id, _tree) = crate::test::commit(&repo_source);
676 t!(builder.insert_object(commit_source_id, None));
677 t!(builder.write_buf(&mut buf));
678 let db = repo_target.odb().unwrap();
679 let mut packwriter = db.packwriter().unwrap();
680 packwriter.write(&buf).unwrap();
681 packwriter.commit().unwrap();
682 let commit_target = repo_target.find_commit(commit_source_id).unwrap();
683 assert_eq!(commit_target.id(), commit_source_id);
684 }
685
686 #[test]
687 fn packwriter_progress() {
688 let mut progress_called = false;
689 {
690 let (_td, repo_source) = crate::test::repo_init();
691 let (_td, repo_target) = crate::test::repo_init();
692 let mut builder = t!(repo_source.packbuilder());
693 let mut buf = Buf::new();
694 let (commit_source_id, _tree) = crate::test::commit(&repo_source);
695 t!(builder.insert_object(commit_source_id, None));
696 t!(builder.write_buf(&mut buf));
697 let db = repo_target.odb().unwrap();
698 let mut packwriter = db.packwriter().unwrap();
699 packwriter.progress(|_| {
700 progress_called = true;
701 true
702 });
703 packwriter.write(&buf).unwrap();
704 packwriter.commit().unwrap();
705 }
706 assert_eq!(progress_called, true);
707 }
708
709 #[test]
710 fn write_with_mempack() {
711 use crate::{Buf, ResetType};
712 use std::io::Write;
713 use std::path::Path;
714
715 // Create a repo, add a mempack backend
716 let (_td, repo) = crate::test::repo_init();
717 let odb = repo.odb().unwrap();
718 let mempack = odb.add_new_mempack_backend(1000).unwrap();
719
720 // Sanity check that foo doesn't exist initially
721 let foo_file = Path::new(repo.workdir().unwrap()).join("foo");
722 assert!(!foo_file.exists());
723
724 // Make a commit that adds foo. This writes new stuff into the mempack
725 // backend.
726 let (oid1, _id) = crate::test::commit(&repo);
727 let commit1 = repo.find_commit(oid1).unwrap();
728 t!(repo.reset(commit1.as_object(), ResetType::Hard, None));
729 assert!(foo_file.exists());
730
731 // Dump the mempack modifications into a buf, and reset it. This "erases"
732 // commit-related objects from the repository. Ensure the commit appears
733 // to have become invalid, by checking for failure in `reset --hard`.
734 let mut buf = Buf::new();
735 mempack.dump(&repo, &mut buf).unwrap();
736 mempack.reset().unwrap();
737 assert!(repo
738 .reset(commit1.as_object(), ResetType::Hard, None)
739 .is_err());
740
741 // Write the buf into a packfile in the repo. This brings back the
742 // missing objects, and we verify everything is good again.
743 let mut packwriter = odb.packwriter().unwrap();
744 packwriter.write(&buf).unwrap();
745 packwriter.commit().unwrap();
746 t!(repo.reset(commit1.as_object(), ResetType::Hard, None));
747 assert!(foo_file.exists());
748 }
749
750 #[test]
751 fn stream_read() {
752 // Test for read impl of OdbReader.
753 const FOO_TEXT: &[u8] = b"this is a test";
754 let (_td, repo) = crate::test::repo_init();
755 let p = repo.path().parent().unwrap().join("foo");
756 std::fs::write(&p, FOO_TEXT).unwrap();
757 let mut index = repo.index().unwrap();
758 index.add_path(std::path::Path::new("foo")).unwrap();
759 let tree_id = index.write_tree().unwrap();
760 let tree = repo.find_tree(tree_id).unwrap();
761 let sig = repo.signature().unwrap();
762 let head_id = repo.refname_to_id("HEAD").unwrap();
763 let parent = repo.find_commit(head_id).unwrap();
764 let _commit = repo
765 .commit(Some("HEAD"), &sig, &sig, "commit", &tree, &[&parent])
766 .unwrap();
767
768 // Try reading from a commit object.
769 let odb = repo.odb().unwrap();
770 let oid = repo.refname_to_id("HEAD").unwrap();
771 let (mut reader, size, ty) = odb.reader(oid).unwrap();
772 assert!(ty == ObjectType::Commit);
773 let mut x = [0; 10000];
774 let r = reader.read(&mut x).unwrap();
775 assert!(r == size);
776
777 // Try reading from a blob. This assumes it is a loose object (packed
778 // objects can't read).
779 let commit = repo.find_commit(oid).unwrap();
780 let tree = commit.tree().unwrap();
781 let entry = tree.get_name("foo").unwrap();
782 let (mut reader, size, ty) = odb.reader(entry.id()).unwrap();
783 assert_eq!(size, FOO_TEXT.len());
784 assert!(ty == ObjectType::Blob);
785 let mut x = [0; 10000];
786 let r = reader.read(&mut x).unwrap();
787 assert_eq!(r, 14);
788 assert_eq!(&x[..FOO_TEXT.len()], FOO_TEXT);
789 }
790 }