1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
use std::borrow::Cow;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use eyre::Context;
use git_record::{FileState, Section, SectionChangedLine};
use itertools::Itertools;

use super::{MaybeZeroOid, Repo};

/// A diff between two trees/commits.
pub struct Diff<'repo> {
    pub(super) inner: git2::Diff<'repo>,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct GitHunk {
    old_start: usize,
    old_lines: usize,
    new_start: usize,
    new_lines: usize,
}

/// Calculate the diff between the index and the working copy.
pub fn process_diff_for_record(
    repo: &Repo,
    diff: &Diff,
) -> eyre::Result<Vec<(PathBuf, FileState<'static>)>> {
    let Diff { inner: diff } = diff;

    #[derive(Clone, Debug)]
    enum DeltaFileContent {
        Hunks(Vec<GitHunk>),
        Binary,
    }

    #[derive(Clone, Debug)]
    struct Delta {
        old_oid: git2::Oid,
        old_file_mode: git2::FileMode,
        new_oid: git2::Oid,
        new_file_mode: git2::FileMode,
        content: DeltaFileContent,
    }
    let deltas: Arc<Mutex<HashMap<PathBuf, Delta>>> = Default::default();
    diff.foreach(
        &mut |delta, _| {
            let mut deltas = deltas.lock().unwrap();
            let old_file = delta.old_file().path().unwrap().into();
            let new_file = delta.new_file().path().unwrap().into();
            let delta = Delta {
                old_oid: delta.old_file().id(),
                old_file_mode: delta.old_file().mode(),
                new_oid: delta.new_file().id(),
                new_file_mode: delta.new_file().mode(),
                content: DeltaFileContent::Hunks(Default::default()),
            };
            deltas.insert(old_file, delta.clone());
            deltas.insert(new_file, delta);
            true
        },
        Some(&mut |delta, _| {
            let mut deltas = deltas.lock().unwrap();

            let old_file = delta.old_file().path().unwrap().into();
            let new_file = delta.new_file().path().unwrap().into();
            let delta = Delta {
                old_oid: delta.old_file().id(),
                old_file_mode: delta.old_file().mode(),
                new_oid: delta.new_file().id(),
                new_file_mode: delta.new_file().mode(),
                content: DeltaFileContent::Binary,
            };
            deltas.insert(old_file, delta.clone());
            deltas.insert(new_file, delta);
            true
        }),
        Some(&mut |delta, hunk| {
            let path = delta.new_file().path().unwrap();
            let mut deltas = deltas.lock().unwrap();
            match &mut deltas.get_mut(path).unwrap().content {
                DeltaFileContent::Hunks(hunks) => {
                    hunks.push(GitHunk {
                        old_start: hunk.old_start().try_into().unwrap(),
                        old_lines: hunk.old_lines().try_into().unwrap(),
                        new_start: hunk.new_start().try_into().unwrap(),
                        new_lines: hunk.new_lines().try_into().unwrap(),
                    });
                }
                DeltaFileContent::Binary => {
                    panic!(
                        "File {:?} got a hunk callback, but it was a binary file",
                        path
                    )
                }
            }
            true
        }),
        None,
    )
    .wrap_err("Iterating over diff deltas")?;

    let deltas = std::mem::take(&mut *deltas.lock().unwrap());
    let mut result = Vec::new();
    for (path, delta) in deltas {
        let Delta {
            old_oid,
            old_file_mode,
            new_oid,
            new_file_mode,
            content,
        } = delta;

        if new_oid.is_zero() {
            result.push((path, FileState::absent()));
            continue;
        }

        let hunks = match content {
            DeltaFileContent::Binary => {
                result.push((path, FileState::binary()));
                continue;
            }
            DeltaFileContent::Hunks(mut hunks) => {
                hunks.sort_by_key(|hunk| (hunk.old_start, hunk.old_lines));
                hunks
            }
        };
        let get_lines_from_blob = |oid| -> eyre::Result<Option<Vec<String>>> {
            let oid = MaybeZeroOid::from(oid);
            match oid {
                MaybeZeroOid::Zero => Ok(Default::default()),
                MaybeZeroOid::NonZero(oid) => {
                    let contents = repo.find_blob_or_fail(oid)?.get_content().to_vec();
                    let contents = match String::from_utf8(contents) {
                        Ok(contents) => contents,
                        Err(_) => {
                            return Ok(None);
                        }
                    };
                    let lines: Vec<String> = contents
                        .split_inclusive('\n')
                        .map(|line| line.to_owned())
                        .collect();
                    Ok(Some(lines))
                }
            }
        };

        // FIXME: should we rely on the caller to add the file contents to
        // the ODB?
        match repo.inner.blob_path(&path) {
            Ok(_) => {}
            Err(err) if err.code() == git2::ErrorCode::NotFound => {}
            Err(err) => return Err(err.into()),
        }
        let before_lines = match get_lines_from_blob(old_oid)? {
            Some(lines) => lines,
            None => {
                result.push((path, FileState::binary()));
                continue;
            }
        };
        let after_lines = match get_lines_from_blob(new_oid)? {
            Some(lines) => lines,
            None => {
                result.push((path, FileState::binary()));
                continue;
            }
        };

        let mut unchanged_hunk_line_idx = 0;
        let mut file_hunks = Vec::new();
        for hunk in hunks {
            let GitHunk {
                old_start,
                old_lines,
                new_start,
                new_lines,
            } = hunk;

            // The line numbers are one-indexed.
            let (old_start, old_is_empty) = if old_start == 0 && old_lines == 0 {
                (0, true)
            } else {
                assert!(old_start > 0);
                (old_start - 1, false)
            };
            let new_start = if new_start == 0 && new_lines == 0 {
                0
            } else {
                assert!(new_start > 0);
                new_start - 1
            };

            // If we're starting a new hunk, first paste in any unchanged
            // lines since the last hunk (from the old version of the file).
            if unchanged_hunk_line_idx <= old_start {
                let end = if old_lines == 0 && !old_is_empty {
                    // Insertions are indicated with `old_lines == 0`, but in
                    // those cases, the inserted line is *after* the provided
                    // line number.
                    old_start + 1
                } else {
                    old_start
                };
                file_hunks.push(Section::Unchanged {
                    contents: before_lines[unchanged_hunk_line_idx..end]
                        .iter()
                        .cloned()
                        .map(Cow::Owned)
                        .collect_vec(),
                });
                unchanged_hunk_line_idx = end + old_lines;
            }

            let before_idx_start = old_start;
            let before_idx_end = before_idx_start + old_lines;
            assert!(
                before_idx_end <= before_lines.len(),
                "before_idx_end {end} was not in range [0, {len}): {hunk:?}, path: {path:?}; lines {start}-... are: {lines:?}",
                start = before_idx_start,
                end = before_idx_end,
                len = before_lines.len(),
                hunk = hunk,
                path = path,
                lines = &before_lines[before_idx_start..],
            );
            let after_idx_start = new_start;
            let after_idx_end = after_idx_start + new_lines;
            assert!(
                after_idx_end <= after_lines.len(),
                "after_idx_end {end} was not in range [0, {len}): {hunk:?}, path: {path:?}; lines {start}-... are: {lines:?}",
                start = after_idx_start,
                end = after_idx_end,
                len = after_lines.len(),
                hunk = hunk,
                path = path,
                lines  = &after_lines[after_idx_start..],
            );
            file_hunks.push(Section::Changed {
                before: before_lines[before_idx_start..before_idx_end]
                    .iter()
                    .cloned()
                    .map(|line| SectionChangedLine {
                        is_selected: false,
                        line: Cow::Owned(line),
                    })
                    .collect(),
                after: after_lines[after_idx_start..after_idx_end]
                    .iter()
                    .cloned()
                    .map(|line| SectionChangedLine {
                        is_selected: false,
                        line: Cow::Owned(line),
                    })
                    .collect(),
            });
        }

        if unchanged_hunk_line_idx < before_lines.len() {
            file_hunks.push(Section::Unchanged {
                contents: before_lines[unchanged_hunk_line_idx..]
                    .iter()
                    .cloned()
                    .map(Cow::Owned)
                    .collect(),
            });
        }

        let old_file_mode: usize = u32::from(old_file_mode).try_into().unwrap();
        let new_file_mode: usize = u32::from(new_file_mode).try_into().unwrap();
        let file_mode_section = if old_file_mode != new_file_mode {
            vec![Section::FileMode {
                is_selected: false,
                before: old_file_mode,
                after: new_file_mode,
            }]
        } else {
            vec![]
        };
        result.push((
            path,
            FileState {
                file_mode: Some(old_file_mode),
                sections: [file_mode_section, file_hunks].concat().to_vec(),
            },
        ));
    }
    Ok(result)
}