//! One commit and its changes. use gitv_core::git_capped; use super::{DIFF_LIMIT, Repo}; use crate::cache::cached; use crate::html::{icon, plural, subject_or_placeholder}; use crate::urls::{Q, lossy, param}; use crate::{View, templates}; /// One changed file: how git names it (raw bytes, from NUL-delimited output) and its status. pub(crate) struct Change { pub(crate) status: &'static str, pub(crate) path: Vec, } /// Parse `git show -z --name-status`: a status (`M`, `A`, `D`, `R100`, ...) then one path, or /// two (old and new) for renames and copies. pub(crate) fn parse_changes(out: &[u8]) -> Vec { let mut fields = out.split(|b| *b == 0).filter(|f| !f.is_empty()); let mut changes = Vec::new(); while let Some(code) = fields.next() { let (status, paths) = match code.first() { Some(b'A') => ("Added", 1), Some(b'D') => ("Deleted", 1), Some(b'R') => ("Renamed", 2), Some(b'C') => ("Copied", 2), _ => ("", 1), }; let mut path = None; for _ in 0..paths { path = fields.next(); } let Some(path) = path else { break }; changes.push(Change { status, path: path.to_vec() }); } changes } /// One line of a diff: `hunk`, `add`, `del` or `ctx`, its old and new line numbers (empty /// where it has none), and its text. pub(crate) struct DiffLine { pub(crate) class: &'static str, pub(crate) old: String, pub(crate) new: String, pub(crate) text: String, } impl DiffLine { fn new(class: &'static str, old: String, new: String, text: &str) -> DiffLine { DiffLine { class, old, new, text: text.to_string() } } /// The mark the page shows before the line. pub(crate) fn sign(&self) -> &'static str { match self.class { "add" => "+", "del" => "-", _ => " ", } } } /// The lines of one file's diff: (class, old number, new number, text). pub(crate) struct FileDiff { pub(crate) rows: Vec, pub(crate) added: usize, pub(crate) removed: usize, pub(crate) binary: bool, } /// Split `git show` patch output into one entry per `diff --git` section, in order. Names come /// from [`parse_changes`], not from these human-readable headers, which quote or misplace odd names. pub(crate) fn parse_diff(text: &str) -> Vec { let mut files: Vec = Vec::new(); let (mut old, mut new) = (0usize, 0usize); for line in text.lines() { if line.starts_with("diff --git ") { files.push(FileDiff { rows: Vec::new(), added: 0, removed: 0, binary: false }); continue; } let Some(file) = files.last_mut() else { continue }; let in_hunk = !file.rows.is_empty(); if !in_hunk && line.starts_with("Binary files ") { file.binary = true; } else if line.starts_with("@@") { let nums: Vec = line .split_whitespace() .skip(1) .take(2) .map(|r| r.trim_start_matches(['-', '+']).split(',').next().and_then(|n| n.parse().ok()).unwrap_or(0)) .collect(); (old, new) = (nums.first().copied().unwrap_or(0), nums.get(1).copied().unwrap_or(0)); file.rows.push(DiffLine::new("hunk", String::new(), String::new(), line)); } else if !in_hunk { continue; } else if let Some(t) = line.strip_prefix('+') { file.rows.push(DiffLine::new("add", String::new(), new.to_string(), t)); new += 1; file.added += 1; } else if let Some(t) = line.strip_prefix('-') { file.rows.push(DiffLine::new("del", old.to_string(), String::new(), t)); old += 1; file.removed += 1; } else if let Some(t) = line.strip_prefix(' ') { file.rows.push(DiffLine::new("ctx", old.to_string(), new.to_string(), t)); old += 1; new += 1; } } files } pub(crate) fn view_commit(repo: &Repo, q: &Q) -> Option { let id = param(q, "id")?; // Any case: ids are hex, and the lookup reads them in lower case. if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_hexdigit()) { return None; } // Looked up as an object only: a branch named like this id can't redirect the page. let commit = repo.reader.commit_object(&id)?; // NUL between fields: a commit message can't contain one, so the subject and body can hold // any other byte, the separator git output elsewhere uses included. let meta = repo.reader.git(&[ "show", "-s", "--date=format:%-d %b %Y, %H:%M", "--format=%H%x00%P%x00%an%x00%ae%x00%ad%x00%s%x00%b", &commit, ])?; let f: Vec<&str> = meta.splitn(7, '\0').collect(); let [oid, parents, author, email, date, subject, message] = <[&str; 7]>::try_from(f).ok()?; let parent_links: String = parents.split_whitespace().map(|p| repo.sha_link(p)).collect::>().join(" "); // A commit's diff never changes, so its rendering is cached. If git can't produce it, the // page still shows the commit, with a note. let diff = cached(repo.key("diff", oid, ""), || render_diff(repo, oid, parents)) .unwrap_or_else(|| r#"

This commit’s changes couldn’t be read.

"#.into()); Some(View::Html( templates::Commit { title: subject_or_placeholder(subject), signed_in: repo.signed_in, masthead: repo.masthead("log", &repo.reader.default_ref(), None), browse: repo.url("tree", &[("ref", oid)]), message: message.trim(), author, email, date, short_id: oid.get(..12)?, parent_links, diff: &diff, } .to_string(), )) } /// A commit's changes as one panel per file. pub(crate) fn render_diff(repo: &Repo, oid: &str, parents: &str) -> Option { // A merge shows what it brought in relative to its first parent. let options = ["--format=", "--no-color", "-M", "--diff-merges=first-parent"]; let names = [&["show", "-z", "--name-status"][..], &options, &[oid]].concat(); let patch = [&["show", "--patch"][..], &options, &[oid]].concat(); // A deleted file still exists in the parent commit. let parent = parents.split_whitespace().next().unwrap_or(oid); render_changes(repo, &names, &patch, parent, oid, "This commit’s changes") } /// The changes from commit `old` to commit `new` as one panel per file, for a comparison. pub(crate) fn render_diff_between(repo: &Repo, old: &str, new: &str) -> Option { let options = ["--no-color", "-M", old, new, "--"]; let names = [&["diff", "-z", "--name-status"][..], &options].concat(); let patch = [&["diff", "--patch"][..], &options].concat(); render_changes(repo, &names, &patch, old, new, "These changes") } /// Changes as one panel per file, from git's `names` (NUL-delimited `--name-status`) and /// `patch` listings of the same diff. Files link to `new`, or to `old` when deleted. Only /// [`DIFF_LIMIT`] bytes of patch are read; past that the files are listed without their lines. fn render_changes( repo: &Repo, names: &[&str], patch: &[&str], old: &str, new: &str, what: &'static str, ) -> Option { let names = repo.reader.git_bytes(names)?; let changes = parse_changes(&names); let (patch, too_big) = git_capped(&repo.reader.dir, patch, DIFF_LIMIT).ok()?; let files = if too_big { Vec::new() } else { parse_diff(&String::from_utf8_lossy(&patch)) }; // The two listings come from the same diff, in the same order; if they ever disagree, show // names only rather than pair lines with the wrong file. let paired = files.len() == changes.len(); let panels: Vec = changes .iter() .enumerate() .map(|(i, change)| { let at = if change.status == "Deleted" { old } else { new }; templates::DiffFile { href: repo.url_at("blob", at.as_bytes(), &change.path, ""), path: lossy(&change.path), status: change.status, diff: files.get(i).filter(|_| paired), } }) .collect(); let totals = paired.then(|| files.iter().fold((0, 0), |(a, r), f| (a + f.added, r + f.removed))); let diff = templates::Diff { file_count: plural(changes.len(), "file", "files"), totals, too_big, what, file_icon: icon("file"), files: panels, }; Some(diff.to_string()) } #[cfg(test)] mod tests { use super::*; #[test] fn name_status_parsing() { let out = b"M\0src/a b.rs\0R100\0old name\0new\tname\0D\0gone\0A\0\xffbin\0"; let changes = parse_changes(out); let got: Vec<(&str, &[u8])> = changes.iter().map(|c| (c.status, c.path.as_slice())).collect(); assert_eq!( got, [("", &b"src/a b.rs"[..]), ("Renamed", b"new\tname"), ("Deleted", b"gone"), ("Added", b"\xffbin")] ); } }