on v0.7.1 help sign in
bat/src/diff.rs
80 lines 2.5 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()?;
19 let repo_path_absolute = fs::canonicalize(repo.workdir()?).ok()?;
21 let filepath_absolute = fs::canonicalize(&filename).ok()?;
22 let filepath_relative_to_repo = filepath_absolute.strip_prefix(&repo_path_absolute).ok()?;
24 let mut diff_options = DiffOptions::new();
25 let pathspec = filepath_relative_to_repo.into_c_string().ok()?;
26 diff_options.pathspec(pathspec);
27 diff_options.context_lines(0);
29 let diff = repo
30 .diff_index_to_workdir(None, Some(&mut diff_options))
31 .ok()?;
33 let mut line_changes: LineChanges = HashMap::new();
35 let mark_section =
36 |line_changes: &mut LineChanges, start: u32, end: i32, change: LineChange| {
37 for line in start..(end + 1) as u32 {
38 line_changes.insert(line, change);
39 }
40 };
42 let _ = diff.foreach(
43 &mut |_, _| true,
44 None,
45 Some(&mut |delta, hunk| {
46 let path = delta.new_file().path().unwrap_or_else(|| Path::new(""));
48 if filepath_relative_to_repo != path {
49 return false;
50 }
52 let old_lines = hunk.old_lines();
53 let new_start = hunk.new_start();
54 let new_lines = hunk.new_lines();
55 let new_end = (new_start + new_lines) as i32 - 1;
57 if old_lines == 0 && new_lines > 0 {
58 mark_section(&mut line_changes, new_start, new_end, LineChange::Added);
59 } else if new_lines == 0 && old_lines > 0 {
60 if new_start == 0 {
61 mark_section(&mut line_changes, 1, 1, LineChange::RemovedAbove);
62 } else {
63 mark_section(
64 &mut line_changes,
65 new_start,
66 new_start as i32,
67 LineChange::RemovedBelow,
68 );
69 }
70 } else {
71 mark_section(&mut line_changes, new_start, new_end, LineChange::Modified);
72 }
74 true
75 }),
76 None,
77 );
79 Some(line_changes)