index : gitrs
A lightweight web interface for browsing Git repositories, implemented in Rust
about summary refs log tree commit diff
gitrs / src / git / diff.rs
-rw-r--r-- blob d246b42aae199bfd0262a9dea3f5314ef41bf829 16521 bytes (plain)
1
use std::fmt::{self, Display, Write};
2
3
use gix::{
4
    bstr::{BStr, ByteSlice},
5
    diff::blob::platform::prepare_diff::Operation,
6
};
7
8
use crate::{git::tree::format_mode, prelude::*};
9
10
#[derive(Default)]
11
pub struct Diff {
12
    pub file_diffs: Vec<FileDiff>,
13
    pub output: String,
14
    pub stats: String,
15
}
16
17
#[derive(Default)]
18
pub enum FileState {
19
    Added,
20
    Removed,
21
    #[default]
22
    Changed,
23
}
24
25
impl Display for FileState {
26
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27
        match self {
28
            Self::Added => write!(f, "diffstat-added"),
29
            Self::Removed => write!(f, "diffstat-removed"),
30
            Self::Changed => write!(f, "diffstat-changed"),
31
        }
32
    }
33
}
34
35
#[derive(Default)]
36
pub struct FileDiff {
37
    pub path: String,
38
    pub state: FileState,
39
    pub mode: String,
40
    pub insertions: usize,
41
    pub deletions: usize,
42
    pub total: usize,
43
    pub insertions_percentage: f64,
44
    pub deletions_percentage: f64,
45
    pub total_percentage: f64,
46
}
47
48
#[derive(PartialEq)]
49
pub enum DiffFormat {
50
    Plain,
51
    Patch,
52
}
53
54
impl Diff {
55
    fn finalize(&mut self, is_patch: bool) -> fmt::Result {
56
        let files_changed = self.file_diffs.len();
57
        let insertions: usize = self.file_diffs.iter().map(|f| f.insertions).sum();
58
        let deletions: usize = self.file_diffs.iter().map(|f| f.deletions).sum();
59
        let total = deletions.saturating_add(insertions);
60
61
        if is_patch {
62
            self.write_patch_stat_bars(insertions, total)?;
63
        }
64
        self.write_summary_line(files_changed, insertions, deletions)?;
65
        self.compute_percentages(total);
66
        Ok(())
67
    }
68
69
    fn write_patch_stat_bars(
70
        &mut self,
71
        total_insertions: usize,
72
        total_changes: usize,
73
    ) -> fmt::Result {
74
        const WIDTH: usize = 80;
75
76
        let (max_name_len, max_change_len) =
77
            self.file_diffs
78
                .iter()
79
                .fold((0, 0), |(max_name, max_change), f| {
80
                    let digits = ((f.insertions + f.deletions + 1).ilog10() + 1) as usize;
81
                    (max_name.max(f.path.len()), max_change.max(digits))
82
                });
83
84
        for f in &self.file_diffs {
85
            let local_changes = f.insertions + f.deletions;
86
            let width = WIDTH.min(local_changes);
87
88
            let add_w = (width * f.insertions) / total_changes;
89
            let del_w = (width * f.deletions) / total_changes;
90
            let rem_w = width - (add_w + del_w);
91
92
            let plus_str = "+".repeat(add_w + rem_w.min(total_insertions));
93
            let minus_str = "-".repeat(del_w + (rem_w - rem_w.min(total_insertions)));
94
95
            writeln!(
96
                self.stats,
97
                " {:max_name_len$} | {:max_change_len$} {plus_str}{minus_str}",
98
                f.path, local_changes
99
            )?;
100
        }
101
        Ok(())
102
    }
103
104
    fn write_summary_line(
105
        &mut self,
106
        files_changed: usize,
107
        insertions: usize,
108
        deletions: usize,
109
    ) -> fmt::Result {
110
        for (i, (singular, plural, amount)) in [
111
            ("file changed", "files changed", files_changed),
112
            ("insertion(+)", "insertions(+)", insertions),
113
            ("deletion(-)", "deletions(-)", deletions),
114
        ]
115
        .into_iter()
116
        .enumerate()
117
        {
118
            if amount == 0 {
119
                continue;
120
            }
121
            let prefix = if i == 0 { "" } else { "," };
122
            let desc = if amount == 1 { singular } else { plural };
123
            write!(self.stats, "{prefix} {amount} {desc}")?;
124
        }
125
        writeln!(self.stats)
126
    }
127
128
    fn compute_percentages(&mut self, total_changes: usize) {
129
        for f in &mut self.file_diffs {
130
            f.total_percentage = if total_changes == 0 {
131
                0.0
132
            } else if total_changes < 100 {
133
                total_changes as f64
134
            } else {
135
                (f.total as f64) * 100.0 / (total_changes as f64)
136
            };
137
138
            if f.total > 0 {
139
                f.insertions_percentage = (f.insertions as f64) * 100.0 / (f.total as f64);
140
                f.deletions_percentage = (f.deletions as f64) * 100.0 / (f.total as f64);
141
            }
142
        }
143
    }
144
}
145
146
impl<'repo> Commit<'repo> {
147
    pub fn diff(
148
        &self,
149
        repo: &Repository,
150
        limit_file: Option<&str>,
151
        format: DiffFormat,
152
    ) -> Result<Diff, Error> {
153
        match format {
154
            DiffFormat::Plain => self.diff_with(repo, limit_file, PlainDiffFormatter),
155
            DiffFormat::Patch => self.diff_with(repo, limit_file, PatchDiffFormatter),
156
        }
157
    }
158
159
    fn diff_with<F: DiffFormatter>(
160
        &self,
161
        repo: &Repository,
162
        limit_file: Option<&str>,
163
        formatter: F,
164
    ) -> Result<Diff, Error> {
165
        let mut diff = Diff::default();
166
        let gix_repo = repo.gix();
167
168
        let current_tree = self.gix.tree()?;
169
        let first_parent = self.gix.parent_ids().next();
170
        let parent_tree = match first_parent {
171
            Some(id) => id.object()?.into_commit().tree()?,
172
            None => gix_repo.empty_tree(),
173
        };
174
        let parent_id = first_parent.map(|id| id.to_string());
175
        let commit_id = self.gix.id.to_string();
176
177
        let mut tree_diff_cache = gix_repo.diff_resource_cache_for_tree_diff()?;
178
        let mut blob_diff_cache = gix_repo.diff_resource_cache_for_tree_diff()?;
179
180
        let mut changes = parent_tree.changes()?;
181
        changes.options(|opts| {
182
            opts.track_path().track_rewrites(None);
183
        });
184
        changes.for_each_to_obtain_tree_with_cache(
185
            &current_tree,
186
            &mut tree_diff_cache,
187
            |change| {
188
                DiffBuilder {
189
                    output: &mut diff.output,
190
                    resource_cache: &mut blob_diff_cache,
191
                    diffs: &mut diff.file_diffs,
192
                    formatter: &formatter,
193
                }
194
                .handle(change, repo, parent_id.as_deref(), &commit_id, limit_file)
195
            },
196
        )?;
197
198
        diff.finalize(formatter.format() == DiffFormat::Patch)?;
199
        Ok(diff)
200
    }
201
}
202
203
trait DiffFormatter {
204
    fn file_header(&self, output: &mut String, data: fmt::Arguments<'_>);
205
    fn write(&self, output: &mut String, class: &str, data: &str);
206
    fn binary(&self, output: &mut String, left: &str, right: &str);
207
    fn path_line(
208
        &self,
209
        prefix: char,
210
        is_null: bool,
211
        state: &FileState,
212
        repo_name: &str,
213
        rela_path: &BStr,
214
        rev_id: &str,
215
    ) -> String;
216
    fn format(&self) -> DiffFormat;
217
}
218
219
struct DiffBuilder<'a, F> {
220
    output: &'a mut String,
221
    resource_cache: &'a mut gix::diff::blob::Platform,
222
    diffs: &'a mut Vec<FileDiff>,
223
    formatter: &'a F,
224
}
225
226
impl<F: DiffFormatter> DiffBuilder<'_, F> {
227
    fn handle(
228
        &mut self,
229
        change: gix::object::tree::diff::Change<'_, '_, '_>,
230
        repo: &Repository,
231
        parent_id: Option<&str>,
232
        commit_id: &str,
233
        limit_file: Option<&str>,
234
    ) -> anyhow::Result<gix::object::tree::diff::Action> {
235
        if !change.entry_mode().is_blob_or_symlink() {
236
            return Ok(gix::object::tree::diff::Action::Continue(()));
237
        }
238
239
        let path = change.location().to_string();
240
        if let Some(limit_file) = limit_file
241
            && !limit_file.is_empty()
242
            && limit_file != path
243
        {
244
            return Ok(gix::object::tree::diff::Action::Continue(()));
245
        }
246
247
        let mut diff = FileDiff {
248
            path,
249
            ..Default::default()
250
        };
251
        let change = change.diff(self.resource_cache)?;
252
        let prep = change.resource_cache.prepare_diff()?;
253
254
        self.formatter.file_header(
255
            self.output,
256
            format_args!(
257
                "diff --git a/{} b/{}",
258
                prep.old.rela_path, prep.new.rela_path
259
            ),
260
        );
261
262
        if prep.old.id.is_null() {
263
            self.formatter.file_header(
264
                self.output,
265
                format_args!("new file mode {}", prep.new.mode.as_octal_str()),
266
            );
267
            diff.state = FileState::Added;
268
        } else if prep.new.id.is_null() {
269
            self.formatter.file_header(
270
                self.output,
271
                format_args!("deleted file mode {}", prep.old.mode.as_octal_str()),
272
            );
273
            diff.state = FileState::Removed;
274
        } else if prep.new.mode != prep.old.mode {
275
            self.formatter.file_header(
276
                self.output,
277
                format_args!("old mode {}", prep.old.mode.as_octal_str()),
278
            );
279
            self.formatter.file_header(
280
                self.output,
281
                format_args!("new mode {}", prep.new.mode.as_octal_str()),
282
            );
283
        }
284
285
        let mode_source = if matches!(diff.state, FileState::Removed) {
286
            prep.old.mode
287
        } else {
288
            prep.new.mode
289
        };
290
        let raw_mode = u32::from_str_radix(mode_source.as_octal_str().to_str()?, 8)?;
291
        diff.mode = format_mode(raw_mode);
292
293
        let (index_suffix_sep, index_suffix) = if prep.old.mode == prep.new.mode {
294
            (" ", prep.new.mode.as_octal_str())
295
        } else {
296
            ("", BStr::new(&[]))
297
        };
298
299
        let old_path = self.formatter.path_line(
300
            'a',
301
            prep.old.id.is_null(),
302
            &diff.state,
303
            &repo.name,
304
            prep.old.rela_path,
305
            parent_id.unwrap_or_default(),
306
        );
307
        let new_path = self.formatter.path_line(
308
            'b',
309
            prep.new.id.is_null(),
310
            &diff.state,
311
            &repo.name,
312
            prep.new.rela_path,
313
            commit_id,
314
        );
315
316
        match prep.operation {
317
            Operation::InternalDiff { algorithm } => {
318
                self.formatter.file_header(
319
                    self.output,
320
                    format_args!(
321
                        "index {}..{}{index_suffix_sep}{index_suffix}",
322
                        prep.old.id.to_hex_with_len(7),
323
                        prep.new.id.to_hex_with_len(7)
324
                    ),
325
                );
326
                self.formatter
327
                    .file_header(self.output, format_args!("--- {old_path}"));
328
                self.formatter
329
                    .file_header(self.output, format_args!("+++ {new_path}"));
330
331
                let old_source = gix::diff::blob::sources::lines(str::from_utf8(
332
                    prep.old.data.as_slice().unwrap_or_default(),
333
                )?);
334
                let new_source = gix::diff::blob::sources::lines(str::from_utf8(
335
                    prep.new.data.as_slice().unwrap_or_default(),
336
                )?);
337
                let input = gix::diff::blob::InternedInput::new(old_source, new_source);
338
                let output = gix::diff::blob::Diff::compute(algorithm, &input);
339
340
                diff.deletions += output.count_removals() as usize;
341
                diff.insertions += output.count_additions() as usize;
342
                diff.total = diff.deletions.saturating_add(diff.insertions);
343
344
                Self::write_hunks(self.formatter, self.output, &input, &output);
345
            }
346
            Operation::ExternalCommand { .. } => {}
347
            Operation::SourceOrDestinationIsBinary => {
348
                self.formatter.file_header(
349
                    self.output,
350
                    format_args!(
351
                        "index {}..{}{index_suffix_sep}{index_suffix}",
352
                        prep.old.id, prep.new.id,
353
                    ),
354
                );
355
                self.formatter.binary(self.output, &old_path, &new_path);
356
            }
357
        }
358
359
        self.diffs.push(diff);
360
        self.resource_cache.clear_resource_cache_keep_allocation();
361
        Ok(gix::object::tree::diff::Action::Continue(()))
362
    }
363
364
    fn write_hunks(
365
        formatter: &F,
366
        output: &mut String,
367
        input: &gix::diff::blob::InternedInput<&str>,
368
        diff: &gix::diff::blob::Diff,
369
    ) {
370
        const CONTEXT_LINES: u32 = 3;
371
372
        let hunks: Vec<_> = diff.hunks().collect();
373
        let mut i = 0;
374
375
        while i < hunks.len() {
376
            let start = i;
377
            let mut end = i + 1;
378
            while end < hunks.len()
379
                && hunks[end]
380
                    .before
381
                    .start
382
                    .saturating_sub(hunks[end - 1].before.end)
383
                    <= CONTEXT_LINES * 2
384
            {
385
                end += 1;
386
            }
387
            i = end;
388
389
            let first = &hunks[start];
390
            let last = &hunks[end - 1];
391
392
            let before_start = first.before.start.saturating_sub(CONTEXT_LINES);
393
            let before_end = (last.before.end + CONTEXT_LINES).min(input.before.len() as u32);
394
            let after_start = first.after.start.saturating_sub(CONTEXT_LINES);
395
            let after_end = (last.after.end + CONTEXT_LINES).min(input.after.len() as u32);
396
397
            formatter.write(
398
                output,
399
                "hunk",
400
                &format!(
401
                    "@@ -{},{} +{},{} @@\n",
402
                    before_start + 1,
403
                    before_end - before_start,
404
                    after_start + 1,
405
                    after_end - after_start,
406
                ),
407
            );
408
409
            let mut before_pos = before_start;
410
411
            for hunk in &hunks[start..end] {
412
                while before_pos < hunk.before.start {
413
                    let line = input.interner[input.before[before_pos as usize]];
414
                    formatter.write(output, "context", line);
415
                    before_pos += 1;
416
                }
417
418
                for pos in hunk.before.clone() {
419
                    let line = input.interner[input.before[pos as usize]];
420
                    formatter.write(output, "deletion", line);
421
                }
422
                before_pos = hunk.before.end;
423
424
                for pos in hunk.after.clone() {
425
                    let line = input.interner[input.after[pos as usize]];
426
                    formatter.write(output, "addition", line);
427
                }
428
            }
429
430
            while before_pos < before_end {
431
                let line = input.interner[input.before[before_pos as usize]];
432
                formatter.write(output, "context", line);
433
                before_pos += 1;
434
            }
435
        }
436
    }
437
}
438
439
struct PlainDiffFormatter;
440
441
impl DiffFormatter for PlainDiffFormatter {
442
    fn file_header(&self, output: &mut String, data: fmt::Arguments<'_>) {
443
        write!(output, r#"<span class="diff-file-header">{data}</span>"#).unwrap();
444
        output.push('\n');
445
    }
446
447
    fn write(&self, output: &mut String, class: &str, data: &str) {
448
        write!(output, r#"<span class="diff-{class}">"#).unwrap();
449
        v_htmlescape::b_escape(data.as_bytes(), output);
450
        output.push_str("</span>");
451
    }
452
453
    fn binary(&self, output: &mut String, left: &str, right: &str) {
454
        writeln!(output, "Binary files {left} and {right} differ").unwrap();
455
    }
456
457
    fn path_line(
458
        &self,
459
        prefix: char,
460
        is_null: bool,
461
        state: &FileState,
462
        repo_name: &str,
463
        rela_path: &BStr,
464
        rev_id: &str,
465
    ) -> String {
466
        if is_null {
467
            "/dev/null".to_string()
468
        } else {
469
            format!(
470
                "{prefix}/<a class='{state}' href='/{repo_name}/diff/{rela_path}?id={rev_id}'>{rela_path}</a>"
471
            )
472
        }
473
    }
474
475
    fn format(&self) -> DiffFormat {
476
        DiffFormat::Plain
477
    }
478
}
479
480
struct PatchDiffFormatter;
481
482
impl DiffFormatter for PatchDiffFormatter {
483
    fn file_header(&self, output: &mut String, data: fmt::Arguments<'_>) {
484
        writeln!(output, "{data}").unwrap();
485
    }
486
487
    fn write(&self, output: &mut String, class: &str, data: &str) {
488
        let prefix = match class {
489
            "addition" => "+",
490
            "deletion" => "-",
491
            "context" => " ",
492
            _ => "",
493
        };
494
        output.push_str(prefix);
495
        output.push_str(data);
496
    }
497
498
    fn binary(&self, output: &mut String, left: &str, right: &str) {
499
        writeln!(output, "Binary files {left} and {right} differ").unwrap();
500
    }
501
502
    fn path_line(
503
        &self,
504
        prefix: char,
505
        is_null: bool,
506
        _state: &FileState,
507
        _repo_name: &str,
508
        rela_path: &BStr,
509
        _rev_id: &str,
510
    ) -> String {
511
        if is_null {
512
            "/dev/null".to_string()
513
        } else {
514
            format!("{prefix}/{rela_path}")
515
        }
516
    }
517
518
    fn format(&self) -> DiffFormat {
519
        DiffFormat::Patch
520
    }
521
}