index : gitrs
A lightweight web interface for browsing Git repositories, implemented in Rust
about summary refs log tree commit diff

Diffstat (limited to 'src/git/diff.rs')

-rw-r--r-- src/git/diff.rs 273
 1 file changed, 103 insertions(+), 170 deletions(-)

diff --git a/src/git/diff.rs b/src/git/diff.rs
index a4b5b7d..d246b42 100644
--- a/src/git/diff.rs
+++ b/src/git/diff.rs
@@ -5,17 +5,13 @@
    diff::blob::platform::prepare_diff::Operation,
};

use crate::prelude::*;
use crate::{git::tree::format_mode, prelude::*};

#[derive(Default)]
pub struct Diff {
    pub file_diffs: Vec<FileDiff>,
    pub output: String,
    pub stats: String,
    pub files_changed: usize,
    pub insertions: usize,
    pub deletions: usize,
    pub total: usize,
}

#[derive(Default)]
@@ -53,6 +49,98 @@
pub enum DiffFormat {
    Plain,
    Patch,
}

impl Diff {
    fn finalize(&mut self, is_patch: bool) -> fmt::Result {
        let files_changed = self.file_diffs.len();
        let insertions: usize = self.file_diffs.iter().map(|f| f.insertions).sum();
        let deletions: usize = self.file_diffs.iter().map(|f| f.deletions).sum();
        let total = deletions.saturating_add(insertions);

        if is_patch {
            self.write_patch_stat_bars(insertions, total)?;
        }
        self.write_summary_line(files_changed, insertions, deletions)?;
        self.compute_percentages(total);
        Ok(())
    }

    fn write_patch_stat_bars(
        &mut self,
        total_insertions: usize,
        total_changes: usize,
    ) -> fmt::Result {
        const WIDTH: usize = 80;

        let (max_name_len, max_change_len) =
            self.file_diffs
                .iter()
                .fold((0, 0), |(max_name, max_change), f| {
                    let digits = ((f.insertions + f.deletions + 1).ilog10() + 1) as usize;
                    (max_name.max(f.path.len()), max_change.max(digits))
                });

        for f in &self.file_diffs {
            let local_changes = f.insertions + f.deletions;
            let width = WIDTH.min(local_changes);

            let add_w = (width * f.insertions) / total_changes;
            let del_w = (width * f.deletions) / total_changes;
            let rem_w = width - (add_w + del_w);

            let plus_str = "+".repeat(add_w + rem_w.min(total_insertions));
            let minus_str = "-".repeat(del_w + (rem_w - rem_w.min(total_insertions)));

            writeln!(
                self.stats,
                " {:max_name_len$} | {:max_change_len$} {plus_str}{minus_str}",
                f.path, local_changes
            )?;
        }
        Ok(())
    }

    fn write_summary_line(
        &mut self,
        files_changed: usize,
        insertions: usize,
        deletions: usize,
    ) -> fmt::Result {
        for (i, (singular, plural, amount)) in [
            ("file changed", "files changed", files_changed),
            ("insertion(+)", "insertions(+)", insertions),
            ("deletion(-)", "deletions(-)", deletions),
        ]
        .into_iter()
        .enumerate()
        {
            if amount == 0 {
                continue;
            }
            let prefix = if i == 0 { "" } else { "," };
            let desc = if amount == 1 { singular } else { plural };
            write!(self.stats, "{prefix} {amount} {desc}")?;
        }
        writeln!(self.stats)
    }

    fn compute_percentages(&mut self, total_changes: usize) {
        for f in &mut self.file_diffs {
            f.total_percentage = if total_changes == 0 {
                0.0
            } else if total_changes < 100 {
                total_changes as f64
            } else {
                (f.total as f64) * 100.0 / (total_changes as f64)
            };

            if f.total > 0 {
                f.insertions_percentage = (f.insertions as f64) * 100.0 / (f.total as f64);
                f.deletions_percentage = (f.deletions as f64) * 100.0 / (f.total as f64);
            }
        }
    }
}

impl<'repo> Commit<'repo> {
@@ -68,19 +156,15 @@
        }
    }

    /// Computes the diff between this commit and its first parent commit (or an empty tree if this is the initial commit).
    fn diff_with<F: DiffFormatter>(
        &self,
        repo: &Repository,
        limit_file: Option<&str>,
        formatter: F,
    ) -> Result<Diff, Error> {
        const WIDTH: usize = 80;
        let mut diff = Diff::default();
        let gix_repo = repo.gix();

        // Phase 1: Get this commit's root directory Tree and its first parent's root directory Tree.
        // If the commit has no parents (the very first commit in the repo), compare against an empty Tree.
        let current_tree = self.gix.tree()?;
        let first_parent = self.gix.parent_ids().next();
        let parent_tree = match first_parent {
@@ -90,8 +174,6 @@
        let parent_id = first_parent.map(|id| id.to_string());
        let commit_id = self.gix.id.to_string();

        // `tree_diff_cache` is held by the tree-walker while iterating directory changes;
        // `blob_diff_cache` is used inside the callback to diff individual file contents (Blobs).
        let mut tree_diff_cache = gix_repo.diff_resource_cache_for_tree_diff()?;
        let mut blob_diff_cache = gix_repo.diff_resource_cache_for_tree_diff()?;

@@ -112,104 +194,16 @@
                .handle(change, repo, parent_id.as_deref(), &commit_id, limit_file)
            },
        )?;

        let files_changed = diff.file_diffs.len();
        let insertions: usize = diff.file_diffs.iter().map(|f| f.insertions).sum();
        let deletions: usize = diff.file_diffs.iter().map(|f| f.deletions).sum();
        diff.files_changed = files_changed;
        diff.insertions = insertions;
        diff.deletions = deletions;
        diff.total = diff.deletions.saturating_add(diff.insertions);

        if formatter.format() == DiffFormat::Patch {
            let (max_file_name_length, max_change_length) = diff.file_diffs.iter().fold(
                (0, 0),
                |(max_file_name_length, max_change_length), stats| {
                    (
                        max_file_name_length.max(stats.path.len()),
                        max_change_length
                            .max(((stats.insertions + stats.deletions + 1).ilog10() + 1) as usize),
                    )
                },
            );

            for file_diff in &diff.file_diffs {
                let local_changes = file_diff.insertions + file_diff.deletions;
                let width = WIDTH.min(local_changes);

                let addition_width = (width * file_diff.insertions) / diff.total;
                let deletion_width = (width * file_diff.deletions) / diff.total;

                // Handle edge case where total width is less than total changes
                let remaining_width = width - (addition_width + deletion_width);
                let adjusted_addition_width = addition_width + remaining_width.min(diff.insertions);
                let adjusted_deletion_width =
                    deletion_width + (remaining_width - remaining_width.min(diff.insertions));

                // Generate the string representation
                let plus_str = "+".repeat(adjusted_addition_width);
                let minus_str = "-".repeat(adjusted_deletion_width);

                let file = file_diff.path.as_str();
                writeln!(diff.stats, " {file:max_file_name_length$} | {local_changes:max_change_length$} {plus_str}{minus_str}").unwrap();
            }
        }

        for (i, (singular_desc, plural_desc, amount)) in [
            ("file changed", "files changed", files_changed),
            ("insertion(+)", "insertions(+)", insertions),
            ("deletion(-)", "deletions(-)", deletions),
        ]
        .into_iter()
        .enumerate()
        {
            if amount == 0 {
                continue;
            }

            let prefix = if i == 0 { "" } else { "," };
            let desc = if amount == 1 {
                singular_desc
            } else {
                plural_desc
            };
            write!(diff.stats, "{prefix} {amount} {desc}")?;
        }
        writeln!(diff.stats)?;

        for f in &mut diff.file_diffs {
            f.total_percentage = if diff.total < 100 && diff.total > 0 {
                diff.total as f64
            } else if diff.total > 0 {
                (f.total as f64) * 100.0 / (diff.total as f64)
            } else {
                0.0
            };

            if f.total > 0 {
                f.insertions_percentage = (f.insertions as f64) * 100.0 / (f.total as f64);
                f.deletions_percentage = (f.deletions as f64) * 100.0 / (f.total as f64);
            }
        }

        diff.finalize(formatter.format() == DiffFormat::Patch)?;
        Ok(diff)
    }
}

trait DiffFormatter {
    fn file_header(&self, output: &mut String, data: fmt::Arguments<'_>);

    fn write(&self, output: &mut String, class: &str, data: &str);

    fn binary(
        &self,
        output: &mut String,
        left: &str,
        right: &str,
        left_content: &[u8],
        right_content: &[u8],
    );

    fn binary(&self, output: &mut String, left: &str, right: &str);
    fn path_line(
        &self,
        prefix: char,
@@ -219,7 +213,6 @@
        rela_path: &BStr,
        rev_id: &str,
    ) -> String;

    fn format(&self) -> DiffFormat;
}

@@ -245,11 +238,12 @@

        let path = change.location().to_string();
        if let Some(limit_file) = limit_file
            && limit_file != path
            && !limit_file.is_empty()
            && limit_file != path
        {
            return Ok(gix::object::tree::diff::Action::Continue(()));
        }

        let mut diff = FileDiff {
            path,
            ..Default::default()
@@ -288,7 +282,6 @@
            );
        }

        // mode shown in the diffstat table: whichever side still exists
        let mode_source = if matches!(diff.state, FileState::Removed) {
            prep.old.mode
        } else {
@@ -296,9 +289,6 @@
        };
        let raw_mode = u32::from_str_radix(mode_source.as_octal_str().to_str()?, 8)?;
        diff.mode = format_mode(raw_mode);

        // copy from / copy to / rename old / rename new / rename from /
        // rename to / similarity index / dissimilarity index — TODO

        let (index_suffix_sep, index_suffix) = if prep.old.mode == prep.new.mode {
            (" ", prep.new.mode.as_octal_str())
@@ -362,19 +352,11 @@
                        prep.old.id, prep.new.id,
                    ),
                );

                self.formatter.binary(
                    self.output,
                    old_path.as_ref(),
                    new_path.as_ref(),
                    prep.old.data.as_slice().unwrap_or_default(),
                    prep.new.data.as_slice().unwrap_or_default(),
                );
                self.formatter.binary(self.output, &old_path, &new_path);
            }
        }

        self.diffs.push(diff);

        self.resource_cache.clear_resource_cache_keep_allocation();
        Ok(gix::object::tree::diff::Action::Continue(()))
    }
@@ -425,14 +407,12 @@
            );

            let mut before_pos = before_start;
            let mut _after_pos = after_start;

            for hunk in &hunks[start..end] {
                while before_pos < hunk.before.start {
                    let line = input.interner[input.before[before_pos as usize]];
                    formatter.write(output, "context", line);
                    before_pos += 1;
                    _after_pos += 1;
                }

                for pos in hunk.before.clone() {
@@ -445,27 +425,23 @@
                    let line = input.interner[input.after[pos as usize]];
                    formatter.write(output, "addition", line);
                }
                _after_pos = hunk.after.end;
            }

            while before_pos < before_end {
                let line = input.interner[input.before[before_pos as usize]];
                formatter.write(output, "context", line);
                before_pos += 1;
                _after_pos += 1;
            }
        }
    }
}

// ---- unchanged, per your request ----
struct PlainDiffFormatter;

impl DiffFormatter for PlainDiffFormatter {
    fn file_header(&self, output: &mut String, data: fmt::Arguments<'_>) {
        write!(output, r#"<span class="diff-file-header">"#).unwrap();
        write!(output, "{data}").unwrap();
        output.push_str("</span>\n");
        write!(output, r#"<span class="diff-file-header">{data}</span>"#).unwrap();
        output.push('\n');
    }

    fn write(&self, output: &mut String, class: &str, data: &str) {
@@ -474,15 +450,7 @@
        output.push_str("</span>");
    }

    fn binary(
        &self,
        output: &mut String,
        left: &str,
        right: &str,
        _left_content: &[u8],
        _right_content: &[u8],
    ) {
        // todo: actually perform the diff and write a `GIT binary patch` out
    fn binary(&self, output: &mut String, left: &str, right: &str) {
        writeln!(output, "Binary files {left} and {right} differ").unwrap();
    }

@@ -509,7 +477,6 @@
    }
}

// ---- new: plain unified diff, git-apply compatible ----
struct PatchDiffFormatter;

impl DiffFormatter for PatchDiffFormatter {
@@ -518,28 +485,17 @@
    }

    fn write(&self, output: &mut String, class: &str, data: &str) {
        // unified diff requires a literal leading +/-/space on every
        // content line — this is what the Plain (CSS-classed) formatter
        // can skip but a real patch cannot.
        let prefix = match class {
            "addition" => "+",
            "deletion" => "-",
            "context" => " ",
            _ => "", // hunk header line, no prefix
            _ => "",
        };
        output.push_str(prefix);
        output.push_str(data);
    }

    fn binary(
        &self,
        output: &mut String,
        left: &str,
        right: &str,
        _left_content: &[u8],
        _right_content: &[u8],
    ) {
        // todo: emit an actual `GIT binary patch` block
    fn binary(&self, output: &mut String, left: &str, right: &str) {
        writeln!(output, "Binary files {left} and {right} differ").unwrap();
    }

@@ -561,28 +517,5 @@

    fn format(&self) -> DiffFormat {
        DiffFormat::Patch
    }
}

pub fn format_mode(mode: u32) -> String {
    let file_type = match mode & 0o170000 {
        0o040000 => 'd',
        0o120000 => 'l',
        0o160000 => 'm',
        0o100000 => '-',
        _ => '?',
    };

    let perms = mode & 0o777;
    let mut out = String::with_capacity(10);
    out.push(file_type);

    for &shift in &[6, 3, 0] {
        let bits = (perms >> shift) & 0o7;
        out.push(if bits & 0o4 != 0 { 'r' } else { '-' });
        out.push(if bits & 0o2 != 0 { 'w' } else { '-' });
        out.push(if bits & 0o1 != 0 { 'x' } else { '-' });
    }

    out
}