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 a4b5b7d622bd79daa79132c88de27baf378dac37 19235 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::prelude::*;
9
10
#[derive(Default)]
11
pub struct Diff {
12
    pub file_diffs: Vec<FileDiff>,
13
    pub output: String,
14
    pub stats: String,
15
    pub files_changed: usize,
16
    pub insertions: usize,
17
    pub deletions: usize,
18
    pub total: usize,
19
}
20
21
#[derive(Default)]
22
pub enum FileState {
23
    Added,
24
    Removed,
25
    #[default]
26
    Changed,
27
}
28
29
impl Display for FileState {
30
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31
        match self {
32
            Self::Added => write!(f, "diffstat-added"),
33
            Self::Removed => write!(f, "diffstat-removed"),
34
            Self::Changed => write!(f, "diffstat-changed"),
35
        }
36
    }
37
}
38
39
#[derive(Default)]
40
pub struct FileDiff {
41
    pub path: String,
42
    pub state: FileState,
43
    pub mode: String,
44
    pub insertions: usize,
45
    pub deletions: usize,
46
    pub total: usize,
47
    pub insertions_percentage: f64,
48
    pub deletions_percentage: f64,
49
    pub total_percentage: f64,
50
}
51
52
#[derive(PartialEq)]
53
pub enum DiffFormat {
54
    Plain,
55
    Patch,
56
}
57
58
impl<'repo> Commit<'repo> {
59
    pub fn diff(
60
        &self,
61
        repo: &Repository,
62
        limit_file: Option<&str>,
63
        format: DiffFormat,
64
    ) -> Result<Diff, Error> {
65
        match format {
66
            DiffFormat::Plain => self.diff_with(repo, limit_file, PlainDiffFormatter),
67
            DiffFormat::Patch => self.diff_with(repo, limit_file, PatchDiffFormatter),
68
        }
69
    }
70
71
    /// Computes the diff between this commit and its first parent commit (or an empty tree if this is the initial commit).
72
    fn diff_with<F: DiffFormatter>(
73
        &self,
74
        repo: &Repository,
75
        limit_file: Option<&str>,
76
        formatter: F,
77
    ) -> Result<Diff, Error> {
78
        const WIDTH: usize = 80;
79
        let mut diff = Diff::default();
80
        let gix_repo = repo.gix();
81
82
        // Phase 1: Get this commit's root directory Tree and its first parent's root directory Tree.
83
        // If the commit has no parents (the very first commit in the repo), compare against an empty Tree.
84
        let current_tree = self.gix.tree()?;
85
        let first_parent = self.gix.parent_ids().next();
86
        let parent_tree = match first_parent {
87
            Some(id) => id.object()?.into_commit().tree()?,
88
            None => gix_repo.empty_tree(),
89
        };
90
        let parent_id = first_parent.map(|id| id.to_string());
91
        let commit_id = self.gix.id.to_string();
92
93
        // `tree_diff_cache` is held by the tree-walker while iterating directory changes;
94
        // `blob_diff_cache` is used inside the callback to diff individual file contents (Blobs).
95
        let mut tree_diff_cache = gix_repo.diff_resource_cache_for_tree_diff()?;
96
        let mut blob_diff_cache = gix_repo.diff_resource_cache_for_tree_diff()?;
97
98
        let mut changes = parent_tree.changes()?;
99
        changes.options(|opts| {
100
            opts.track_path().track_rewrites(None);
101
        });
102
        changes.for_each_to_obtain_tree_with_cache(
103
            &current_tree,
104
            &mut tree_diff_cache,
105
            |change| {
106
                DiffBuilder {
107
                    output: &mut diff.output,
108
                    resource_cache: &mut blob_diff_cache,
109
                    diffs: &mut diff.file_diffs,
110
                    formatter: &formatter,
111
                }
112
                .handle(change, repo, parent_id.as_deref(), &commit_id, limit_file)
113
            },
114
        )?;
115
116
        let files_changed = diff.file_diffs.len();
117
        let insertions: usize = diff.file_diffs.iter().map(|f| f.insertions).sum();
118
        let deletions: usize = diff.file_diffs.iter().map(|f| f.deletions).sum();
119
        diff.files_changed = files_changed;
120
        diff.insertions = insertions;
121
        diff.deletions = deletions;
122
        diff.total = diff.deletions.saturating_add(diff.insertions);
123
124
        if formatter.format() == DiffFormat::Patch {
125
            let (max_file_name_length, max_change_length) = diff.file_diffs.iter().fold(
126
                (0, 0),
127
                |(max_file_name_length, max_change_length), stats| {
128
                    (
129
                        max_file_name_length.max(stats.path.len()),
130
                        max_change_length
131
                            .max(((stats.insertions + stats.deletions + 1).ilog10() + 1) as usize),
132
                    )
133
                },
134
            );
135
136
            for file_diff in &diff.file_diffs {
137
                let local_changes = file_diff.insertions + file_diff.deletions;
138
                let width = WIDTH.min(local_changes);
139
140
                let addition_width = (width * file_diff.insertions) / diff.total;
141
                let deletion_width = (width * file_diff.deletions) / diff.total;
142
143
                // Handle edge case where total width is less than total changes
144
                let remaining_width = width - (addition_width + deletion_width);
145
                let adjusted_addition_width = addition_width + remaining_width.min(diff.insertions);
146
                let adjusted_deletion_width =
147
                    deletion_width + (remaining_width - remaining_width.min(diff.insertions));
148
149
                // Generate the string representation
150
                let plus_str = "+".repeat(adjusted_addition_width);
151
                let minus_str = "-".repeat(adjusted_deletion_width);
152
153
                let file = file_diff.path.as_str();
154
                writeln!(diff.stats, " {file:max_file_name_length$} | {local_changes:max_change_length$} {plus_str}{minus_str}").unwrap();
155
            }
156
        }
157
158
        for (i, (singular_desc, plural_desc, amount)) in [
159
            ("file changed", "files changed", files_changed),
160
            ("insertion(+)", "insertions(+)", insertions),
161
            ("deletion(-)", "deletions(-)", deletions),
162
        ]
163
        .into_iter()
164
        .enumerate()
165
        {
166
            if amount == 0 {
167
                continue;
168
            }
169
170
            let prefix = if i == 0 { "" } else { "," };
171
            let desc = if amount == 1 {
172
                singular_desc
173
            } else {
174
                plural_desc
175
            };
176
            write!(diff.stats, "{prefix} {amount} {desc}")?;
177
        }
178
        writeln!(diff.stats)?;
179
180
        for f in &mut diff.file_diffs {
181
            f.total_percentage = if diff.total < 100 && diff.total > 0 {
182
                diff.total as f64
183
            } else if diff.total > 0 {
184
                (f.total as f64) * 100.0 / (diff.total as f64)
185
            } else {
186
                0.0
187
            };
188
189
            if f.total > 0 {
190
                f.insertions_percentage = (f.insertions as f64) * 100.0 / (f.total as f64);
191
                f.deletions_percentage = (f.deletions as f64) * 100.0 / (f.total as f64);
192
            }
193
        }
194
195
        Ok(diff)
196
    }
197
}
198
199
trait DiffFormatter {
200
    fn file_header(&self, output: &mut String, data: fmt::Arguments<'_>);
201
202
    fn write(&self, output: &mut String, class: &str, data: &str);
203
204
    fn binary(
205
        &self,
206
        output: &mut String,
207
        left: &str,
208
        right: &str,
209
        left_content: &[u8],
210
        right_content: &[u8],
211
    );
212
213
    fn path_line(
214
        &self,
215
        prefix: char,
216
        is_null: bool,
217
        state: &FileState,
218
        repo_name: &str,
219
        rela_path: &BStr,
220
        rev_id: &str,
221
    ) -> String;
222
223
    fn format(&self) -> DiffFormat;
224
}
225
226
struct DiffBuilder<'a, F> {
227
    output: &'a mut String,
228
    resource_cache: &'a mut gix::diff::blob::Platform,
229
    diffs: &'a mut Vec<FileDiff>,
230
    formatter: &'a F,
231
}
232
233
impl<F: DiffFormatter> DiffBuilder<'_, F> {
234
    fn handle(
235
        &mut self,
236
        change: gix::object::tree::diff::Change<'_, '_, '_>,
237
        repo: &Repository,
238
        parent_id: Option<&str>,
239
        commit_id: &str,
240
        limit_file: Option<&str>,
241
    ) -> anyhow::Result<gix::object::tree::diff::Action> {
242
        if !change.entry_mode().is_blob_or_symlink() {
243
            return Ok(gix::object::tree::diff::Action::Continue(()));
244
        }
245
246
        let path = change.location().to_string();
247
        if let Some(limit_file) = limit_file
248
            && limit_file != path
249
            && !limit_file.is_empty()
250
        {
251
            return Ok(gix::object::tree::diff::Action::Continue(()));
252
        }
253
        let mut diff = FileDiff {
254
            path,
255
            ..Default::default()
256
        };
257
        let change = change.diff(self.resource_cache)?;
258
        let prep = change.resource_cache.prepare_diff()?;
259
260
        self.formatter.file_header(
261
            self.output,
262
            format_args!(
263
                "diff --git a/{} b/{}",
264
                prep.old.rela_path, prep.new.rela_path
265
            ),
266
        );
267
268
        if prep.old.id.is_null() {
269
            self.formatter.file_header(
270
                self.output,
271
                format_args!("new file mode {}", prep.new.mode.as_octal_str()),
272
            );
273
            diff.state = FileState::Added;
274
        } else if prep.new.id.is_null() {
275
            self.formatter.file_header(
276
                self.output,
277
                format_args!("deleted file mode {}", prep.old.mode.as_octal_str()),
278
            );
279
            diff.state = FileState::Removed;
280
        } else if prep.new.mode != prep.old.mode {
281
            self.formatter.file_header(
282
                self.output,
283
                format_args!("old mode {}", prep.old.mode.as_octal_str()),
284
            );
285
            self.formatter.file_header(
286
                self.output,
287
                format_args!("new mode {}", prep.new.mode.as_octal_str()),
288
            );
289
        }
290
291
        // mode shown in the diffstat table: whichever side still exists
292
        let mode_source = if matches!(diff.state, FileState::Removed) {
293
            prep.old.mode
294
        } else {
295
            prep.new.mode
296
        };
297
        let raw_mode = u32::from_str_radix(mode_source.as_octal_str().to_str()?, 8)?;
298
        diff.mode = format_mode(raw_mode);
299
300
        // copy from / copy to / rename old / rename new / rename from /
301
        // rename to / similarity index / dissimilarity index — TODO
302
303
        let (index_suffix_sep, index_suffix) = if prep.old.mode == prep.new.mode {
304
            (" ", prep.new.mode.as_octal_str())
305
        } else {
306
            ("", BStr::new(&[]))
307
        };
308
309
        let old_path = self.formatter.path_line(
310
            'a',
311
            prep.old.id.is_null(),
312
            &diff.state,
313
            &repo.name,
314
            prep.old.rela_path,
315
            parent_id.unwrap_or_default(),
316
        );
317
        let new_path = self.formatter.path_line(
318
            'b',
319
            prep.new.id.is_null(),
320
            &diff.state,
321
            &repo.name,
322
            prep.new.rela_path,
323
            commit_id,
324
        );
325
326
        match prep.operation {
327
            Operation::InternalDiff { algorithm } => {
328
                self.formatter.file_header(
329
                    self.output,
330
                    format_args!(
331
                        "index {}..{}{index_suffix_sep}{index_suffix}",
332
                        prep.old.id.to_hex_with_len(7),
333
                        prep.new.id.to_hex_with_len(7)
334
                    ),
335
                );
336
                self.formatter
337
                    .file_header(self.output, format_args!("--- {old_path}"));
338
                self.formatter
339
                    .file_header(self.output, format_args!("+++ {new_path}"));
340
341
                let old_source = gix::diff::blob::sources::lines(str::from_utf8(
342
                    prep.old.data.as_slice().unwrap_or_default(),
343
                )?);
344
                let new_source = gix::diff::blob::sources::lines(str::from_utf8(
345
                    prep.new.data.as_slice().unwrap_or_default(),
346
                )?);
347
                let input = gix::diff::blob::InternedInput::new(old_source, new_source);
348
                let output = gix::diff::blob::Diff::compute(algorithm, &input);
349
350
                diff.deletions += output.count_removals() as usize;
351
                diff.insertions += output.count_additions() as usize;
352
                diff.total = diff.deletions.saturating_add(diff.insertions);
353
354
                Self::write_hunks(self.formatter, self.output, &input, &output);
355
            }
356
            Operation::ExternalCommand { .. } => {}
357
            Operation::SourceOrDestinationIsBinary => {
358
                self.formatter.file_header(
359
                    self.output,
360
                    format_args!(
361
                        "index {}..{}{index_suffix_sep}{index_suffix}",
362
                        prep.old.id, prep.new.id,
363
                    ),
364
                );
365
366
                self.formatter.binary(
367
                    self.output,
368
                    old_path.as_ref(),
369
                    new_path.as_ref(),
370
                    prep.old.data.as_slice().unwrap_or_default(),
371
                    prep.new.data.as_slice().unwrap_or_default(),
372
                );
373
            }
374
        }
375
376
        self.diffs.push(diff);
377
378
        self.resource_cache.clear_resource_cache_keep_allocation();
379
        Ok(gix::object::tree::diff::Action::Continue(()))
380
    }
381
382
    fn write_hunks(
383
        formatter: &F,
384
        output: &mut String,
385
        input: &gix::diff::blob::InternedInput<&str>,
386
        diff: &gix::diff::blob::Diff,
387
    ) {
388
        const CONTEXT_LINES: u32 = 3;
389
390
        let hunks: Vec<_> = diff.hunks().collect();
391
        let mut i = 0;
392
393
        while i < hunks.len() {
394
            let start = i;
395
            let mut end = i + 1;
396
            while end < hunks.len()
397
                && hunks[end]
398
                    .before
399
                    .start
400
                    .saturating_sub(hunks[end - 1].before.end)
401
                    <= CONTEXT_LINES * 2
402
            {
403
                end += 1;
404
            }
405
            i = end;
406
407
            let first = &hunks[start];
408
            let last = &hunks[end - 1];
409
410
            let before_start = first.before.start.saturating_sub(CONTEXT_LINES);
411
            let before_end = (last.before.end + CONTEXT_LINES).min(input.before.len() as u32);
412
            let after_start = first.after.start.saturating_sub(CONTEXT_LINES);
413
            let after_end = (last.after.end + CONTEXT_LINES).min(input.after.len() as u32);
414
415
            formatter.write(
416
                output,
417
                "hunk",
418
                &format!(
419
                    "@@ -{},{} +{},{} @@\n",
420
                    before_start + 1,
421
                    before_end - before_start,
422
                    after_start + 1,
423
                    after_end - after_start,
424
                ),
425
            );
426
427
            let mut before_pos = before_start;
428
            let mut _after_pos = after_start;
429
430
            for hunk in &hunks[start..end] {
431
                while before_pos < hunk.before.start {
432
                    let line = input.interner[input.before[before_pos as usize]];
433
                    formatter.write(output, "context", line);
434
                    before_pos += 1;
435
                    _after_pos += 1;
436
                }
437
438
                for pos in hunk.before.clone() {
439
                    let line = input.interner[input.before[pos as usize]];
440
                    formatter.write(output, "deletion", line);
441
                }
442
                before_pos = hunk.before.end;
443
444
                for pos in hunk.after.clone() {
445
                    let line = input.interner[input.after[pos as usize]];
446
                    formatter.write(output, "addition", line);
447
                }
448
                _after_pos = hunk.after.end;
449
            }
450
451
            while before_pos < before_end {
452
                let line = input.interner[input.before[before_pos as usize]];
453
                formatter.write(output, "context", line);
454
                before_pos += 1;
455
                _after_pos += 1;
456
            }
457
        }
458
    }
459
}
460
461
// ---- unchanged, per your request ----
462
struct PlainDiffFormatter;
463
464
impl DiffFormatter for PlainDiffFormatter {
465
    fn file_header(&self, output: &mut String, data: fmt::Arguments<'_>) {
466
        write!(output, r#"<span class="diff-file-header">"#).unwrap();
467
        write!(output, "{data}").unwrap();
468
        output.push_str("</span>\n");
469
    }
470
471
    fn write(&self, output: &mut String, class: &str, data: &str) {
472
        write!(output, r#"<span class="diff-{class}">"#).unwrap();
473
        v_htmlescape::b_escape(data.as_bytes(), output);
474
        output.push_str("</span>");
475
    }
476
477
    fn binary(
478
        &self,
479
        output: &mut String,
480
        left: &str,
481
        right: &str,
482
        _left_content: &[u8],
483
        _right_content: &[u8],
484
    ) {
485
        // todo: actually perform the diff and write a `GIT binary patch` out
486
        writeln!(output, "Binary files {left} and {right} differ").unwrap();
487
    }
488
489
    fn path_line(
490
        &self,
491
        prefix: char,
492
        is_null: bool,
493
        state: &FileState,
494
        repo_name: &str,
495
        rela_path: &BStr,
496
        rev_id: &str,
497
    ) -> String {
498
        if is_null {
499
            "/dev/null".to_string()
500
        } else {
501
            format!(
502
                "{prefix}/<a class='{state}' href='/{repo_name}/diff/{rela_path}?id={rev_id}'>{rela_path}</a>"
503
            )
504
        }
505
    }
506
507
    fn format(&self) -> DiffFormat {
508
        DiffFormat::Plain
509
    }
510
}
511
512
// ---- new: plain unified diff, git-apply compatible ----
513
struct PatchDiffFormatter;
514
515
impl DiffFormatter for PatchDiffFormatter {
516
    fn file_header(&self, output: &mut String, data: fmt::Arguments<'_>) {
517
        writeln!(output, "{data}").unwrap();
518
    }
519
520
    fn write(&self, output: &mut String, class: &str, data: &str) {
521
        // unified diff requires a literal leading +/-/space on every
522
        // content line — this is what the Plain (CSS-classed) formatter
523
        // can skip but a real patch cannot.
524
        let prefix = match class {
525
            "addition" => "+",
526
            "deletion" => "-",
527
            "context" => " ",
528
            _ => "", // hunk header line, no prefix
529
        };
530
        output.push_str(prefix);
531
        output.push_str(data);
532
    }
533
534
    fn binary(
535
        &self,
536
        output: &mut String,
537
        left: &str,
538
        right: &str,
539
        _left_content: &[u8],
540
        _right_content: &[u8],
541
    ) {
542
        // todo: emit an actual `GIT binary patch` block
543
        writeln!(output, "Binary files {left} and {right} differ").unwrap();
544
    }
545
546
    fn path_line(
547
        &self,
548
        prefix: char,
549
        is_null: bool,
550
        _state: &FileState,
551
        _repo_name: &str,
552
        rela_path: &BStr,
553
        _rev_id: &str,
554
    ) -> String {
555
        if is_null {
556
            "/dev/null".to_string()
557
        } else {
558
            format!("{prefix}/{rela_path}")
559
        }
560
    }
561
562
    fn format(&self) -> DiffFormat {
563
        DiffFormat::Patch
564
    }
565
}
566
567
pub fn format_mode(mode: u32) -> String {
568
    let file_type = match mode & 0o170000 {
569
        0o040000 => 'd',
570
        0o120000 => 'l',
571
        0o160000 => 'm',
572
        0o100000 => '-',
573
        _ => '?',
574
    };
575
576
    let perms = mode & 0o777;
577
    let mut out = String::with_capacity(10);
578
    out.push(file_type);
579
580
    for &shift in &[6, 3, 0] {
581
        let bits = (perms >> shift) & 0o7;
582
        out.push(if bits & 0o4 != 0 { 'r' } else { '-' });
583
        out.push(if bits & 0o2 != 0 { 'w' } else { '-' });
584
        out.push(if bits & 0o1 != 0 { 'x' } else { '-' });
585
    }
586
587
    out
588
}