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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// This file is part of radicle-surf
// <https://github.com/radicle-dev/radicle-surf>
//
// Copyright (C) 2019-2020 The Radicle Team <dev@radicle.xyz>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 or
// later as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use std::convert::TryFrom;

use super::{
    Diff, DiffContent, DiffFile, EofNewLine, FileMode, FileStats, Hunk, Hunks, Line, Modification,
    Stats,
};

pub mod error {
    use std::path::PathBuf;

    use thiserror::Error;

    #[derive(Debug, Error)]
    #[non_exhaustive]
    pub enum Addition {
        #[error(transparent)]
        Git(#[from] git2::Error),
        #[error("the new line number was missing for an added line")]
        MissingNewLineNo,
    }

    #[derive(Debug, Error)]
    #[non_exhaustive]
    pub enum Deletion {
        #[error(transparent)]
        Git(#[from] git2::Error),
        #[error("the new line number was missing for an deleted line")]
        MissingOldLineNo,
    }

    #[derive(Debug, Error)]
    #[non_exhaustive]
    pub enum FileMode {
        #[error("unknown file mode `{0:?}`")]
        Unknown(git2::FileMode),
    }

    #[derive(Debug, Error)]
    #[non_exhaustive]
    pub enum Modification {
        /// A Git `DiffLine` is invalid.
        #[error(
            "invalid `git2::DiffLine` which contains no line numbers for either side of the diff"
        )]
        Invalid,
    }

    #[derive(Debug, Error)]
    #[non_exhaustive]
    pub enum Hunk {
        #[error(transparent)]
        Git(#[from] git2::Error),
        #[error(transparent)]
        Line(#[from] Modification),
    }

    /// A Git diff error.
    #[derive(Debug, Error)]
    #[non_exhaustive]
    pub enum Diff {
        #[error(transparent)]
        Addition(#[from] Addition),
        #[error(transparent)]
        Deletion(#[from] Deletion),
        /// A Git delta type isn't currently handled.
        #[error("git delta type is not handled")]
        DeltaUnhandled(git2::Delta),
        #[error(transparent)]
        Git(#[from] git2::Error),
        #[error(transparent)]
        FileMode(#[from] FileMode),
        #[error(transparent)]
        Hunk(#[from] Hunk),
        #[error(transparent)]
        Line(#[from] Modification),
        /// A patch is unavailable.
        #[error("couldn't retrieve patch for {0}")]
        PatchUnavailable(PathBuf),
        /// A The path of a file isn't available.
        #[error("couldn't retrieve file path")]
        PathUnavailable,
    }
}

impl<'a> TryFrom<git2::DiffFile<'a>> for DiffFile {
    type Error = error::FileMode;

    fn try_from(value: git2::DiffFile) -> Result<Self, Self::Error> {
        Ok(Self {
            mode: value.mode().try_into()?,
            oid: value.id().into(),
        })
    }
}

impl TryFrom<git2::FileMode> for FileMode {
    type Error = error::FileMode;

    fn try_from(value: git2::FileMode) -> Result<Self, Self::Error> {
        match value {
            git2::FileMode::Blob => Ok(Self::Blob),
            git2::FileMode::BlobExecutable => Ok(Self::BlobExecutable),
            git2::FileMode::Commit => Ok(Self::Commit),
            git2::FileMode::Tree => Ok(Self::Tree),
            git2::FileMode::Link => Ok(Self::Link),
            _ => Err(error::FileMode::Unknown(value)),
        }
    }
}

impl From<FileMode> for git2::FileMode {
    fn from(m: FileMode) -> Self {
        match m {
            FileMode::Blob => git2::FileMode::Blob,
            FileMode::BlobExecutable => git2::FileMode::BlobExecutable,
            FileMode::Tree => git2::FileMode::Tree,
            FileMode::Link => git2::FileMode::Link,
            FileMode::Commit => git2::FileMode::Commit,
        }
    }
}

impl TryFrom<git2::Patch<'_>> for DiffContent {
    type Error = error::Hunk;

    fn try_from(patch: git2::Patch) -> Result<Self, Self::Error> {
        let mut hunks = Vec::new();
        let mut old_missing_eof = false;
        let mut new_missing_eof = false;
        let mut additions = 0;
        let mut deletions = 0;

        for h in 0..patch.num_hunks() {
            let (hunk, hunk_lines) = patch.hunk(h)?;
            let header = Line(hunk.header().to_owned());
            let mut lines: Vec<Modification> = Vec::new();

            for l in 0..hunk_lines {
                let line = patch.line_in_hunk(h, l)?;
                match line.origin_value() {
                    git2::DiffLineType::ContextEOFNL => {
                        new_missing_eof = true;
                        old_missing_eof = true;
                        continue;
                    }
                    git2::DiffLineType::Addition => {
                        additions += 1;
                    }
                    git2::DiffLineType::Deletion => {
                        deletions += 1;
                    }
                    git2::DiffLineType::AddEOFNL => {
                        additions += 1;
                        old_missing_eof = true;
                        continue;
                    }
                    git2::DiffLineType::DeleteEOFNL => {
                        deletions += 1;
                        new_missing_eof = true;
                        continue;
                    }
                    _ => {}
                }
                let line = Modification::try_from(line)?;
                lines.push(line);
            }
            hunks.push(Hunk {
                header,
                lines,
                old: hunk.old_start()..hunk.old_start() + hunk.old_lines(),
                new: hunk.new_start()..hunk.new_start() + hunk.new_lines(),
            });
        }
        let eof = match (old_missing_eof, new_missing_eof) {
            (true, true) => EofNewLine::BothMissing,
            (true, false) => EofNewLine::OldMissing,
            (false, true) => EofNewLine::NewMissing,
            (false, false) => EofNewLine::NoneMissing,
        };
        Ok(DiffContent::Plain {
            hunks: Hunks(hunks),
            stats: FileStats {
                additions,
                deletions,
            },
            eof,
        })
    }
}

impl<'a> TryFrom<git2::DiffLine<'a>> for Modification {
    type Error = error::Modification;

    fn try_from(line: git2::DiffLine) -> Result<Self, Self::Error> {
        match (line.old_lineno(), line.new_lineno()) {
            (None, Some(n)) => Ok(Self::addition(line.content().to_owned(), n)),
            (Some(n), None) => Ok(Self::deletion(line.content().to_owned(), n)),
            (Some(l), Some(r)) => Ok(Self::context(line.content().to_owned(), l, r)),
            (None, None) => Err(error::Modification::Invalid),
        }
    }
}

impl From<git2::DiffStats> for Stats {
    fn from(stats: git2::DiffStats) -> Self {
        Self {
            files_changed: stats.files_changed(),
            insertions: stats.insertions(),
            deletions: stats.deletions(),
        }
    }
}

impl<'a> TryFrom<git2::Diff<'a>> for Diff {
    type Error = error::Diff;

    fn try_from(git_diff: git2::Diff) -> Result<Diff, Self::Error> {
        use git2::Delta;

        let mut diff = Diff::new();

        // This allows libgit2 to run the binary detection.
        // Reference: <https://github.com/libgit2/libgit2/issues/6637>
        git_diff.foreach(&mut |_, _| true, None, None, None)?;

        for (idx, delta) in git_diff.deltas().enumerate() {
            match delta.status() {
                Delta::Added => created(&mut diff, &git_diff, idx, &delta)?,
                Delta::Deleted => deleted(&mut diff, &git_diff, idx, &delta)?,
                Delta::Modified => modified(&mut diff, &git_diff, idx, &delta)?,
                Delta::Renamed => renamed(&mut diff, &git_diff, idx, &delta)?,
                Delta::Copied => copied(&mut diff, &git_diff, idx, &delta)?,
                status => {
                    return Err(error::Diff::DeltaUnhandled(status));
                }
            }
        }

        Ok(diff)
    }
}

fn created(
    diff: &mut Diff,
    git_diff: &git2::Diff<'_>,
    idx: usize,
    delta: &git2::DiffDelta<'_>,
) -> Result<(), error::Diff> {
    let diff_file = delta.new_file();
    let is_binary = diff_file.is_binary();
    let path = diff_file
        .path()
        .ok_or(error::Diff::PathUnavailable)?
        .to_path_buf();
    let new = DiffFile::try_from(diff_file)?;

    let patch = git2::Patch::from_diff(git_diff, idx)?;
    if is_binary {
        diff.insert_added(path, DiffContent::Binary, new);
    } else if let Some(patch) = patch {
        diff.insert_added(path, DiffContent::try_from(patch)?, new);
    } else {
        return Err(error::Diff::PatchUnavailable(path));
    }
    Ok(())
}

fn deleted(
    diff: &mut Diff,
    git_diff: &git2::Diff<'_>,
    idx: usize,
    delta: &git2::DiffDelta<'_>,
) -> Result<(), error::Diff> {
    let diff_file = delta.old_file();
    let is_binary = diff_file.is_binary();
    let path = diff_file
        .path()
        .ok_or(error::Diff::PathUnavailable)?
        .to_path_buf();
    let patch = git2::Patch::from_diff(git_diff, idx)?;
    let old = DiffFile::try_from(diff_file)?;

    if is_binary {
        diff.insert_deleted(path, DiffContent::Binary, old);
    } else if let Some(patch) = patch {
        diff.insert_deleted(path, DiffContent::try_from(patch)?, old);
    } else {
        return Err(error::Diff::PatchUnavailable(path));
    }
    Ok(())
}

fn modified(
    diff: &mut Diff,
    git_diff: &git2::Diff<'_>,
    idx: usize,
    delta: &git2::DiffDelta<'_>,
) -> Result<(), error::Diff> {
    let diff_file = delta.new_file();
    let path = diff_file
        .path()
        .ok_or(error::Diff::PathUnavailable)?
        .to_path_buf();
    let patch = git2::Patch::from_diff(git_diff, idx)?;
    let old = DiffFile::try_from(delta.old_file())?;
    let new = DiffFile::try_from(delta.new_file())?;

    if diff_file.is_binary() {
        diff.insert_modified(path, DiffContent::Binary, old, new);
        Ok(())
    } else if let Some(patch) = patch {
        diff.insert_modified(path, DiffContent::try_from(patch)?, old, new);
        Ok(())
    } else {
        Err(error::Diff::PatchUnavailable(path))
    }
}

fn renamed(
    diff: &mut Diff,
    git_diff: &git2::Diff<'_>,
    idx: usize,
    delta: &git2::DiffDelta<'_>,
) -> Result<(), error::Diff> {
    let old_path = delta
        .old_file()
        .path()
        .ok_or(error::Diff::PathUnavailable)?
        .to_path_buf();
    let new_path = delta
        .new_file()
        .path()
        .ok_or(error::Diff::PathUnavailable)?
        .to_path_buf();
    let patch = git2::Patch::from_diff(git_diff, idx)?;
    let old = DiffFile::try_from(delta.old_file())?;
    let new = DiffFile::try_from(delta.new_file())?;

    if delta.new_file().is_binary() {
        diff.insert_moved(old_path, new_path, old, new, DiffContent::Binary);
    } else if let Some(patch) = patch {
        diff.insert_moved(old_path, new_path, old, new, DiffContent::try_from(patch)?);
    } else {
        diff.insert_moved(old_path, new_path, old, new, DiffContent::Empty);
    }
    Ok(())
}

fn copied(
    diff: &mut Diff,
    git_diff: &git2::Diff<'_>,
    idx: usize,
    delta: &git2::DiffDelta<'_>,
) -> Result<(), error::Diff> {
    let old_path = delta
        .old_file()
        .path()
        .ok_or(error::Diff::PathUnavailable)?
        .to_path_buf();
    let new_path = delta
        .new_file()
        .path()
        .ok_or(error::Diff::PathUnavailable)?
        .to_path_buf();
    let patch = git2::Patch::from_diff(git_diff, idx)?;
    let old = DiffFile::try_from(delta.old_file())?;
    let new = DiffFile::try_from(delta.new_file())?;

    if delta.new_file().is_binary() {
        diff.insert_copied(old_path, new_path, old, new, DiffContent::Binary);
    } else if let Some(patch) = patch {
        diff.insert_copied(old_path, new_path, old, new, DiffContent::try_from(patch)?);
    } else {
        diff.insert_copied(old_path, new_path, old, new, DiffContent::Empty);
    }
    Ok(())
}