Debian Codegraph @

src/diff.rs

raw
1 use libc::{c_char, c_int, c_void, size_t};
2 use std::ffi::CString;
3 use std::iter::FusedIterator;
4 use std::marker;
5 use std::mem;
6 use std::ops::Range;
7 use std::path::Path;
8 use std::ptr;
9 use std::slice;
10
11 use crate::util::{self, Binding};
12 use crate::ObjectFormat;
13 use crate::{panic, raw, Buf, Delta, DiffFormat, Error, FileMode, Oid, Repository};
14 use crate::{DiffFlags, DiffStatsFormat, IntoCString};
15
16 /// The diff object that contains all individual file deltas.
17 ///
18 /// This is an opaque structure which will be allocated by one of the diff
19 /// generator functions on the `Repository` structure (e.g. `diff_tree_to_tree`
20 /// or other `diff_*` functions).
21 pub struct Diff<'repo> {
22 raw: *mut raw::git_diff,
23 _marker: marker::PhantomData<&'repo Repository>,
24 }
25
26 unsafe impl<'repo> Send for Diff<'repo> {}
27
28 /// Description of changes to one entry.
29 pub struct DiffDelta<'a> {
30 raw: *mut raw::git_diff_delta,
31 _marker: marker::PhantomData<&'a raw::git_diff_delta>,
32 }
33
34 /// Description of one side of a delta.
35 ///
36 /// Although this is called a "file" it could represent a file, a symbolic
37 /// link, a submodule commit id, or even a tree (although that only happens if
38 /// you are tracking type changes or ignored/untracked directories).
39 pub struct DiffFile<'a> {
40 raw: *const raw::git_diff_file,
41 _marker: marker::PhantomData<&'a raw::git_diff_file>,
42 }
43
44 /// Structure describing options about how the diff should be executed.
45 pub struct DiffOptions {
46 pathspec: Vec<CString>,
47 pathspec_ptrs: Vec<*const c_char>,
48 old_prefix: Option<CString>,
49 new_prefix: Option<CString>,
50 raw: raw::git_diff_options,
51 }
52
53 /// Control behavior of rename and copy detection
54 pub struct DiffFindOptions {
55 raw: raw::git_diff_find_options,
56 }
57
58 /// Control behavior of formatting emails
59 pub struct DiffFormatEmailOptions {
60 raw: raw::git_diff_format_email_options,
61 }
62
63 /// Control behavior of formatting emails
64 pub struct DiffPatchidOptions {
65 raw: raw::git_diff_patchid_options,
66 }
67
68 /// An iterator over the diffs in a delta
69 pub struct Deltas<'diff> {
70 range: Range<usize>,
71 diff: &'diff Diff<'diff>,
72 }
73
74 /// Structure describing a line (or data span) of a diff.
75 pub struct DiffLine<'a> {
76 raw: *const raw::git_diff_line,
77 _marker: marker::PhantomData<&'a raw::git_diff_line>,
78 }
79
80 /// Structure describing a hunk of a diff.
81 pub struct DiffHunk<'a> {
82 raw: *const raw::git_diff_hunk,
83 _marker: marker::PhantomData<&'a raw::git_diff_hunk>,
84 }
85
86 /// Structure describing a hunk of a diff.
87 pub struct DiffStats {
88 raw: *mut raw::git_diff_stats,
89 }
90
91 /// Structure describing the binary contents of a diff.
92 pub struct DiffBinary<'a> {
93 raw: *const raw::git_diff_binary,
94 _marker: marker::PhantomData<&'a raw::git_diff_binary>,
95 }
96
97 /// The contents of one of the files in a binary diff.
98 pub struct DiffBinaryFile<'a> {
99 raw: *const raw::git_diff_binary_file,
100 _marker: marker::PhantomData<&'a raw::git_diff_binary_file>,
101 }
102
103 /// When producing a binary diff, the binary data returned will be
104 /// either the deflated full ("literal") contents of the file, or
105 /// the deflated binary delta between the two sides (whichever is
106 /// smaller).
107 #[derive(Copy, Clone, Debug)]
108 pub enum DiffBinaryKind {
109 /// There is no binary delta
110 None,
111 /// The binary data is the literal contents of the file
112 Literal,
113 /// The binary data is the delta from one side to the other
114 Delta,
115 }
116
117 type PrintCb<'a> = dyn FnMut(DiffDelta<'_>, Option<DiffHunk<'_>>, DiffLine<'_>) -> bool + 'a;
118
119 pub type FileCb<'a> = dyn FnMut(DiffDelta<'_>, f32) -> bool + 'a;
120 pub type BinaryCb<'a> = dyn FnMut(DiffDelta<'_>, DiffBinary<'_>) -> bool + 'a;
121 pub type HunkCb<'a> = dyn FnMut(DiffDelta<'_>, DiffHunk<'_>) -> bool + 'a;
122 pub type LineCb<'a> = dyn FnMut(DiffDelta<'_>, Option<DiffHunk<'_>>, DiffLine<'_>) -> bool + 'a;
123
124 pub struct DiffCallbacks<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h> {
125 pub file: Option<&'a mut FileCb<'b>>,
126 pub binary: Option<&'c mut BinaryCb<'d>>,
127 pub hunk: Option<&'e mut HunkCb<'f>>,
128 pub line: Option<&'g mut LineCb<'h>>,
129 }
130
131 impl<'repo> Diff<'repo> {
132 /// Merge one diff into another.
133 ///
134 /// This merges items from the "from" list into the "self" list. The
135 /// resulting diff will have all items that appear in either list.
136 /// If an item appears in both lists, then it will be "merged" to appear
137 /// as if the old version was from the "onto" list and the new version
138 /// is from the "from" list (with the exception that if the item has a
139 /// pending DELETE in the middle, then it will show as deleted).
140 pub fn merge(&mut self, from: &Diff<'repo>) -> Result<(), Error> {
141 unsafe {
142 try_call!(raw::git_diff_merge(self.raw, &*from.raw));
143 }
144 Ok(())
145 }
146
147 /// Returns an iterator over the deltas in this diff.
148 pub fn deltas(&self) -> Deltas<'_> {
149 let num_deltas = unsafe { raw::git_diff_num_deltas(&*self.raw) };
150 Deltas {
151 range: 0..(num_deltas as usize),
152 diff: self,
153 }
154 }
155
156 /// Return the diff delta for an entry in the diff list.
157 pub fn get_delta(&self, i: usize) -> Option<DiffDelta<'_>> {
158 unsafe {
159 let ptr = raw::git_diff_get_delta(&*self.raw, i as size_t);
160 Binding::from_raw_opt(ptr as *mut _)
161 }
162 }
163
164 /// Check if deltas are sorted case sensitively or insensitively.
165 pub fn is_sorted_icase(&self) -> bool {
166 unsafe { raw::git_diff_is_sorted_icase(&*self.raw) == 1 }
167 }
168
169 /// Iterate over a diff generating formatted text output.
170 ///
171 /// Returning `false` from the callback will terminate the iteration and
172 /// return an error from this function.
173 pub fn print<F>(&self, format: DiffFormat, mut cb: F) -> Result<(), Error>
174 where
175 F: FnMut(DiffDelta<'_>, Option<DiffHunk<'_>>, DiffLine<'_>) -> bool,
176 {
177 let mut cb: &mut PrintCb<'_> = &mut cb;
178 let ptr = &mut cb as *mut _;
179 let print: raw::git_diff_line_cb = Some(print_cb);
180 unsafe {
181 try_call!(raw::git_diff_print(self.raw, format, print, ptr as *mut _));
182 Ok(())
183 }
184 }
185
186 /// Loop over all deltas in a diff issuing callbacks.
187 ///
188 /// Returning `false` from any callback will terminate the iteration and
189 /// return an error from this function.
190 pub fn foreach(
191 &self,
192 file_cb: &mut FileCb<'_>,
193 binary_cb: Option<&mut BinaryCb<'_>>,
194 hunk_cb: Option<&mut HunkCb<'_>>,
195 line_cb: Option<&mut LineCb<'_>>,
196 ) -> Result<(), Error> {
197 let mut cbs = DiffCallbacks {
198 file: Some(file_cb),
199 binary: binary_cb,
200 hunk: hunk_cb,
201 line: line_cb,
202 };
203 let ptr = &mut cbs as *mut _;
204 unsafe {
205 let binary_cb_c: raw::git_diff_binary_cb = if cbs.binary.is_some() {
206 Some(binary_cb_c)
207 } else {
208 None
209 };
210 let hunk_cb_c: raw::git_diff_hunk_cb = if cbs.hunk.is_some() {
211 Some(hunk_cb_c)
212 } else {
213 None
214 };
215 let line_cb_c: raw::git_diff_line_cb = if cbs.line.is_some() {
216 Some(line_cb_c)
217 } else {
218 None
219 };
220 let file_cb: raw::git_diff_file_cb = Some(file_cb_c);
221 try_call!(raw::git_diff_foreach(
222 self.raw,
223 file_cb,
224 binary_cb_c,
225 hunk_cb_c,
226 line_cb_c,
227 ptr as *mut _
228 ));
229 Ok(())
230 }
231 }
232
233 /// Accumulate diff statistics for all patches.
234 pub fn stats(&self) -> Result<DiffStats, Error> {
235 let mut ret = ptr::null_mut();
236 unsafe {
237 try_call!(raw::git_diff_get_stats(&mut ret, self.raw));
238 Ok(Binding::from_raw(ret))
239 }
240 }
241
242 /// Transform a diff marking file renames, copies, etc.
243 ///
244 /// This modifies a diff in place, replacing old entries that look like
245 /// renames or copies with new entries reflecting those changes. This also
246 /// will, if requested, break modified files into add/remove pairs if the
247 /// amount of change is above a threshold.
248 pub fn find_similar(&mut self, opts: Option<&mut DiffFindOptions>) -> Result<(), Error> {
249 let opts = opts.map(|opts| &opts.raw);
250 unsafe {
251 try_call!(raw::git_diff_find_similar(self.raw, opts));
252 }
253 Ok(())
254 }
255
256 /// Create an e-mail ready patch from a diff.
257 ///
258 /// Matches the format created by `git format-patch`
259 #[doc(hidden)]
260 #[deprecated(note = "refactored to `Email::from_diff` to match upstream")]
261 pub fn format_email(
262 &mut self,
263 patch_no: usize,
264 total_patches: usize,
265 commit: &crate::Commit<'repo>,
266 opts: Option<&mut DiffFormatEmailOptions>,
267 ) -> Result<Buf, Error> {
268 assert!(patch_no > 0);
269 assert!(patch_no <= total_patches);
270 let mut default = DiffFormatEmailOptions::default();
271 let raw_opts = opts.map_or(&mut default.raw, |opts| &mut opts.raw);
272 let summary = commit.summary_bytes().unwrap();
273 let mut message = commit.message_bytes();
274 assert!(message.starts_with(summary));
275 message = &message[summary.len()..];
276 raw_opts.patch_no = patch_no;
277 raw_opts.total_patches = total_patches;
278 let id = commit.id();
279 raw_opts.id = id.raw();
280 raw_opts.summary = summary.as_ptr() as *const _;
281 raw_opts.body = message.as_ptr() as *const _;
282 raw_opts.author = commit.author().raw();
283 let buf = Buf::new();
284 #[allow(deprecated)]
285 unsafe {
286 try_call!(raw::git_diff_format_email(buf.raw(), self.raw, &*raw_opts));
287 }
288 Ok(buf)
289 }
290
291 /// Create a patch ID from a diff.
292 pub fn patchid(&self, opts: Option<&mut DiffPatchidOptions>) -> Result<Oid, Error> {
293 let mut raw = crate::util::zeroed_raw_oid();
294 unsafe {
295 try_call!(raw::git_diff_patchid(
296 &mut raw,
297 self.raw,
298 opts.map(|o| &mut o.raw)
299 ));
300 Ok(Binding::from_raw(&raw as *const _))
301 }
302 }
303
304 // TODO: num_deltas_of_type, find_similar
305 }
306 impl Diff<'static> {
307 /// Read the contents of a git patch file into a `git_diff` object.
308 ///
309 /// The diff object produced is similar to the one that would be
310 /// produced if you actually produced it computationally by comparing
311 /// two trees, however there may be subtle differences. For example,
312 /// a patch file likely contains abbreviated object IDs, so the
313 /// object IDs parsed by this function will also be abbreviated.
314 ///
315 /// This parses the diff assuming SHA1 object IDs. Use
316 /// [`Diff::from_buffer_ext`] to specify a different format.
317 pub fn from_buffer(buffer: &[u8]) -> Result<Diff<'static>, Error> {
318 Self::from_buffer_ext(buffer, ObjectFormat::Sha1)
319 }
320
321 /// Reads the contents of a git patch file into a `git_diff` object,
322 /// with a specific object format.
323 ///
324 /// See [`Diff::from_buffer`] for more details.
325 pub fn from_buffer_ext(buffer: &[u8], format: ObjectFormat) -> Result<Diff<'static>, Error> {
326 crate::init();
327 let mut diff: *mut raw::git_diff = std::ptr::null_mut();
328 let data = buffer.as_ptr() as *const c_char;
329 let len = buffer.len();
330 // NOTE: Doesn't depend on repo, so lifetime can be 'static
331 unsafe {
332 #[cfg(not(feature = "unstable-sha256"))]
333 {
334 let _ = format;
335 try_call!(raw::git_diff_from_buffer(&mut diff, data, len));
336 }
337 #[cfg(feature = "unstable-sha256")]
338 {
339 let mut opts: raw::git_diff_parse_options = std::mem::zeroed();
340 opts.version = raw::GIT_DIFF_PARSE_OPTIONS_VERSION;
341 opts.oid_type = format.raw();
342 try_call!(raw::git_diff_from_buffer(&mut diff, data, len, &mut opts));
343 }
344 Ok(Diff::from_raw(diff))
345 }
346 }
347 }
348
349 pub extern "C" fn print_cb(
350 delta: *const raw::git_diff_delta,
351 hunk: *const raw::git_diff_hunk,
352 line: *const raw::git_diff_line,
353 data: *mut c_void,
354 ) -> c_int {
355 unsafe {
356 let delta = Binding::from_raw(delta as *mut _);
357 let hunk = Binding::from_raw_opt(hunk);
358 let line = Binding::from_raw(line);
359
360 let r = panic::wrap(|| {
361 let data = data as *mut &mut PrintCb<'_>;
362 (*data)(delta, hunk, line)
363 });
364 if r == Some(true) {
365 raw::GIT_OK
366 } else {
367 raw::GIT_EUSER
368 }
369 }
370 }
371
372 pub extern "C" fn file_cb_c(
373 delta: *const raw::git_diff_delta,
374 progress: f32,
375 data: *mut c_void,
376 ) -> c_int {
377 unsafe {
378 let delta = Binding::from_raw(delta as *mut _);
379
380 let r = panic::wrap(|| {
381 let cbs = data as *mut DiffCallbacks<'_, '_, '_, '_, '_, '_, '_, '_>;
382 match (*cbs).file {
383 Some(ref mut cb) => cb(delta, progress),
384 None => false,
385 }
386 });
387 if r == Some(true) {
388 raw::GIT_OK
389 } else {
390 raw::GIT_EUSER
391 }
392 }
393 }
394
395 pub extern "C" fn binary_cb_c(
396 delta: *const raw::git_diff_delta,
397 binary: *const raw::git_diff_binary,
398 data: *mut c_void,
399 ) -> c_int {
400 unsafe {
401 let delta = Binding::from_raw(delta as *mut _);
402 let binary = Binding::from_raw(binary);
403
404 let r = panic::wrap(|| {
405 let cbs = data as *mut DiffCallbacks<'_, '_, '_, '_, '_, '_, '_, '_>;
406 match (*cbs).binary {
407 Some(ref mut cb) => cb(delta, binary),
408 None => false,
409 }
410 });
411 if r == Some(true) {
412 raw::GIT_OK
413 } else {
414 raw::GIT_EUSER
415 }
416 }
417 }
418
419 pub extern "C" fn hunk_cb_c(
420 delta: *const raw::git_diff_delta,
421 hunk: *const raw::git_diff_hunk,
422 data: *mut c_void,
423 ) -> c_int {
424 unsafe {
425 let delta = Binding::from_raw(delta as *mut _);
426 let hunk = Binding::from_raw(hunk);
427
428 let r = panic::wrap(|| {
429 let cbs = data as *mut DiffCallbacks<'_, '_, '_, '_, '_, '_, '_, '_>;
430 match (*cbs).hunk {
431 Some(ref mut cb) => cb(delta, hunk),
432 None => false,
433 }
434 });
435 if r == Some(true) {
436 raw::GIT_OK
437 } else {
438 raw::GIT_EUSER
439 }
440 }
441 }
442
443 pub extern "C" fn line_cb_c(
444 delta: *const raw::git_diff_delta,
445 hunk: *const raw::git_diff_hunk,
446 line: *const raw::git_diff_line,
447 data: *mut c_void,
448 ) -> c_int {
449 unsafe {
450 let delta = Binding::from_raw(delta as *mut _);
451 let hunk = Binding::from_raw_opt(hunk);
452 let line = Binding::from_raw(line);
453
454 let r = panic::wrap(|| {
455 let cbs = data as *mut DiffCallbacks<'_, '_, '_, '_, '_, '_, '_, '_>;
456 match (*cbs).line {
457 Some(ref mut cb) => cb(delta, hunk, line),
458 None => false,
459 }
460 });
461 if r == Some(true) {
462 raw::GIT_OK
463 } else {
464 raw::GIT_EUSER
465 }
466 }
467 }
468
469 impl<'repo> Binding for Diff<'repo> {
470 type Raw = *mut raw::git_diff;
471 unsafe fn from_raw(raw: *mut raw::git_diff) -> Diff<'repo> {
472 Diff {
473 raw,
474 _marker: marker::PhantomData,
475 }
476 }
477 fn raw(&self) -> *mut raw::git_diff {
478 self.raw
479 }
480 }
481
482 impl<'repo> Drop for Diff<'repo> {
483 fn drop(&mut self) {
484 unsafe { raw::git_diff_free(self.raw) }
485 }
486 }
487
488 impl<'a> DiffDelta<'a> {
489 /// Returns the flags on the delta.
490 ///
491 /// For more information, see `DiffFlags`'s documentation.
492 pub fn flags(&self) -> DiffFlags {
493 let flags = unsafe { (*self.raw).flags };
494 let mut result = DiffFlags::empty();
495
496 #[cfg(target_env = "msvc")]
497 fn as_u32(flag: i32) -> u32 {
498 flag as u32
499 }
500 #[cfg(not(target_env = "msvc"))]
501 fn as_u32(flag: u32) -> u32 {
502 flag
503 }
504
505 if (flags & as_u32(raw::GIT_DIFF_FLAG_BINARY)) != 0 {
506 result |= DiffFlags::BINARY;
507 }
508 if (flags & as_u32(raw::GIT_DIFF_FLAG_NOT_BINARY)) != 0 {
509 result |= DiffFlags::NOT_BINARY;
510 }
511 if (flags & as_u32(raw::GIT_DIFF_FLAG_VALID_ID)) != 0 {
512 result |= DiffFlags::VALID_ID;
513 }
514 if (flags & as_u32(raw::GIT_DIFF_FLAG_EXISTS)) != 0 {
515 result |= DiffFlags::EXISTS;
516 }
517 result
518 }
519
520 // TODO: expose when diffs are more exposed
521 // pub fn similarity(&self) -> u16 {
522 // unsafe { (*self.raw).similarity }
523 // }
524
525 /// Returns the number of files in this delta.
526 pub fn nfiles(&self) -> u16 {
527 unsafe { (*self.raw).nfiles }
528 }
529
530 /// Returns the status of this entry
531 ///
532 /// For more information, see `Delta`'s documentation
533 pub fn status(&self) -> Delta {
534 match unsafe { (*self.raw).status } {
535 raw::GIT_DELTA_UNMODIFIED => Delta::Unmodified,
536 raw::GIT_DELTA_ADDED => Delta::Added,
537 raw::GIT_DELTA_DELETED => Delta::Deleted,
538 raw::GIT_DELTA_MODIFIED => Delta::Modified,
539 raw::GIT_DELTA_RENAMED => Delta::Renamed,
540 raw::GIT_DELTA_COPIED => Delta::Copied,
541 raw::GIT_DELTA_IGNORED => Delta::Ignored,
542 raw::GIT_DELTA_UNTRACKED => Delta::Untracked,
543 raw::GIT_DELTA_TYPECHANGE => Delta::Typechange,
544 raw::GIT_DELTA_UNREADABLE => Delta::Unreadable,
545 raw::GIT_DELTA_CONFLICTED => Delta::Conflicted,
546 n => panic!("unknown diff status: {}", n),
547 }
548 }
549
550 /// Return the file which represents the "from" side of the diff.
551 ///
552 /// What side this means depends on the function that was used to generate
553 /// the diff and will be documented on the function itself.
554 pub fn old_file(&self) -> DiffFile<'a> {
555 unsafe { Binding::from_raw(&(*self.raw).old_file as *const _) }
556 }
557
558 /// Return the file which represents the "to" side of the diff.
559 ///
560 /// What side this means depends on the function that was used to generate
561 /// the diff and will be documented on the function itself.
562 pub fn new_file(&self) -> DiffFile<'a> {
563 unsafe { Binding::from_raw(&(*self.raw).new_file as *const _) }
564 }
565 }
566
567 impl<'a> Binding for DiffDelta<'a> {
568 type Raw = *mut raw::git_diff_delta;
569 unsafe fn from_raw(raw: *mut raw::git_diff_delta) -> DiffDelta<'a> {
570 DiffDelta {
571 raw,
572 _marker: marker::PhantomData,
573 }
574 }
575 fn raw(&self) -> *mut raw::git_diff_delta {
576 self.raw
577 }
578 }
579
580 impl<'a> std::fmt::Debug for DiffDelta<'a> {
581 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
582 f.debug_struct("DiffDelta")
583 .field("nfiles", &self.nfiles())
584 .field("status", &self.status())
585 .field("old_file", &self.old_file())
586 .field("new_file", &self.new_file())
587 .finish()
588 }
589 }
590
591 impl<'a> DiffFile<'a> {
592 /// Returns the Oid of this item.
593 ///
594 /// If this entry represents an absent side of a diff (e.g. the `old_file`
595 /// of a `Added` delta), then the oid returned will be zeroes.
596 pub fn id(&self) -> Oid {
597 unsafe { Binding::from_raw(&(*self.raw).id as *const _) }
598 }
599
600 /// Returns the path, in bytes, of the entry relative to the working
601 /// directory of the repository.
602 pub fn path_bytes(&self) -> Option<&'a [u8]> {
603 static FOO: () = ();
604 unsafe { crate::opt_bytes(&FOO, (*self.raw).path) }
605 }
606
607 /// Returns the path of the entry relative to the working directory of the
608 /// repository.
609 pub fn path(&self) -> Option<&'a Path> {
610 self.path_bytes().map(util::bytes2path)
611 }
612
613 /// Returns the size of this entry, in bytes
614 pub fn size(&self) -> u64 {
615 unsafe { (*self.raw).size as u64 }
616 }
617
618 /// Returns `true` if file(s) are treated as binary data.
619 pub fn is_binary(&self) -> bool {
620 unsafe { (*self.raw).flags & raw::GIT_DIFF_FLAG_BINARY as u32 != 0 }
621 }
622
623 /// Returns `true` if file(s) are treated as text data.
624 pub fn is_not_binary(&self) -> bool {
625 unsafe { (*self.raw).flags & raw::GIT_DIFF_FLAG_NOT_BINARY as u32 != 0 }
626 }
627
628 /// Returns `true` if `id` value is known correct.
629 pub fn is_valid_id(&self) -> bool {
630 unsafe { (*self.raw).flags & raw::GIT_DIFF_FLAG_VALID_ID as u32 != 0 }
631 }
632
633 /// Returns `true` if file exists at this side of the delta.
634 pub fn exists(&self) -> bool {
635 unsafe { (*self.raw).flags & raw::GIT_DIFF_FLAG_EXISTS as u32 != 0 }
636 }
637
638 /// Returns file mode.
639 pub fn mode(&self) -> FileMode {
640 match unsafe { (*self.raw).mode.into() } {
641 raw::GIT_FILEMODE_UNREADABLE => FileMode::Unreadable,
642 raw::GIT_FILEMODE_TREE => FileMode::Tree,
643 raw::GIT_FILEMODE_BLOB => FileMode::Blob,
644 raw::GIT_FILEMODE_BLOB_GROUP_WRITABLE => FileMode::BlobGroupWritable,
645 raw::GIT_FILEMODE_BLOB_EXECUTABLE => FileMode::BlobExecutable,
646 raw::GIT_FILEMODE_LINK => FileMode::Link,
647 raw::GIT_FILEMODE_COMMIT => FileMode::Commit,
648 mode => panic!("unknown mode: {}", mode),
649 }
650 }
651 }
652
653 impl<'a> Binding for DiffFile<'a> {
654 type Raw = *const raw::git_diff_file;
655 unsafe fn from_raw(raw: *const raw::git_diff_file) -> DiffFile<'a> {
656 DiffFile {
657 raw,
658 _marker: marker::PhantomData,
659 }
660 }
661 fn raw(&self) -> *const raw::git_diff_file {
662 self.raw
663 }
664 }
665
666 impl<'a> std::fmt::Debug for DiffFile<'a> {
667 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
668 let mut ds = f.debug_struct("DiffFile");
669 ds.field("id", &self.id());
670 if let Some(path_bytes) = &self.path_bytes() {
671 ds.field("path_bytes", path_bytes);
672 }
673 if let Some(path) = &self.path() {
674 ds.field("path", path);
675 }
676 ds.field("size", &self.size()).finish()
677 }
678 }
679
680 impl Default for DiffOptions {
681 fn default() -> Self {
682 Self::new()
683 }
684 }
685
686 impl DiffOptions {
687 /// Creates a new set of empty diff options.
688 ///
689 /// All flags and other options are defaulted to false or their otherwise
690 /// zero equivalents.
691 pub fn new() -> DiffOptions {
692 let mut opts = DiffOptions {
693 pathspec: Vec::new(),
694 pathspec_ptrs: Vec::new(),
695 raw: unsafe { mem::zeroed() },
696 old_prefix: None,
697 new_prefix: None,
698 };
699 assert_eq!(unsafe { raw::git_diff_init_options(&mut opts.raw, 1) }, 0);
700 opts
701 }
702
703 fn flag(&mut self, opt: raw::git_diff_option_t, val: bool) -> &mut DiffOptions {
704 let opt = opt as u32;
705 if val {
706 self.raw.flags |= opt;
707 } else {
708 self.raw.flags &= !opt;
709 }
710 self
711 }
712
713 /// Flag indicating whether the sides of the diff will be reversed.
714 pub fn reverse(&mut self, reverse: bool) -> &mut DiffOptions {
715 self.flag(raw::GIT_DIFF_REVERSE, reverse)
716 }
717
718 /// Flag indicating whether ignored files are included.
719 pub fn include_ignored(&mut self, include: bool) -> &mut DiffOptions {
720 self.flag(raw::GIT_DIFF_INCLUDE_IGNORED, include)
721 }
722
723 /// Flag indicating whether ignored directories are traversed deeply or not.
724 pub fn recurse_ignored_dirs(&mut self, recurse: bool) -> &mut DiffOptions {
725 self.flag(raw::GIT_DIFF_RECURSE_IGNORED_DIRS, recurse)
726 }
727
728 /// Flag indicating whether untracked files are in the diff
729 pub fn include_untracked(&mut self, include: bool) -> &mut DiffOptions {
730 self.flag(raw::GIT_DIFF_INCLUDE_UNTRACKED, include)
731 }
732
733 /// Flag indicating whether untracked directories are traversed deeply or
734 /// not.
735 pub fn recurse_untracked_dirs(&mut self, recurse: bool) -> &mut DiffOptions {
736 self.flag(raw::GIT_DIFF_RECURSE_UNTRACKED_DIRS, recurse)
737 }
738
739 /// Flag indicating whether unmodified files are in the diff.
740 pub fn include_unmodified(&mut self, include: bool) -> &mut DiffOptions {
741 self.flag(raw::GIT_DIFF_INCLUDE_UNMODIFIED, include)
742 }
743
744 /// If enabled, then Typechange delta records are generated.
745 pub fn include_typechange(&mut self, include: bool) -> &mut DiffOptions {
746 self.flag(raw::GIT_DIFF_INCLUDE_TYPECHANGE, include)
747 }
748
749 /// Event with `include_typechange`, the tree returned generally shows a
750 /// deleted blob. This flag correctly labels the tree transitions as a
751 /// typechange record with the `new_file`'s mode set to tree.
752 ///
753 /// Note that the tree SHA will not be available.
754 pub fn include_typechange_trees(&mut self, include: bool) -> &mut DiffOptions {
755 self.flag(raw::GIT_DIFF_INCLUDE_TYPECHANGE_TREES, include)
756 }
757
758 /// Flag indicating whether file mode changes are ignored.
759 pub fn ignore_filemode(&mut self, ignore: bool) -> &mut DiffOptions {
760 self.flag(raw::GIT_DIFF_IGNORE_FILEMODE, ignore)
761 }
762
763 /// Flag indicating whether all submodules should be treated as unmodified.
764 pub fn ignore_submodules(&mut self, ignore: bool) -> &mut DiffOptions {
765 self.flag(raw::GIT_DIFF_IGNORE_SUBMODULES, ignore)
766 }
767
768 /// Flag indicating whether case insensitive filenames should be used.
769 pub fn ignore_case(&mut self, ignore: bool) -> &mut DiffOptions {
770 self.flag(raw::GIT_DIFF_IGNORE_CASE, ignore)
771 }
772
773 /// If pathspecs are specified, this flag means that they should be applied
774 /// as an exact match instead of a fnmatch pattern.
775 pub fn disable_pathspec_match(&mut self, disable: bool) -> &mut DiffOptions {
776 self.flag(raw::GIT_DIFF_DISABLE_PATHSPEC_MATCH, disable)
777 }
778
779 /// Disable updating the `binary` flag in delta records. This is useful when
780 /// iterating over a diff if you don't need hunk and data callbacks and want
781 /// to avoid having to load a file completely.
782 pub fn skip_binary_check(&mut self, skip: bool) -> &mut DiffOptions {
783 self.flag(raw::GIT_DIFF_SKIP_BINARY_CHECK, skip)
784 }
785
786 /// When diff finds an untracked directory, to match the behavior of core
787 /// Git, it scans the contents for ignored and untracked files. If all
788 /// contents are ignored, then the directory is ignored; if any contents are
789 /// not ignored, then the directory is untracked. This is extra work that
790 /// may not matter in many cases.
791 ///
792 /// This flag turns off that scan and immediately labels an untracked
793 /// directory as untracked (changing the behavior to not match core git).
794 pub fn enable_fast_untracked_dirs(&mut self, enable: bool) -> &mut DiffOptions {
795 self.flag(raw::GIT_DIFF_ENABLE_FAST_UNTRACKED_DIRS, enable)
796 }
797
798 /// When diff finds a file in the working directory with stat information
799 /// different from the index, but the OID ends up being the same, write the
800 /// correct stat information into the index. Note: without this flag, diff
801 /// will always leave the index untouched.
802 pub fn update_index(&mut self, update: bool) -> &mut DiffOptions {
803 self.flag(raw::GIT_DIFF_UPDATE_INDEX, update)
804 }
805
806 /// Include unreadable files in the diff
807 pub fn include_unreadable(&mut self, include: bool) -> &mut DiffOptions {
808 self.flag(raw::GIT_DIFF_INCLUDE_UNREADABLE, include)
809 }
810
811 /// Include unreadable files in the diff as untracked files
812 pub fn include_unreadable_as_untracked(&mut self, include: bool) -> &mut DiffOptions {
813 self.flag(raw::GIT_DIFF_INCLUDE_UNREADABLE_AS_UNTRACKED, include)
814 }
815
816 /// Treat all files as text, disabling binary attributes and detection.
817 pub fn force_text(&mut self, force: bool) -> &mut DiffOptions {
818 self.flag(raw::GIT_DIFF_FORCE_TEXT, force)
819 }
820
821 /// Treat all files as binary, disabling text diffs
822 pub fn force_binary(&mut self, force: bool) -> &mut DiffOptions {
823 self.flag(raw::GIT_DIFF_FORCE_BINARY, force)
824 }
825
826 /// Ignore all whitespace
827 pub fn ignore_whitespace(&mut self, ignore: bool) -> &mut DiffOptions {
828 self.flag(raw::GIT_DIFF_IGNORE_WHITESPACE, ignore)
829 }
830
831 /// Ignore changes in the amount of whitespace
832 pub fn ignore_whitespace_change(&mut self, ignore: bool) -> &mut DiffOptions {
833 self.flag(raw::GIT_DIFF_IGNORE_WHITESPACE_CHANGE, ignore)
834 }
835
836 /// Ignore whitespace at the end of line
837 pub fn ignore_whitespace_eol(&mut self, ignore: bool) -> &mut DiffOptions {
838 self.flag(raw::GIT_DIFF_IGNORE_WHITESPACE_EOL, ignore)
839 }
840
841 /// Ignore blank lines
842 pub fn ignore_blank_lines(&mut self, ignore: bool) -> &mut DiffOptions {
843 self.flag(raw::GIT_DIFF_IGNORE_BLANK_LINES, ignore)
844 }
845
846 /// When generating patch text, include the content of untracked files.
847 ///
848 /// This automatically turns on `include_untracked` but it does not turn on
849 /// `recurse_untracked_dirs`. Add that flag if you want the content of every
850 /// single untracked file.
851 pub fn show_untracked_content(&mut self, show: bool) -> &mut DiffOptions {
852 self.flag(raw::GIT_DIFF_SHOW_UNTRACKED_CONTENT, show)
853 }
854
855 /// When generating output, include the names of unmodified files if they
856 /// are included in the `Diff`. Normally these are skipped in the formats
857 /// that list files (e.g. name-only, name-status, raw). Even with this these
858 /// will not be included in the patch format.
859 pub fn show_unmodified(&mut self, show: bool) -> &mut DiffOptions {
860 self.flag(raw::GIT_DIFF_SHOW_UNMODIFIED, show)
861 }
862
863 /// Use the "patience diff" algorithm
864 pub fn patience(&mut self, patience: bool) -> &mut DiffOptions {
865 self.flag(raw::GIT_DIFF_PATIENCE, patience)
866 }
867
868 /// Take extra time to find the minimal diff
869 pub fn minimal(&mut self, minimal: bool) -> &mut DiffOptions {
870 self.flag(raw::GIT_DIFF_MINIMAL, minimal)
871 }
872
873 /// Include the necessary deflate/delta information so that `git-apply` can
874 /// apply given diff information to binary files.
875 pub fn show_binary(&mut self, show: bool) -> &mut DiffOptions {
876 self.flag(raw::GIT_DIFF_SHOW_BINARY, show)
877 }
878
879 /// Use a heuristic that takes indentation and whitespace into account
880 /// which generally can produce better diffs when dealing with ambiguous
881 /// diff hunks.
882 pub fn indent_heuristic(&mut self, heuristic: bool) -> &mut DiffOptions {
883 self.flag(raw::GIT_DIFF_INDENT_HEURISTIC, heuristic)
884 }
885
886 /// Set the number of unchanged lines that define the boundary of a hunk
887 /// (and to display before and after).
888 ///
889 /// The default value for this is 3.
890 pub fn context_lines(&mut self, lines: u32) -> &mut DiffOptions {
891 self.raw.context_lines = lines;
892 self
893 }
894
895 /// Set the maximum number of unchanged lines between hunk boundaries before
896 /// the hunks will be merged into one.
897 ///
898 /// The default value for this is 0.
899 pub fn interhunk_lines(&mut self, lines: u32) -> &mut DiffOptions {
900 self.raw.interhunk_lines = lines;
901 self
902 }
903
904 /// The default value for this is `core.abbrev` or 7 if unset.
905 pub fn id_abbrev(&mut self, abbrev: u16) -> &mut DiffOptions {
906 self.raw.id_abbrev = abbrev;
907 self
908 }
909
910 /// Maximum size (in bytes) above which a blob will be marked as binary
911 /// automatically.
912 ///
913 /// A negative value will disable this entirely.
914 ///
915 /// The default value for this is 512MB.
916 pub fn max_size(&mut self, size: i64) -> &mut DiffOptions {
917 self.raw.max_size = size as raw::git_off_t;
918 self
919 }
920
921 /// The virtual "directory" to prefix old file names with in hunk headers.
922 ///
923 /// The default value for this is "a".
924 pub fn old_prefix<T: IntoCString>(&mut self, t: T) -> &mut DiffOptions {
925 self.old_prefix = Some(t.into_c_string().unwrap());
926 self
927 }
928
929 /// The virtual "directory" to prefix new file names with in hunk headers.
930 ///
931 /// The default value for this is "b".
932 pub fn new_prefix<T: IntoCString>(&mut self, t: T) -> &mut DiffOptions {
933 self.new_prefix = Some(t.into_c_string().unwrap());
934 self
935 }
936
937 /// Add to the array of paths/fnmatch patterns to constrain the diff.
938 pub fn pathspec<T: IntoCString>(&mut self, pathspec: T) -> &mut DiffOptions {
939 let s = util::cstring_to_repo_path(pathspec).unwrap();
940 self.pathspec_ptrs.push(s.as_ptr());
941 self.pathspec.push(s);
942 self
943 }
944
945 /// Acquire a pointer to the underlying raw options.
946 ///
947 /// This function is unsafe as the pointer is only valid so long as this
948 /// structure is not moved, modified, or used elsewhere.
949 pub unsafe fn raw(&mut self) -> *const raw::git_diff_options {
950 self.raw.old_prefix = self
951 .old_prefix
952 .as_ref()
953 .map(|s| s.as_ptr())
954 .unwrap_or(ptr::null());
955 self.raw.new_prefix = self
956 .new_prefix
957 .as_ref()
958 .map(|s| s.as_ptr())
959 .unwrap_or(ptr::null());
960 self.raw.pathspec.count = self.pathspec_ptrs.len() as size_t;
961 self.raw.pathspec.strings = self.pathspec_ptrs.as_ptr() as *mut _;
962 &self.raw as *const _
963 }
964
965 // TODO: expose ignore_submodules, notify_cb/notify_payload
966 }
967
968 impl<'diff> Iterator for Deltas<'diff> {
969 type Item = DiffDelta<'diff>;
970 fn next(&mut self) -> Option<DiffDelta<'diff>> {
971 self.range.next().and_then(|i| self.diff.get_delta(i))
972 }
973 fn size_hint(&self) -> (usize, Option<usize>) {
974 self.range.size_hint()
975 }
976 }
977 impl<'diff> DoubleEndedIterator for Deltas<'diff> {
978 fn next_back(&mut self) -> Option<DiffDelta<'diff>> {
979 self.range.next_back().and_then(|i| self.diff.get_delta(i))
980 }
981 }
982 impl<'diff> FusedIterator for Deltas<'diff> {}
983
984 impl<'diff> ExactSizeIterator for Deltas<'diff> {}
985
986 /// Line origin constants.
987 #[derive(Copy, Clone, Debug, PartialEq)]
988 pub enum DiffLineType {
989 /// These values will be sent to `git_diff_line_cb` along with the line
990 Context,
991 ///
992 Addition,
993 ///
994 Deletion,
995 /// Both files have no LF at end
996 ContextEOFNL,
997 /// Old has no LF at end, new does
998 AddEOFNL,
999 /// Old has LF at end, new does not
1000 DeleteEOFNL,
1001 /// The following values will only be sent to a `git_diff_line_cb` when
1002 /// the content of a diff is being formatted through `git_diff_print`.
1003 FileHeader,
1004 ///
1005 HunkHeader,
1006 /// For "Binary files x and y differ"
1007 Binary,
1008 }
1009
1010 impl Binding for DiffLineType {
1011 type Raw = raw::git_diff_line_t;
1012 unsafe fn from_raw(raw: raw::git_diff_line_t) -> Self {
1013 match raw {
1014 raw::GIT_DIFF_LINE_CONTEXT => DiffLineType::Context,
1015 raw::GIT_DIFF_LINE_ADDITION => DiffLineType::Addition,
1016 raw::GIT_DIFF_LINE_DELETION => DiffLineType::Deletion,
1017 raw::GIT_DIFF_LINE_CONTEXT_EOFNL => DiffLineType::ContextEOFNL,
1018 raw::GIT_DIFF_LINE_ADD_EOFNL => DiffLineType::AddEOFNL,
1019 raw::GIT_DIFF_LINE_DEL_EOFNL => DiffLineType::DeleteEOFNL,
1020 raw::GIT_DIFF_LINE_FILE_HDR => DiffLineType::FileHeader,
1021 raw::GIT_DIFF_LINE_HUNK_HDR => DiffLineType::HunkHeader,
1022 raw::GIT_DIFF_LINE_BINARY => DiffLineType::Binary,
1023 _ => panic!("Unknown git diff line type"),
1024 }
1025 }
1026 fn raw(&self) -> raw::git_diff_line_t {
1027 match *self {
1028 DiffLineType::Context => raw::GIT_DIFF_LINE_CONTEXT,
1029 DiffLineType::Addition => raw::GIT_DIFF_LINE_ADDITION,
1030 DiffLineType::Deletion => raw::GIT_DIFF_LINE_DELETION,
1031 DiffLineType::ContextEOFNL => raw::GIT_DIFF_LINE_CONTEXT_EOFNL,
1032 DiffLineType::AddEOFNL => raw::GIT_DIFF_LINE_ADD_EOFNL,
1033 DiffLineType::DeleteEOFNL => raw::GIT_DIFF_LINE_DEL_EOFNL,
1034 DiffLineType::FileHeader => raw::GIT_DIFF_LINE_FILE_HDR,
1035 DiffLineType::HunkHeader => raw::GIT_DIFF_LINE_HUNK_HDR,
1036 DiffLineType::Binary => raw::GIT_DIFF_LINE_BINARY,
1037 }
1038 }
1039 }
1040
1041 impl<'a> DiffLine<'a> {
1042 /// Line number in old file or `None` for added line
1043 pub fn old_lineno(&self) -> Option<u32> {
1044 match unsafe { (*self.raw).old_lineno } {
1045 n if n < 0 => None,
1046 n => Some(n as u32),
1047 }
1048 }
1049
1050 /// Line number in new file or `None` for deleted line
1051 pub fn new_lineno(&self) -> Option<u32> {
1052 match unsafe { (*self.raw).new_lineno } {
1053 n if n < 0 => None,
1054 n => Some(n as u32),
1055 }
1056 }
1057
1058 /// Number of newline characters in content
1059 pub fn num_lines(&self) -> u32 {
1060 unsafe { (*self.raw).num_lines as u32 }
1061 }
1062
1063 /// Offset in the original file to the content
1064 pub fn content_offset(&self) -> i64 {
1065 unsafe { (*self.raw).content_offset as i64 }
1066 }
1067
1068 /// Content of this line as bytes.
1069 pub fn content(&self) -> &'a [u8] {
1070 unsafe {
1071 slice::from_raw_parts(
1072 (*self.raw).content as *const u8,
1073 (*self.raw).content_len as usize,
1074 )
1075 }
1076 }
1077
1078 /// origin of this `DiffLine`.
1079 ///
1080 pub fn origin_value(&self) -> DiffLineType {
1081 unsafe { Binding::from_raw((*self.raw).origin as raw::git_diff_line_t) }
1082 }
1083
1084 /// Sigil showing the origin of this `DiffLine`.
1085 ///
1086 /// * ` ` - Line context
1087 /// * `+` - Line addition
1088 /// * `-` - Line deletion
1089 /// * `=` - Context (End of file)
1090 /// * `>` - Add (End of file)
1091 /// * `<` - Remove (End of file)
1092 /// * `F` - File header
1093 /// * `H` - Hunk header
1094 /// * `B` - Line binary
1095 pub fn origin(&self) -> char {
1096 match unsafe { (*self.raw).origin as raw::git_diff_line_t } {
1097 raw::GIT_DIFF_LINE_CONTEXT => ' ',
1098 raw::GIT_DIFF_LINE_ADDITION => '+',
1099 raw::GIT_DIFF_LINE_DELETION => '-',
1100 raw::GIT_DIFF_LINE_CONTEXT_EOFNL => '=',
1101 raw::GIT_DIFF_LINE_ADD_EOFNL => '>',
1102 raw::GIT_DIFF_LINE_DEL_EOFNL => '<',
1103 raw::GIT_DIFF_LINE_FILE_HDR => 'F',
1104 raw::GIT_DIFF_LINE_HUNK_HDR => 'H',
1105 raw::GIT_DIFF_LINE_BINARY => 'B',
1106 _ => ' ',
1107 }
1108 }
1109 }
1110
1111 impl<'a> Binding for DiffLine<'a> {
1112 type Raw = *const raw::git_diff_line;
1113 unsafe fn from_raw(raw: *const raw::git_diff_line) -> DiffLine<'a> {
1114 DiffLine {
1115 raw,
1116 _marker: marker::PhantomData,
1117 }
1118 }
1119 fn raw(&self) -> *const raw::git_diff_line {
1120 self.raw
1121 }
1122 }
1123
1124 impl<'a> std::fmt::Debug for DiffLine<'a> {
1125 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
1126 let mut ds = f.debug_struct("DiffLine");
1127 if let Some(old_lineno) = &self.old_lineno() {
1128 ds.field("old_lineno", old_lineno);
1129 }
1130 if let Some(new_lineno) = &self.new_lineno() {
1131 ds.field("new_lineno", new_lineno);
1132 }
1133 ds.field("num_lines", &self.num_lines())
1134 .field("content_offset", &self.content_offset())
1135 .field("content", &self.content())
1136 .field("origin", &self.origin())
1137 .finish()
1138 }
1139 }
1140
1141 impl<'a> DiffHunk<'a> {
1142 /// Starting line number in old_file
1143 pub fn old_start(&self) -> u32 {
1144 unsafe { (*self.raw).old_start as u32 }
1145 }
1146
1147 /// Number of lines in old_file
1148 pub fn old_lines(&self) -> u32 {
1149 unsafe { (*self.raw).old_lines as u32 }
1150 }
1151
1152 /// Starting line number in new_file
1153 pub fn new_start(&self) -> u32 {
1154 unsafe { (*self.raw).new_start as u32 }
1155 }
1156
1157 /// Number of lines in new_file
1158 pub fn new_lines(&self) -> u32 {
1159 unsafe { (*self.raw).new_lines as u32 }
1160 }
1161
1162 /// Header text
1163 pub fn header(&self) -> &'a [u8] {
1164 unsafe {
1165 slice::from_raw_parts(
1166 (*self.raw).header.as_ptr() as *const u8,
1167 (*self.raw).header_len as usize,
1168 )
1169 }
1170 }
1171 }
1172
1173 impl<'a> Binding for DiffHunk<'a> {
1174 type Raw = *const raw::git_diff_hunk;
1175 unsafe fn from_raw(raw: *const raw::git_diff_hunk) -> DiffHunk<'a> {
1176 DiffHunk {
1177 raw,
1178 _marker: marker::PhantomData,
1179 }
1180 }
1181 fn raw(&self) -> *const raw::git_diff_hunk {
1182 self.raw
1183 }
1184 }
1185
1186 impl<'a> std::fmt::Debug for DiffHunk<'a> {
1187 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
1188 f.debug_struct("DiffHunk")
1189 .field("old_start", &self.old_start())
1190 .field("old_lines", &self.old_lines())
1191 .field("new_start", &self.new_start())
1192 .field("new_lines", &self.new_lines())
1193 .field("header", &self.header())
1194 .finish()
1195 }
1196 }
1197
1198 impl DiffStats {
1199 /// Get the total number of files changed in a diff.
1200 pub fn files_changed(&self) -> usize {
1201 unsafe { raw::git_diff_stats_files_changed(&*self.raw) as usize }
1202 }
1203
1204 /// Get the total number of insertions in a diff
1205 pub fn insertions(&self) -> usize {
1206 unsafe { raw::git_diff_stats_insertions(&*self.raw) as usize }
1207 }
1208
1209 /// Get the total number of deletions in a diff
1210 pub fn deletions(&self) -> usize {
1211 unsafe { raw::git_diff_stats_deletions(&*self.raw) as usize }
1212 }
1213
1214 /// Print diff statistics to a Buf
1215 pub fn to_buf(&self, format: DiffStatsFormat, width: usize) -> Result<Buf, Error> {
1216 let buf = Buf::new();
1217 unsafe {
1218 try_call!(raw::git_diff_stats_to_buf(
1219 buf.raw(),
1220 self.raw,
1221 format.bits(),
1222 width as size_t
1223 ));
1224 }
1225 Ok(buf)
1226 }
1227 }
1228
1229 impl Binding for DiffStats {
1230 type Raw = *mut raw::git_diff_stats;
1231
1232 unsafe fn from_raw(raw: *mut raw::git_diff_stats) -> DiffStats {
1233 DiffStats { raw }
1234 }
1235 fn raw(&self) -> *mut raw::git_diff_stats {
1236 self.raw
1237 }
1238 }
1239
1240 impl Drop for DiffStats {
1241 fn drop(&mut self) {
1242 unsafe { raw::git_diff_stats_free(self.raw) }
1243 }
1244 }
1245
1246 impl std::fmt::Debug for DiffStats {
1247 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
1248 f.debug_struct("DiffStats")
1249 .field("files_changed", &self.files_changed())
1250 .field("insertions", &self.insertions())
1251 .field("deletions", &self.deletions())
1252 .finish()
1253 }
1254 }
1255
1256 impl<'a> DiffBinary<'a> {
1257 /// Returns whether there is data in this binary structure or not.
1258 ///
1259 /// If this is `true`, then this was produced and included binary content.
1260 /// If this is `false` then this was generated knowing only that a binary
1261 /// file changed but without providing the data, probably from a patch that
1262 /// said `Binary files a/file.txt and b/file.txt differ`.
1263 pub fn contains_data(&self) -> bool {
1264 unsafe { (*self.raw).contains_data == 1 }
1265 }
1266
1267 /// The contents of the old file.
1268 pub fn old_file(&self) -> DiffBinaryFile<'a> {
1269 unsafe { Binding::from_raw(&(*self.raw).old_file as *const _) }
1270 }
1271
1272 /// The contents of the new file.
1273 pub fn new_file(&self) -> DiffBinaryFile<'a> {
1274 unsafe { Binding::from_raw(&(*self.raw).new_file as *const _) }
1275 }
1276 }
1277
1278 impl<'a> Binding for DiffBinary<'a> {
1279 type Raw = *const raw::git_diff_binary;
1280 unsafe fn from_raw(raw: *const raw::git_diff_binary) -> DiffBinary<'a> {
1281 DiffBinary {
1282 raw,
1283 _marker: marker::PhantomData,
1284 }
1285 }
1286 fn raw(&self) -> *const raw::git_diff_binary {
1287 self.raw
1288 }
1289 }
1290
1291 impl<'a> DiffBinaryFile<'a> {
1292 /// The type of binary data for this file
1293 pub fn kind(&self) -> DiffBinaryKind {
1294 unsafe { Binding::from_raw((*self.raw).kind) }
1295 }
1296
1297 /// The binary data, deflated
1298 pub fn data(&self) -> &[u8] {
1299 unsafe {
1300 slice::from_raw_parts((*self.raw).data as *const u8, (*self.raw).datalen as usize)
1301 }
1302 }
1303
1304 /// The length of the binary data after inflation
1305 pub fn inflated_len(&self) -> usize {
1306 unsafe { (*self.raw).inflatedlen as usize }
1307 }
1308 }
1309
1310 impl<'a> Binding for DiffBinaryFile<'a> {
1311 type Raw = *const raw::git_diff_binary_file;
1312 unsafe fn from_raw(raw: *const raw::git_diff_binary_file) -> DiffBinaryFile<'a> {
1313 DiffBinaryFile {
1314 raw,
1315 _marker: marker::PhantomData,
1316 }
1317 }
1318 fn raw(&self) -> *const raw::git_diff_binary_file {
1319 self.raw
1320 }
1321 }
1322
1323 impl Binding for DiffBinaryKind {
1324 type Raw = raw::git_diff_binary_t;
1325 unsafe fn from_raw(raw: raw::git_diff_binary_t) -> DiffBinaryKind {
1326 match raw {
1327 raw::GIT_DIFF_BINARY_NONE => DiffBinaryKind::None,
1328 raw::GIT_DIFF_BINARY_LITERAL => DiffBinaryKind::Literal,
1329 raw::GIT_DIFF_BINARY_DELTA => DiffBinaryKind::Delta,
1330 _ => panic!("Unknown git diff binary kind"),
1331 }
1332 }
1333 fn raw(&self) -> raw::git_diff_binary_t {
1334 match *self {
1335 DiffBinaryKind::None => raw::GIT_DIFF_BINARY_NONE,
1336 DiffBinaryKind::Literal => raw::GIT_DIFF_BINARY_LITERAL,
1337 DiffBinaryKind::Delta => raw::GIT_DIFF_BINARY_DELTA,
1338 }
1339 }
1340 }
1341
1342 impl Default for DiffFindOptions {
1343 fn default() -> Self {
1344 Self::new()
1345 }
1346 }
1347
1348 impl DiffFindOptions {
1349 /// Creates a new set of empty diff find options.
1350 ///
1351 /// All flags and other options are defaulted to false or their otherwise
1352 /// zero equivalents.
1353 pub fn new() -> DiffFindOptions {
1354 let mut opts = DiffFindOptions {
1355 raw: unsafe { mem::zeroed() },
1356 };
1357 assert_eq!(
1358 unsafe { raw::git_diff_find_init_options(&mut opts.raw, 1) },
1359 0
1360 );
1361 opts
1362 }
1363
1364 fn flag(&mut self, opt: u32, val: bool) -> &mut DiffFindOptions {
1365 if val {
1366 self.raw.flags |= opt;
1367 } else {
1368 self.raw.flags &= !opt;
1369 }
1370 self
1371 }
1372
1373 /// Reset all flags back to their unset state, indicating that
1374 /// `diff.renames` should be used instead. This is overridden once any flag
1375 /// is set.
1376 pub fn by_config(&mut self) -> &mut DiffFindOptions {
1377 self.flag(0xffffffff, false)
1378 }
1379
1380 /// Look for renames?
1381 pub fn renames(&mut self, find: bool) -> &mut DiffFindOptions {
1382 self.flag(raw::GIT_DIFF_FIND_RENAMES, find)
1383 }
1384
1385 /// Consider old side of modified for renames?
1386 pub fn renames_from_rewrites(&mut self, find: bool) -> &mut DiffFindOptions {
1387 self.flag(raw::GIT_DIFF_FIND_RENAMES_FROM_REWRITES, find)
1388 }
1389
1390 /// Look for copies?
1391 pub fn copies(&mut self, find: bool) -> &mut DiffFindOptions {
1392 self.flag(raw::GIT_DIFF_FIND_COPIES, find)
1393 }
1394
1395 /// Consider unmodified as copy sources?
1396 ///
1397 /// For this to work correctly, use `include_unmodified` when the initial
1398 /// diff is being generated.
1399 pub fn copies_from_unmodified(&mut self, find: bool) -> &mut DiffFindOptions {
1400 self.flag(raw::GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED, find)
1401 }
1402
1403 /// Mark significant rewrites for split.
1404 pub fn rewrites(&mut self, find: bool) -> &mut DiffFindOptions {
1405 self.flag(raw::GIT_DIFF_FIND_REWRITES, find)
1406 }
1407
1408 /// Actually split large rewrites into delete/add pairs
1409 pub fn break_rewrites(&mut self, find: bool) -> &mut DiffFindOptions {
1410 self.flag(raw::GIT_DIFF_BREAK_REWRITES, find)
1411 }
1412
1413 #[doc(hidden)]
1414 pub fn break_rewries(&mut self, find: bool) -> &mut DiffFindOptions {
1415 self.break_rewrites(find)
1416 }
1417
1418 /// Find renames/copies for untracked items in working directory.
1419 ///
1420 /// For this to work correctly use the `include_untracked` option when the
1421 /// initial diff is being generated.
1422 pub fn for_untracked(&mut self, find: bool) -> &mut DiffFindOptions {
1423 self.flag(raw::GIT_DIFF_FIND_FOR_UNTRACKED, find)
1424 }
1425
1426 /// Turn on all finding features.
1427 pub fn all(&mut self, find: bool) -> &mut DiffFindOptions {
1428 self.flag(raw::GIT_DIFF_FIND_ALL, find)
1429 }
1430
1431 /// Measure similarity ignoring leading whitespace (default)
1432 pub fn ignore_leading_whitespace(&mut self, ignore: bool) -> &mut DiffFindOptions {
1433 self.flag(raw::GIT_DIFF_FIND_IGNORE_LEADING_WHITESPACE, ignore)
1434 }
1435
1436 /// Measure similarity ignoring all whitespace
1437 pub fn ignore_whitespace(&mut self, ignore: bool) -> &mut DiffFindOptions {
1438 self.flag(raw::GIT_DIFF_FIND_IGNORE_WHITESPACE, ignore)
1439 }
1440
1441 /// Measure similarity including all data
1442 pub fn dont_ignore_whitespace(&mut self, dont: bool) -> &mut DiffFindOptions {
1443 self.flag(raw::GIT_DIFF_FIND_DONT_IGNORE_WHITESPACE, dont)
1444 }
1445
1446 /// Measure similarity only by comparing SHAs (fast and cheap)
1447 pub fn exact_match_only(&mut self, exact: bool) -> &mut DiffFindOptions {
1448 self.flag(raw::GIT_DIFF_FIND_EXACT_MATCH_ONLY, exact)
1449 }
1450
1451 /// Do not break rewrites unless they contribute to a rename.
1452 ///
1453 /// Normally, `break_rewrites` and `rewrites` will measure the
1454 /// self-similarity of modified files and split the ones that have changed a
1455 /// lot into a delete/add pair. Then the sides of that pair will be
1456 /// considered candidates for rename and copy detection
1457 ///
1458 /// If you add this flag in and the split pair is not used for an actual
1459 /// rename or copy, then the modified record will be restored to a regular
1460 /// modified record instead of being split.
1461 pub fn break_rewrites_for_renames_only(&mut self, b: bool) -> &mut DiffFindOptions {
1462 self.flag(raw::GIT_DIFF_BREAK_REWRITES_FOR_RENAMES_ONLY, b)
1463 }
1464
1465 /// Remove any unmodified deltas after find_similar is done.
1466 ///
1467 /// Using `copies_from_unmodified` to emulate the `--find-copies-harder`
1468 /// behavior requires building a diff with the `include_unmodified` flag. If
1469 /// you do not want unmodified records in the final result, pas this flag to
1470 /// have them removed.
1471 pub fn remove_unmodified(&mut self, remove: bool) -> &mut DiffFindOptions {
1472 self.flag(raw::GIT_DIFF_FIND_REMOVE_UNMODIFIED, remove)
1473 }
1474
1475 /// Similarity to consider a file renamed (default 50)
1476 pub fn rename_threshold(&mut self, thresh: u16) -> &mut DiffFindOptions {
1477 self.raw.rename_threshold = thresh;
1478 self
1479 }
1480
1481 /// Similarity of modified to be eligible rename source (default 50)
1482 pub fn rename_from_rewrite_threshold(&mut self, thresh: u16) -> &mut DiffFindOptions {
1483 self.raw.rename_from_rewrite_threshold = thresh;
1484 self
1485 }
1486
1487 /// Similarity to consider a file copy (default 50)
1488 pub fn copy_threshold(&mut self, thresh: u16) -> &mut DiffFindOptions {
1489 self.raw.copy_threshold = thresh;
1490 self
1491 }
1492
1493 /// Similarity to split modify into delete/add pair (default 60)
1494 pub fn break_rewrite_threshold(&mut self, thresh: u16) -> &mut DiffFindOptions {
1495 self.raw.break_rewrite_threshold = thresh;
1496 self
1497 }
1498
1499 /// Maximum similarity sources to examine for a file (somewhat like
1500 /// git-diff's `-l` option or `diff.renameLimit` config)
1501 ///
1502 /// Defaults to 200
1503 pub fn rename_limit(&mut self, limit: usize) -> &mut DiffFindOptions {
1504 self.raw.rename_limit = limit as size_t;
1505 self
1506 }
1507
1508 // TODO: expose git_diff_similarity_metric
1509
1510 /// Acquire a pointer to the underlying raw options.
1511 pub unsafe fn raw(&mut self) -> *const raw::git_diff_find_options {
1512 &self.raw
1513 }
1514 }
1515
1516 impl Default for DiffFormatEmailOptions {
1517 fn default() -> Self {
1518 Self::new()
1519 }
1520 }
1521
1522 impl DiffFormatEmailOptions {
1523 /// Creates a new set of email options,
1524 /// initialized to the default values
1525 pub fn new() -> Self {
1526 let mut opts = DiffFormatEmailOptions {
1527 raw: unsafe { mem::zeroed() },
1528 };
1529 assert_eq!(
1530 unsafe { raw::git_diff_format_email_options_init(&mut opts.raw, 1) },
1531 0
1532 );
1533 opts
1534 }
1535
1536 fn flag(&mut self, opt: u32, val: bool) -> &mut Self {
1537 if val {
1538 self.raw.flags |= opt;
1539 } else {
1540 self.raw.flags &= !opt;
1541 }
1542 self
1543 }
1544
1545 /// Exclude `[PATCH]` from the subject header
1546 pub fn exclude_subject_patch_header(&mut self, should_exclude: bool) -> &mut Self {
1547 self.flag(
1548 raw::GIT_DIFF_FORMAT_EMAIL_EXCLUDE_SUBJECT_PATCH_MARKER,
1549 should_exclude,
1550 )
1551 }
1552 }
1553
1554 impl DiffPatchidOptions {
1555 /// Creates a new set of patchid options,
1556 /// initialized to the default values
1557 pub fn new() -> Self {
1558 let mut opts = DiffPatchidOptions {
1559 raw: unsafe { mem::zeroed() },
1560 };
1561 assert_eq!(
1562 unsafe {
1563 raw::git_diff_patchid_options_init(
1564 &mut opts.raw,
1565 raw::GIT_DIFF_PATCHID_OPTIONS_VERSION,
1566 )
1567 },
1568 0
1569 );
1570 opts
1571 }
1572 }
1573
1574 #[cfg(test)]
1575 mod tests {
1576 #[cfg(feature = "unstable-sha256")]
1577 use crate::Diff;
1578 use crate::{DiffLineType, DiffOptions, Oid, Signature, Time};
1579 use std::borrow::Borrow;
1580 use std::fs::File;
1581 use std::io::Write;
1582 use std::path::Path;
1583
1584 #[test]
1585 fn smoke() {
1586 let (_td, repo) = crate::test::repo_init();
1587 let diff = repo.diff_tree_to_workdir(None, None).unwrap();
1588 assert_eq!(diff.deltas().len(), 0);
1589 let stats = diff.stats().unwrap();
1590 assert_eq!(stats.insertions(), 0);
1591 assert_eq!(stats.deletions(), 0);
1592 assert_eq!(stats.files_changed(), 0);
1593 let patchid = diff.patchid(None).unwrap();
1594 assert_ne!(patchid, Oid::ZERO_SHA1);
1595 }
1596
1597 #[test]
1598 fn foreach_smoke() {
1599 let (_td, repo) = crate::test::repo_init();
1600 let diff = t!(repo.diff_tree_to_workdir(None, None));
1601 let mut count = 0;
1602 t!(diff.foreach(
1603 &mut |_file, _progress| {
1604 count = count + 1;
1605 true
1606 },
1607 None,
1608 None,
1609 None
1610 ));
1611 assert_eq!(count, 0);
1612 }
1613
1614 #[test]
1615 fn foreach_file_only() {
1616 let path = Path::new("foo");
1617 let (td, repo) = crate::test::repo_init();
1618 t!(t!(File::create(&td.path().join(path))).write_all(b"bar"));
1619 let mut opts = DiffOptions::new();
1620 opts.include_untracked(true);
1621 let diff = t!(repo.diff_tree_to_workdir(None, Some(&mut opts)));
1622 let mut count = 0;
1623 let mut result = None;
1624 t!(diff.foreach(
1625 &mut |file, _progress| {
1626 count = count + 1;
1627 result = file.new_file().path().map(ToOwned::to_owned);
1628 true
1629 },
1630 None,
1631 None,
1632 None
1633 ));
1634 assert_eq!(result.as_ref().map(Borrow::borrow), Some(path));
1635 assert_eq!(count, 1);
1636 }
1637
1638 #[test]
1639 fn foreach_file_and_hunk() {
1640 let path = Path::new("foo");
1641 let (td, repo) = crate::test::repo_init();
1642 t!(t!(File::create(&td.path().join(path))).write_all(b"bar"));
1643 let mut index = t!(repo.index());
1644 t!(index.add_path(path));
1645 let mut opts = DiffOptions::new();
1646 opts.include_untracked(true);
1647 let diff = t!(repo.diff_tree_to_index(None, Some(&index), Some(&mut opts)));
1648 let mut new_lines = 0;
1649 t!(diff.foreach(
1650 &mut |_file, _progress| { true },
1651 None,
1652 Some(&mut |_file, hunk| {
1653 new_lines = hunk.new_lines();
1654 true
1655 }),
1656 None
1657 ));
1658 assert_eq!(new_lines, 1);
1659 }
1660
1661 #[test]
1662 fn foreach_all_callbacks() {
1663 let fib = vec![0, 1, 1, 2, 3, 5, 8];
1664 // Verified with a node implementation of deflate, might be worth
1665 // adding a deflate lib to do this inline here.
1666 let deflated_fib = vec![120, 156, 99, 96, 100, 100, 98, 102, 229, 0, 0, 0, 53, 0, 21];
1667 let foo_path = Path::new("foo");
1668 let bin_path = Path::new("bin");
1669 let (td, repo) = crate::test::repo_init();
1670 t!(t!(File::create(&td.path().join(foo_path))).write_all(b"bar\n"));
1671 t!(t!(File::create(&td.path().join(bin_path))).write_all(&fib));
1672 let mut index = t!(repo.index());
1673 t!(index.add_path(foo_path));
1674 t!(index.add_path(bin_path));
1675 let mut opts = DiffOptions::new();
1676 opts.include_untracked(true).show_binary(true);
1677 let diff = t!(repo.diff_tree_to_index(None, Some(&index), Some(&mut opts)));
1678 let mut bin_content = None;
1679 let mut new_lines = 0;
1680 let mut line_content = None;
1681 t!(diff.foreach(
1682 &mut |_file, _progress| { true },
1683 Some(&mut |_file, binary| {
1684 bin_content = Some(binary.new_file().data().to_owned());
1685 true
1686 }),
1687 Some(&mut |_file, hunk| {
1688 new_lines = hunk.new_lines();
1689 true
1690 }),
1691 Some(&mut |_file, _hunk, line| {
1692 line_content = String::from_utf8(line.content().into()).ok();
1693 true
1694 })
1695 ));
1696 assert_eq!(bin_content, Some(deflated_fib));
1697 assert_eq!(new_lines, 1);
1698 assert_eq!(line_content, Some("bar\n".to_string()));
1699 }
1700
1701 #[test]
1702 fn format_email_simple() {
1703 let (_td, repo) = crate::test::repo_init();
1704 const COMMIT_MESSAGE: &str = "Modify some content";
1705 const EXPECTED_EMAIL_START: &str = concat!(
1706 "From f1234fb0588b6ed670779a34ba5c51ef962f285f Mon Sep 17 00:00:00 2001\n",
1707 "From: Techcable <[email protected]>\n",
1708 "Date: Tue, 11 Jan 1972 17:46:40 +0000\n",
1709 "Subject: [PATCH] Modify some content\n",
1710 "\n",
1711 "---\n",
1712 " file1.txt | 8 +++++---\n",
1713 " 1 file changed, 5 insertions(+), 3 deletions(-)\n",
1714 "\n",
1715 "diff --git a/file1.txt b/file1.txt\n",
1716 "index 94aaae8..af8f41d 100644\n",
1717 "--- a/file1.txt\n",
1718 "+++ b/file1.txt\n",
1719 "@@ -1,15 +1,17 @@\n",
1720 " file1.txt\n",
1721 " file1.txt\n",
1722 "+_file1.txt_\n",
1723 " file1.txt\n",
1724 " file1.txt\n",
1725 " file1.txt\n",
1726 " file1.txt\n",
1727 "+\n",
1728 "+\n",
1729 " file1.txt\n",
1730 " file1.txt\n",
1731 " file1.txt\n",
1732 " file1.txt\n",
1733 " file1.txt\n",
1734 "-file1.txt\n",
1735 "-file1.txt\n",
1736 "-file1.txt\n",
1737 "+_file1.txt_\n",
1738 "+_file1.txt_\n",
1739 " file1.txt\n",
1740 "--\n"
1741 );
1742 const ORIGINAL_FILE: &str = concat!(
1743 "file1.txt\n",
1744 "file1.txt\n",
1745 "file1.txt\n",
1746 "file1.txt\n",
1747 "file1.txt\n",
1748 "file1.txt\n",
1749 "file1.txt\n",
1750 "file1.txt\n",
1751 "file1.txt\n",
1752 "file1.txt\n",
1753 "file1.txt\n",
1754 "file1.txt\n",
1755 "file1.txt\n",
1756 "file1.txt\n",
1757 "file1.txt\n"
1758 );
1759 const UPDATED_FILE: &str = concat!(
1760 "file1.txt\n",
1761 "file1.txt\n",
1762 "_file1.txt_\n",
1763 "file1.txt\n",
1764 "file1.txt\n",
1765 "file1.txt\n",
1766 "file1.txt\n",
1767 "\n",
1768 "\n",
1769 "file1.txt\n",
1770 "file1.txt\n",
1771 "file1.txt\n",
1772 "file1.txt\n",
1773 "file1.txt\n",
1774 "_file1.txt_\n",
1775 "_file1.txt_\n",
1776 "file1.txt\n"
1777 );
1778 const FILE_MODE: i32 = 0o100644;
1779 let original_file = repo.blob(ORIGINAL_FILE.as_bytes()).unwrap();
1780 let updated_file = repo.blob(UPDATED_FILE.as_bytes()).unwrap();
1781 let mut original_tree = repo.treebuilder(None).unwrap();
1782 original_tree
1783 .insert("file1.txt", original_file, FILE_MODE)
1784 .unwrap();
1785 let original_tree = original_tree.write().unwrap();
1786 let mut updated_tree = repo.treebuilder(None).unwrap();
1787 updated_tree
1788 .insert("file1.txt", updated_file, FILE_MODE)
1789 .unwrap();
1790 let updated_tree = updated_tree.write().unwrap();
1791 let time = Time::new(64_000_000, 0);
1792 let author = Signature::new("Techcable", "[email protected]", &time).unwrap();
1793 let updated_commit = repo
1794 .commit(
1795 None,
1796 &author,
1797 &author,
1798 COMMIT_MESSAGE,
1799 &repo.find_tree(updated_tree).unwrap(),
1800 &[], // NOTE: Have no parents to ensure stable hash
1801 )
1802 .unwrap();
1803 let updated_commit = repo.find_commit(updated_commit).unwrap();
1804 let mut diff = repo
1805 .diff_tree_to_tree(
1806 Some(&repo.find_tree(original_tree).unwrap()),
1807 Some(&repo.find_tree(updated_tree).unwrap()),
1808 None,
1809 )
1810 .unwrap();
1811 #[allow(deprecated)]
1812 let actual_email = diff.format_email(1, 1, &updated_commit, None).unwrap();
1813 let actual_email = actual_email.as_str().unwrap();
1814 assert!(
1815 actual_email.starts_with(EXPECTED_EMAIL_START),
1816 "Unexpected email:\n{}",
1817 actual_email
1818 );
1819 let mut remaining_lines = actual_email[EXPECTED_EMAIL_START.len()..].lines();
1820 let version_line = remaining_lines.next();
1821 assert!(
1822 version_line.unwrap().starts_with("libgit2"),
1823 "Invalid version line: {:?}",
1824 version_line
1825 );
1826 while let Some(line) = remaining_lines.next() {
1827 assert_eq!(line.trim(), "")
1828 }
1829 }
1830
1831 #[test]
1832 fn foreach_diff_line_origin_value() {
1833 let foo_path = Path::new("foo");
1834 let (td, repo) = crate::test::repo_init();
1835 t!(t!(File::create(&td.path().join(foo_path))).write_all(b"bar\n"));
1836 let mut index = t!(repo.index());
1837 t!(index.add_path(foo_path));
1838 let mut opts = DiffOptions::new();
1839 opts.include_untracked(true);
1840 let diff = t!(repo.diff_tree_to_index(None, Some(&index), Some(&mut opts)));
1841 let mut origin_values: Vec<DiffLineType> = Vec::new();
1842 t!(diff.foreach(
1843 &mut |_file, _progress| { true },
1844 None,
1845 None,
1846 Some(&mut |_file, _hunk, line| {
1847 origin_values.push(line.origin_value());
1848 true
1849 })
1850 ));
1851 assert_eq!(origin_values.len(), 1);
1852 assert_eq!(origin_values[0], DiffLineType::Addition);
1853 }
1854
1855 #[test]
1856 fn foreach_exits_with_euser() {
1857 let foo_path = Path::new("foo");
1858 let bar_path = Path::new("foo");
1859
1860 let (td, repo) = crate::test::repo_init();
1861 t!(t!(File::create(&td.path().join(foo_path))).write_all(b"bar\n"));
1862
1863 let mut index = t!(repo.index());
1864 t!(index.add_path(foo_path));
1865 t!(index.add_path(bar_path));
1866
1867 let mut opts = DiffOptions::new();
1868 opts.include_untracked(true);
1869 let diff = t!(repo.diff_tree_to_index(None, Some(&index), Some(&mut opts)));
1870
1871 let mut calls = 0;
1872 let result = diff.foreach(
1873 &mut |_file, _progress| {
1874 calls += 1;
1875 false
1876 },
1877 None,
1878 None,
1879 None,
1880 );
1881
1882 assert_eq!(result.unwrap_err().code(), crate::ErrorCode::User);
1883 }
1884
1885 #[test]
1886 #[cfg(feature = "unstable-sha256")]
1887 fn diff_sha256() {
1888 let (_td, repo) = crate::test::repo_init_sha256();
1889 let diff = repo.diff_tree_to_workdir(None, None).unwrap();
1890 assert_eq!(diff.deltas().len(), 0);
1891 let stats = diff.stats().unwrap();
1892 assert_eq!(stats.insertions(), 0);
1893 assert_eq!(stats.deletions(), 0);
1894 assert_eq!(stats.files_changed(), 0);
1895 let patchid = diff.patchid(None).unwrap();
1896
1897 // Verify SHA256 OID (32 bytes)
1898 assert_eq!(patchid.as_bytes().len(), 32);
1899 }
1900
1901 #[test]
1902 #[cfg(feature = "unstable-sha256")]
1903 fn diff_from_buffer_sha256() {
1904 // Minimal patch with SHA256 OID (64 chars)
1905 let patch = b"diff --git a/file.txt b/file.txt
1906 index 0000000000000000000000000000000000000000000000000000000000000000..1111111111111111111111111111111111111111111111111111111111111111 100644
1907 --- a/file.txt
1908 +++ b/file.txt
1909 @@ -1 +1 @@
1910 -old
1911 +new
1912 ";
1913
1914 let diff = Diff::from_buffer_ext(patch, crate::ObjectFormat::Sha256).unwrap();
1915 assert_eq!(diff.deltas().len(), 1);
1916 }
1917 }