on v0.21.0 help sign in
bat/src/diff.rs
83 lines 2.5 kB history raw
1#![cfg(feature = "git")]
3use std::collections::HashMap;
4use std::fs;
5use std::path::Path;
7use git2::{DiffOptions, IntoCString, Repository};
9#[derive(Copy, Clone, Debug)]
10pub enum LineChange {
11 Added,
12 RemovedAbove,
13 RemovedBelow,
14 Modified,
17pub type LineChanges = HashMap<u32, LineChange>;
19pub fn get_git_diff(filename: &Path) -> Option<LineChanges> {
20 let repo = Repository::discover(&filename).ok()?;
22 let repo_path_absolute = fs::canonicalize(repo.workdir()?).ok()?;
24 let filepath_absolute = fs::canonicalize(&filename).ok()?;
25 let filepath_relative_to_repo = filepath_absolute.strip_prefix(&repo_path_absolute).ok()?;
27 let mut diff_options = DiffOptions::new();
28 let pathspec = filepath_relative_to_repo.into_c_string().ok()?;
29 diff_options.pathspec(pathspec);
30 diff_options.context_lines(0);
32 let diff = repo
33 .diff_index_to_workdir(None, Some(&mut diff_options))
34 .ok()?;
36 let mut line_changes: LineChanges = HashMap::new();
38 let mark_section =
39 |line_changes: &mut LineChanges, start: u32, end: i32, change: LineChange| {
40 for line in start..=end as u32 {
41 line_changes.insert(line, change);
42 }
43 };
45 let _ = diff.foreach(
46 &mut |_, _| true,
47 None,
48 Some(&mut |delta, hunk| {
49 let path = delta.new_file().path().unwrap_or_else(|| Path::new(""));
51 if filepath_relative_to_repo != path {
52 return false;
53 }
55 let old_lines = hunk.old_lines();
56 let new_start = hunk.new_start();
57 let new_lines = hunk.new_lines();
58 let new_end = (new_start + new_lines) as i32 - 1;
60 if old_lines == 0 && new_lines > 0 {
61 mark_section(&mut line_changes, new_start, new_end, LineChange::Added);
62 } else if new_lines == 0 && old_lines > 0 {
63 if new_start == 0 {
64 mark_section(&mut line_changes, 1, 1, LineChange::RemovedAbove);
65 } else {
66 mark_section(
67 &mut line_changes,
68 new_start,
69 new_start as i32,
70 LineChange::RemovedBelow,
71 );
72 }
73 } else {
74 mark_section(&mut line_changes, new_start, new_end, LineChange::Modified);
75 }
77 true
78 }),
79 None,
80 );
82 Some(line_changes)