//! History (M4.6): pages of the commit log, one commit's details and a //! file's contents at any commit. //! //! Output is read from NUL-separated formats only (`--format` with `%x00` //! between fields and `%x1e` before each record, `--name-status -z`). The //! parsers take untrusted bytes: malformed records are skipped, never a //! panic (property-tested). use crate::repo::{SMALL_CAP, check_name}; use crate::runner::Call; use crate::{Contents, FILE_CAP, Repo, VcsError, decode}; /// Most commits one [`Repo::log`] page returns. pub const LOG_LIMIT: usize = 500; /// Most changed files [`Repo::show_commit`] lists. pub const COMMIT_FILES_CAP: usize = 10_000; /// Separator before each record of the log format. const RECORD: u8 = 0x1e; /// The log format: hash, parents, author, email, author date (strict ISO /// 8601), subject, ref names; fields NUL-separated, each record starting /// with [`RECORD`]. const LOG_FORMAT: &str = "--format=%x1e%H%x00%P%x00%an%x00%ae%x00%aI%x00%s%x00%D"; /// The details format: hash, parents, author, email, author date, the raw /// message. const SHOW_FORMAT: &str = "--format=%H%x00%P%x00%an%x00%ae%x00%aI%x00%B"; /// What [`Repo::log`] lists. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct LogQuery { /// Commits to skip (paging). pub skip: usize, /// Commits to return; capped at [`LOG_LIMIT`], 0 means the cap. pub limit: usize, /// Only commits touching this project-relative file or folder (a file's /// history follows renames). pub path: Option, /// Only commits whose message contains this text (case-insensitive). pub query: Option, /// Only commits whose author name or email contains this text /// (case-insensitive). pub author: Option, } /// One commit of the log. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct LogCommit { /// Full hash. pub hash: String, /// Parent hashes, first parent first; empty for a root commit. pub parents: Vec, /// Author name. pub author: String, /// Author email. pub email: String, /// Author date, strict ISO 8601 with offset. pub date: String, /// The subject line. pub subject: String, /// Ref names pointing here as git decorates them: `HEAD -> main`, /// `origin/main`, `tag: v1.0`. pub refs: Vec, } /// How a file changed in a commit (against its first parent). #[derive(Debug, Clone, PartialEq, Eq)] pub struct CommitFile { /// Project-relative path after the change. pub path: String, /// `added`, `modified`, `deleted`, `renamed` or `copied`. pub status: &'static str, /// The path before a rename or copy (project-relative; `None` when it /// lay outside the project). pub orig_path: Option, } /// One commit with its message and changed files. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct CommitDetails { /// Full hash. pub hash: String, /// Parent hashes, first parent first. pub parents: Vec, /// Author name. pub author: String, /// Author email. pub email: String, /// Author date, strict ISO 8601. pub date: String, /// The full message, trailing line breaks removed. pub message: String, /// Files changed against the first parent (against nothing for a root /// commit), inside the project, at most [`COMMIT_FILES_CAP`]. pub files: Vec, /// More files changed than [`CommitDetails::files`] holds. pub truncated: bool, } impl Repo { /// One page of history, newest first in topological order (children /// before parents, so graph lanes can be drawn), over all local /// branches, remote-tracking branches, tags and HEAD. With a path: /// only HEAD's history of that path. Inside a repository whose root /// lies above the project, only commits touching the project. /// /// # Errors /// [`VcsError::InvalidPath`], or git's refusal. A repository without /// commits has an empty log. pub fn log(&self, query: &LogQuery) -> Result, VcsError> { let limit = if query.limit == 0 { LOG_LIMIT } else { query.limit.min(LOG_LIMIT) }; let pathspec = match query.path.as_deref() { Some(path) => Some(self.to_repo_path(path)?), None => Some(self.prefix().trim_end_matches('/').to_string()).filter(|p| !p.is_empty()), }; let follow = query.path.is_some() && pathspec .as_deref() .is_some_and(|p| self.root().join(p).is_file()); let skip = format!("--skip={}", query.skip); let count = format!("--max-count={limit}"); let grep = filter_text(query.query.as_deref()).map(|q| format!("--grep={q}")); let author = filter_text(query.author.as_deref()).map(|a| format!("--author={a}")); let mut args: Vec<&str> = vec![ "log", LOG_FORMAT, "--topo-order", "--decorate=short", "--fixed-strings", "--regexp-ignore-case", &skip, &count, ]; if follow { args.push("--follow"); } args.extend(grep.as_deref()); args.extend(author.as_deref()); if query.path.is_none() { args.extend(["--branches", "--remotes", "--tags"]); } args.extend(["--end-of-options", "HEAD"]); if let Some(spec) = pathspec.as_deref() { args.extend(["--", spec]); } let output = self.run(Call::read(self.root(), &args, SMALL_CAP))?; if !output.success() { let message = output.message(); if message.contains("does not have any commits") || message.contains("unknown revision") { return Ok(Vec::new()); } return Err(VcsError::Git(message)); } Ok(parse_log(&output.stdout)) } /// One commit's details: the full message and the files changed /// against its first parent, renames detected. /// /// # Parameters /// - `hash`: a commit hash (4 to 64 hex digits, abbreviations allowed /// when unambiguous). /// /// # Errors /// [`VcsError::InvalidName`] for something that is not a hash, /// [`VcsError::Git`] when no such commit exists. pub fn show_commit(&self, hash: &str) -> Result { check_hash(hash)?; let commit = format!("{hash}^{{commit}}"); let output = self .run(Call::read( self.root(), &["show", "-s", SHOW_FORMAT, "--end-of-options", &commit], SMALL_CAP, ))? .checked()?; let mut details = parse_details(&output.stdout).ok_or_else(|| VcsError::BadOutput(hash.to_string()))?; let mut args = vec![ "diff-tree", "--no-commit-id", "-r", "-z", "-M", "--name-status", ]; let parent = details.parents.first().cloned(); if parent.is_none() { args.push("--root"); } args.push("--end-of-options"); if let Some(parent) = parent.as_deref() { args.push(parent); } args.push(&details.hash); let output = self .run(Call::read(self.root(), &args, SMALL_CAP))? .checked()?; let mut files = Vec::new(); for (status, path, orig) in parse_name_status(&output.stdout) { let Some(path) = self.from_repo_path(&path) else { continue; }; if files.len() == COMMIT_FILES_CAP { details.truncated = true; break; } files.push(CommitFile { path, status, orig_path: orig.and_then(|o| self.from_repo_path(&o)), }); } details.files = files; Ok(details) } /// A file's contents at a commit, as stored (no filters or line-ending /// conversion), with the same rules as [`Repo::show`]. /// /// # Parameters /// - `path`: project-relative path. /// - `rev`: a commit hash or another revision (`main`, `abc123^`); /// not starting with `-`, without `:` or control characters. /// /// # Errors /// [`VcsError::InvalidPath`], [`VcsError::InvalidName`], or the /// runner's errors. A path or revision that does not exist is empty /// [`Contents`]. pub fn show_at(&self, path: &str, rev: &str) -> Result { let path = self.to_repo_path(path)?; check_name(rev)?; if rev.contains(':') || rev.trim() != rev { return Err(VcsError::InvalidName(rev.to_string())); } let object = format!("{rev}:{path}\n"); let output = self .run( Call::read(self.root(), &["cat-file", "--batch-check"], SMALL_CAP) .stdin(object.into_bytes()), )? .checked()?; let line = String::from_utf8_lossy(&output.stdout); let fields: Vec<&str> = line.trim_end().rsplitn(3, ' ').collect(); let [size, kind, oid] = fields.as_slice() else { return Ok(Contents::default()); }; if *size == "missing" || *kind == "missing" || *kind == "ambiguous" || *kind == "tree" { return Ok(Contents::default()); } if *kind != "blob" { return Ok(Contents { binary: true, ..Contents::default() }); } let size: usize = size .parse() .map_err(|_| VcsError::BadOutput(line.to_string()))?; if size > FILE_CAP { return Ok(Contents { too_large: true, ..Contents::default() }); } let output = self .run(Call::read( self.root(), &["cat-file", "blob", oid], FILE_CAP, ))? .checked()?; Ok(decode(output.stdout)) } } /// A filter text worth passing: trimmed, not empty, without control /// characters (which git's pattern options cannot take anyway). fn filter_text(text: Option<&str>) -> Option { let text = text?.trim(); if text.is_empty() { return None; } Some(text.chars().filter(|c| !c.is_control()).collect()) } /// Rejects anything but 4 to 64 hex digits. fn check_hash(hash: &str) -> Result<(), VcsError> { if (4..=64).contains(&hash.len()) && hash.bytes().all(|b| b.is_ascii_hexdigit()) { Ok(()) } else { Err(VcsError::InvalidName(hash.to_string())) } } /// Splits git's space-separated parent list. fn parents(field: &str) -> Vec { field.split_whitespace().map(str::to_string).collect() } /// Parses the [`LOG_FORMAT`] output. Records with too few fields or an /// empty hash are skipped. pub fn parse_log(bytes: &[u8]) -> Vec { let mut commits = Vec::new(); for record in bytes.split(|b| *b == RECORD) { let text = String::from_utf8_lossy(record); let text = text.trim_end_matches(['\n', '\r']); let mut fields = text.split('\0'); let ( Some(hash), Some(parent_list), Some(author), Some(email), Some(date), Some(subject), Some(refs), ) = ( fields.next(), fields.next(), fields.next(), fields.next(), fields.next(), fields.next(), fields.next(), ) else { continue; }; let hash = hash.trim(); if hash.is_empty() { continue; } commits.push(LogCommit { hash: hash.to_string(), parents: parents(parent_list), author: author.to_string(), email: email.to_string(), date: date.to_string(), subject: subject.to_string(), refs: refs .split(", ") .map(str::trim) .filter(|r| !r.is_empty()) .map(str::to_string) .collect(), }); } commits } /// Parses the [`SHOW_FORMAT`] output; `None` without a hash. pub fn parse_details(bytes: &[u8]) -> Option { let text = String::from_utf8_lossy(bytes); let mut fields = text.splitn(6, '\0'); let hash = fields.next()?.trim().to_string(); if hash.is_empty() { return None; } let parent_list = fields.next()?; let author = fields.next()?.to_string(); let email = fields.next()?.to_string(); let date = fields.next()?.to_string(); let message = fields .next() .unwrap_or_default() .trim_end_matches(['\n', '\r']) .to_string(); Some(CommitDetails { hash, parents: parents(parent_list), author, email, date, message, files: Vec::new(), truncated: false, }) } /// Parses `diff-tree --name-status -z` into `(status, path, orig_path)` /// with root-relative paths. Unknown letters count as `modified`; a /// rename or copy without its second path (or an empty path) ends the /// list. pub fn parse_name_status(bytes: &[u8]) -> Vec<(&'static str, String, Option)> { let mut entries = Vec::new(); let mut fields = bytes .split(|b| *b == 0) .map(|f| String::from_utf8_lossy(f).into_owned()); while let Some(code) = fields.next() { let Some(letter) = code.bytes().next() else { continue; }; let status = match letter { b'A' => "added", b'D' => "deleted", b'R' => "renamed", b'C' => "copied", _ => "modified", }; let Some(first) = fields.next().filter(|f| !f.is_empty()) else { break; }; if matches!(letter, b'R' | b'C') { let Some(second) = fields.next().filter(|f| !f.is_empty()) else { break; }; entries.push((status, second, Some(first))); } else { entries.push((status, first, None)); } } entries } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used, clippy::indexing_slicing)] use super::*; use proptest::prelude::*; #[test] fn log_records_parse() { let bytes = b"\x1eaaa\0p1 p2\0Ann\0a@x\x002026-01-01T00:00:00+01:00\0Merge it\0HEAD -> main, tag: v1\n\x1ebbb\0\0Bo\0b@x\x002026-01-01T00:00:00Z\0Root\0\n"; let commits = parse_log(bytes); assert_eq!(commits.len(), 2); assert_eq!(commits[0].parents, ["p1", "p2"]); assert_eq!(commits[0].refs, ["HEAD -> main", "tag: v1"]); assert_eq!(commits[1].parents, Vec::::new()); assert!(commits[1].refs.is_empty()); assert_eq!(commits[1].subject, "Root"); } #[test] fn short_records_are_skipped() { assert!(parse_log(b"\x1eaaa\0p\0only three").is_empty()); assert!(parse_log(b"").is_empty()); } #[test] fn details_keep_the_message_body() { let d = parse_details(b"h\0p\0A\0e\0d\0Subject\n\nBody\0with nul\n\n").unwrap(); assert_eq!(d.message, "Subject\n\nBody\0with nul"); assert_eq!(d.parents, ["p"]); assert!(parse_details(b"").is_none()); } #[test] fn name_status_reads_renames() { let e = parse_name_status(b"M\0a.php\0R087\0old.php\0new.php\0A\0b\0D\0c\0T\0d\0"); assert_eq!(e[0], ("modified", "a.php".into(), None)); assert_eq!(e[1], ("renamed", "new.php".into(), Some("old.php".into()))); assert_eq!(e[2].0, "added"); assert_eq!(e[3].0, "deleted"); assert_eq!(e[4].0, "modified"); assert_eq!(parse_name_status(b"R100\0only\0").len(), 0); } #[test] fn hashes_are_checked() { assert!(check_hash("abcd").is_ok()); assert!(check_hash("abc").is_err()); assert!(check_hash("HEAD").is_err()); assert!(check_hash("-abcd").is_err()); assert!(check_hash(&"a".repeat(65)).is_err()); } #[test] fn filter_text_drops_blanks_and_controls() { assert_eq!(filter_text(Some(" ")), None); assert_eq!(filter_text(Some(" a\nb ")), Some("ab".into())); assert_eq!(filter_text(None), None); } proptest! { #[test] fn parsers_never_panic(bytes in proptest::collection::vec(any::(), 0..512)) { let _ = parse_log(&bytes); let _ = parse_details(&bytes); let _ = parse_name_status(&bytes); } #[test] fn log_fields_round_trip( subject in "[^\0\x1e\n\r]{0,40}", author in "[^\0\x1e\n\r]{0,20}", ) { let bytes = format!("\x1eh\0\0{author}\0e\0d\0{subject}\0\n"); let commits = parse_log(bytes.as_bytes()); prop_assert_eq!(commits.len(), 1); prop_assert_eq!(&commits[0].subject, &subject); prop_assert_eq!(&commits[0].author, &author); } } }