on v0.6.0 help sign in
bat/src/diff.rs
77 lines 2.4 kB history raw
1use git2::{DiffOptions, IntoCString, Repository};
2use std::collections::HashMap;
3use std::fs;
4use std::path::Path;
6#[derive(Copy, Clone, Debug)]
7pub enum LineChange {
8 Added,
9 RemovedAbove,
10 RemovedBelow,
11 Modified,
14pub type LineChanges = HashMap<u32, LineChange>;
16pub fn get_git_diff(filename: &str) -> Option<LineChanges> {
17 let repo = Repository::discover(&filename).ok()?;
18 let path_absolute = fs::canonicalize(&filename).ok()?;
19 let path_relative_to_repo = path_absolute.strip_prefix(repo.workdir()?).ok()?;
21 let mut diff_options = DiffOptions::new();
22 let pathspec = path_relative_to_repo.into_c_string().ok()?;
23 diff_options.pathspec(pathspec);
24 diff_options.context_lines(0);
26 let diff = repo
27 .diff_index_to_workdir(None, Some(&mut diff_options))
28 .ok()?;
30 let mut line_changes: LineChanges = HashMap::new();
32 let mark_section =
33 |line_changes: &mut LineChanges, start: u32, end: i32, change: LineChange| {
34 for line in start..(end + 1) as u32 {
35 line_changes.insert(line, change);
36 }
37 };
39 let _ = diff.foreach(
40 &mut |_, _| true,
41 None,
42 Some(&mut |delta, hunk| {
43 let path = delta.new_file().path().unwrap_or_else(|| Path::new(""));
45 if path_relative_to_repo != path {
46 return false;
47 }
49 let old_lines = hunk.old_lines();
50 let new_start = hunk.new_start();
51 let new_lines = hunk.new_lines();
52 let new_end = (new_start + new_lines) as i32 - 1;
54 if old_lines == 0 && new_lines > 0 {
55 mark_section(&mut line_changes, new_start, new_end, LineChange::Added);
56 } else if new_lines == 0 && old_lines > 0 {
57 if new_start == 0 {
58 mark_section(&mut line_changes, 1, 1, LineChange::RemovedAbove);
59 } else {
60 mark_section(
61 &mut line_changes,
62 new_start,
63 new_start as i32,
64 LineChange::RemovedBelow,
65 );
66 }
67 } else {
68 mark_section(&mut line_changes, new_start, new_end, LineChange::Modified);
69 }
71 true
72 }),
73 None,
74 );
76 Some(line_changes)