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