//! Git plumbing for reading and writing repository state. use std::collections::BTreeMap; use std::ffi::OsString; use std::fs; use std::io::{self, Read as _, Write as _}; use std::path::{Path, PathBuf}; use std::process::{Command, Output, Stdio}; use std::time::{SystemTime, UNIX_EPOCH}; use self::refs::Qualified; use crate::{ AheadBehind, Branch, CommitTime, DiffRepository, DiffStat, MergeStatus, Oid, PatchId, ReadRepository, RepoError, Rev, WriteRepository, }; /// Git reference names and refspecs. pub mod refs; /// Environment variable that disables Git's colored output. const NO_COLOR: &str = "NO_COLOR"; /// Environment variable selecting the locale for Git's output. /// /// Forced to `C` so translatable output that gets parsed here, such as /// `--shortstat` summaries, stays in English regardless of the user's locale. const LC_ALL: &str = "LC_ALL"; /// Maximum bytes read from a file head for shebang-style inference. const HEAD_BYTES: usize = 64; /// Pathspec separator that ends Git's option list. const PATHSPEC_SEPARATOR: &str = "--"; /// Hexadecimal width of a SHA-1 object identifier. const SHA1_HEX_LEN: usize = 40; /// Object identifier of the empty tree in SHA-1 repositories. const SHA1_EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"; /// Hexadecimal width of a SHA-256 object identifier. const SHA256_HEX_LEN: usize = 64; /// Object identifier of the empty tree in SHA-256 repositories. const SHA256_EMPTY_TREE: &str = "6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321"; /// Git repository command context. #[derive(Clone, Debug)] pub struct Repository { /// Working directory for worktree-aware invocations. cwd: PathBuf, /// Git repository directory used for plumbing invocations. git_dir: PathBuf, /// Hexadecimal width of object identifiers in this repository. object_id_width: usize, /// Revision and option arguments forwarded during context refetches. selector_args: Vec, } impl Repository { /// Creates a repository context for `cwd` with selectors from raw diff args. pub fn new( cwd: impl Into, diff_args: impl Into>, ) -> Result { let repository = Self::discover(cwd.into())?; let selector_args = repository.diff_selector_args(diff_args.into())?; Ok(repository.with_selector_args(selector_args)) } /// Creates a repository command context with an explicit repository directory. pub fn from_git_dir(cwd: PathBuf, git_dir: PathBuf) -> Result { let output = Command::new("git") .arg("--git-dir") .arg(&git_dir) .args(["rev-parse", "--show-object-format"]) .current_dir(&cwd) .env(NO_COLOR, "1") .env(LC_ALL, "C") .output()?; if !output.status.success() { return Err(RepoError::git(&output)); } let format = utf8(output.stdout)?; let object_id_width = object_id_width(format.trim())?; Ok(Self { cwd, git_dir, object_id_width, selector_args: Vec::new(), }) } /// Creates a repository command context by resolving the repository for `cwd`. pub fn discover(cwd: PathBuf) -> Result { let output = Command::new("git") .arg("rev-parse") .args(["--absolute-git-dir", "--show-object-format"]) .current_dir(&cwd) .env(NO_COLOR, "1") .env(LC_ALL, "C") .output()?; if !output.status.success() { return Err(RepoError::git(&output)); } let text = utf8(output.stdout)?; let mut lines = text.lines(); let git_dir = PathBuf::from(lines.next().unwrap_or_default()); let object_id_width = object_id_width(lines.next().unwrap_or_default())?; if git_dir.as_os_str().is_empty() || lines.next().is_some() { return Err(RepoError::Git( "git rev-parse returned invalid repository metadata".to_owned(), )); } Ok(Self { cwd, git_dir, object_id_width, selector_args: Vec::new(), }) } /// Returns the absolute working-tree root, which diff paths are relative to. pub fn workdir(&self) -> Result { let output = self.command("rev-parse").arg("--show-toplevel").output()?; if !output.status.success() { return Err(RepoError::git(&output)); } let text = utf8(output.stdout)?; let root = PathBuf::from(text.trim()); if root.as_os_str().is_empty() { return Err(RepoError::Git( "git rev-parse --show-toplevel returned an empty path".to_owned(), )); } Ok(root) } /// Returns a copy with `selector_args` used for diff context refetches. pub fn with_selector_args(&self, selector_args: impl Into>) -> Self { Self { cwd: self.cwd.clone(), git_dir: self.git_dir.clone(), object_id_width: self.object_id_width, selector_args: selector_args.into(), } } /// Runs `git diff` with raw command-line arguments. pub fn diff_output(&self, args: &[OsString]) -> Result { self.command("diff") .arg("--full-index") .args(args) .output() .map_err(RepoError::Io) } /// Pairs corresponding commits between two versions of a review range. /// /// Git's range-diff matching is similarity based, so rewritten commits can /// be paired even when their object ids and exact patch ids changed. pub fn range_diff( &self, old_base: Oid, old_target: Oid, new_base: Oid, new_target: Oid, ) -> Result, RepoError> { let old_range = format!("{old_base}..{old_target}"); let new_range = format!("{new_base}..{new_target}"); let abbrev = format!("--abbrev={}", self.object_id_width); let output = self.run( "range-diff", &[ "--no-color", "--no-dual-color", &abbrev, &old_range, &new_range, ], Opts::default(), )?; if !output.status.success() { return Err(RepoError::git(&output)); } let stdout = utf8(output.stdout)?; let mut pairs = BTreeMap::new(); for line in stdout.lines() { let mut fields = line.split_whitespace(); let Some(_old_index) = fields.next() else { continue; }; let Some(old) = fields.next() else { continue; }; let Some(marker) = fields.next() else { continue; }; let Some(_new_index) = fields.next() else { continue; }; let Some(new) = fields.next() else { continue; }; if !matches!(marker, "=" | "!") { continue; } let (Ok(old), Ok(new)) = (old.parse(), new.parse()) else { continue; }; pairs.insert(old, new); } Ok(pairs) } /// Reads the first bytes of a Git blob object. pub fn head_line(&self, oid: Oid) -> Result, RepoError> { let mut child = self .command("show") .arg(oid.to_string()) .stdout(Stdio::piped()) .stderr(Stdio::null()) .spawn()?; let Some(mut stdout) = child.stdout.take() else { return Ok(None); }; let head = read_head(&mut stdout)?; let _ = child.kill(); let _ = child.wait(); Ok(head) } /// Returns a Git command configured for this repository. fn command(&self, subcommand: &str) -> Command { let mut command = Command::new("git"); command .arg(subcommand) .current_dir(&self.cwd) .env("GIT_DIR", &self.git_dir) .env(NO_COLOR, "1") .env(LC_ALL, "C"); command } /// Returns diff selectors without pathspec arguments. fn diff_selector_args(&self, args: Vec) -> Result, RepoError> { if let Some(separator) = args .iter() .position(|arg| arg.as_os_str() == PATHSPEC_SEPARATOR) { return Ok(args[..separator].to_vec()); } let mut selectors = self.rev_parse(&["--flags", "--no-revs"], &args)?; let revisions = self.rev_parse(&["--revs-only", "--symbolic"], &args)?; selectors.extend(revisions); Ok(selectors) } /// Runs `git rev-parse` to classify diff arguments. fn rev_parse(&self, modes: &[&str], args: &[OsString]) -> Result, RepoError> { let output = self.command("rev-parse").args(modes).args(args).output()?; if !output.status.success() { return Err(RepoError::git(&output)); } Ok(String::from_utf8_lossy(&output.stdout) .lines() .filter(|line| !line.is_empty()) .map(OsString::from) .collect()) } /// Runs a Git subcommand with default options and returns stdout bytes on success. fn git(&self, subcommand: &str, args: &[&str]) -> Result, RepoError> { let output = self.run(subcommand, args, Opts::default())?; if output.status.success() { Ok(output.stdout) } else { Err(RepoError::git(&output)) } } /// Returns the `git log`-style header for `commit`. pub fn commit_header(&self, commit: Oid) -> Result, RepoError> { let commit = commit.to_string(); self.git("show", &["-s", "--format=medium", &commit]) } /// Returns each commit's author name and newest author or committer timestamp. pub fn commit_metadata(&self, commits: &[Oid]) -> Result, RepoError> { if commits.is_empty() { return Ok(Vec::new()); } let mut args = vec![ "--no-walk=unsorted".to_owned(), "--format=%H%x00%an%x00%at%x00%ct".to_owned(), ]; args.extend(commits.iter().map(Oid::to_string)); let args = args.iter().map(String::as_str).collect::>(); let text = self.git("log", &args).and_then(utf8)?; let mut metadata = BTreeMap::new(); for line in text.lines() { let (id, author, recency) = Self::parse_commit_metadata(line)?; metadata.insert(id, (author, recency)); } commits .iter() .map(|commit| { metadata .get(commit) .cloned() .ok_or_else(|| RepoError::Git(format!("git log omitted metadata for {commit}"))) }) .collect() } /// Parses one fixed four-field commit metadata record from `git log`. fn parse_commit_metadata(line: &str) -> Result<(Oid, String, CommitTime), RepoError> { let mut fields = line.split('\0'); let (Some(id), Some(author), Some(authored), Some(committed), None) = ( fields.next(), fields.next(), fields.next(), fields.next(), fields.next(), ) else { return Err(RepoError::Git( "malformed commit metadata line from git log".to_owned(), )); }; let id = id .parse::() .map_err(|_| RepoError::Git("invalid oid from git log".to_owned()))?; let authored = authored .parse::() .map_err(|_| RepoError::Git("invalid author timestamp from git log".to_owned()))?; let committed = committed .parse::() .map_err(|_| RepoError::Git("invalid commit timestamp from git log".to_owned()))?; Ok(( id, author.to_owned(), CommitTime { seconds: authored.max(committed), }, )) } /// Runs a Git subcommand with optional stdin, index, and environment overrides. fn run(&self, subcommand: &str, args: &[&str], opts: Opts<'_>) -> Result { let mut command = self.command(subcommand); command.args(args); for (key, value) in opts.env { command.env(key, value); } if let Some(index) = opts.index { command.env("GIT_INDEX_FILE", index); } if let Some(stdin) = opts.stdin { command .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); let mut child = command.spawn()?; if let Some(child_stdin) = child.stdin.as_mut() { child_stdin.write_all(stdin)?; } child.wait_with_output().map_err(RepoError::Io) } else { command.output().map_err(RepoError::Io) } } } impl ReadRepository for Repository { /// Resolves a revision reference to a commit id. fn commit_id(&self, rev: &Rev) -> Result { let revision = format!("{}^{{commit}}", rev.as_str()); let bytes = self.git("rev-parse", &[&revision])?; Oid::try_from(bytes.as_slice()) .map_err(|_| RepoError::Git(format!("invalid oid from rev-parse {}", rev.as_str()))) } /// Returns the tree id for any commit or tree object. fn tree_id(&self, object: Oid) -> Result { let object = format!("{object}^{{tree}}"); let bytes = self.git("rev-parse", &[&object])?; Oid::try_from(bytes.as_slice()) .map_err(|_| RepoError::Git(format!("invalid oid from rev-parse {object}"))) } /// Returns the current commit stored in `reference`, if the ref exists. fn optional_ref(&self, reference: &Qualified<'_>) -> Result, RepoError> { let output = self.run( "rev-parse", &["--verify", "--quiet", reference.as_str()], Opts::default(), )?; if !output.status.success() { return Ok(None); } let oid = Oid::try_from(output.stdout.as_slice()) .map_err(|_| RepoError::Git(format!("invalid oid from {reference}")))?; Ok(Some(oid)) } /// Returns refs below `prefix`, sorted by refname. fn refs(&self, prefix: &Qualified<'_>) -> Result, Oid)>, RepoError> { let bytes = self.git( "for-each-ref", &["--format=%(refname) %(objectname)", prefix.as_str()], )?; let text = utf8(bytes)?; text.lines() .map(|line| { let (refname, object) = line .split_once(' ') .ok_or_else(|| RepoError::Git(format!("invalid for-each-ref line: {line}")))?; let refname = refs::RefString::try_from(refname.to_owned()) .map_err(|error| RepoError::Git(format!("invalid refname: {error}")))?; let reference = Qualified::from_refstr(refname.as_refstr()) .ok_or_else(|| RepoError::Git(format!("unqualified refname: {refname}")))? .into_owned(); let oid = object .parse() .map_err(|_| RepoError::Git(format!("invalid oid from {reference}")))?; Ok((reference, oid)) }) .collect() } /// Returns local branches, sorted by branch name. /// /// Tip commit times come from the same `for-each-ref` invocation, so /// callers can order branches without a subprocess per branch. fn branches(&self) -> Result, RepoError> { let bytes = self.git( "for-each-ref", &[ "--format=%(refname:short)%00%(objectname)%00%(committerdate:unix)", "refs/heads", ], )?; let text = utf8(bytes)?; text.lines() .map(|line| { let mut fields = line.split('\0'); let (Some(name), Some(head), Some(seconds)) = (fields.next(), fields.next(), fields.next()) else { return Err(RepoError::Git(format!("invalid branch line: {line}"))); }; let head = head .parse() .map_err(|_| RepoError::Git(format!("invalid branch head: {head}")))?; let seconds = seconds .parse() .map_err(|_| RepoError::Git(format!("invalid branch time: {seconds}")))?; Ok(Branch { name: name.to_owned(), head, time: CommitTime { seconds }, }) }) .collect() } /// Returns a Git configuration value, if set. fn config(&self, key: &str) -> Result, RepoError> { let output = self.run("config", &["--get", key], Opts::default())?; if !output.status.success() { return Ok(None); } let value = utf8(output.stdout)?; let value = value.trim().to_owned(); Ok((!value.is_empty()).then_some(value)) } /// Returns the repository trunk branch among `branches`. fn trunk(&self, branches: &[Branch]) -> Result, RepoError> { let remote = self.remote_default_branch()?; let configured = self.config("init.defaultBranch")?; Ok(remote .as_deref() .into_iter() .chain(configured.as_deref()) .chain([refs::name::str::MAIN, refs::name::str::MASTER]) .find_map(|name| branches.iter().find(|branch| branch.name == name)) .cloned()) } /// Returns the best common ancestor of two revisions. fn merge_base(&self, left: &Rev, right: &Rev) -> Result { let bytes = self.git("merge-base", &[left.as_str(), right.as_str()])?; let text = utf8(bytes)?; text.trim() .parse() .map_err(|_| RepoError::Git("invalid merge base".to_owned())) } /// Returns the branch point for `target` and its upstream or the trunk. fn branch_base(&self, target: &Rev) -> Result, RepoError> { let target_id = self.commit_id(target)?; let contains = format!("--contains={target_id}"); let bytes = self.git( "for-each-ref", &[ &contains, "--format=%(objectname)%00%(upstream)", "refs/heads", ], )?; let text = utf8(bytes)?; let target_id = target_id.to_string(); let refs = || text.lines().filter_map(|line| line.split_once('\0')); let has_exact_head = refs().any(|(head, _)| *head == target_id); let mut base = None; for (_, upstream) in refs() .filter(|(_, upstream)| !upstream.is_empty()) .filter(|(head, _)| !has_exact_head || *head == target_id) { let revision = format!("{upstream}^{{commit}}"); let output = self.run( "rev-parse", &["--verify", "--quiet", &revision], Opts::default(), )?; if !output.status.success() { continue; } let upstream = Oid::try_from(output.stdout.as_slice()) .map_err(|_| RepoError::Git(format!("invalid oid from rev-parse {upstream}")))?; base = Some(Rev::from(upstream)); break; } let base = if let Some(base) = base { base } else { let branches = self.branches()?; let Some(trunk) = self.trunk(&branches)? else { return Ok(None); }; Rev::from(trunk.head) }; let base = self.merge_base(&base, target)?; Ok(Some(base)) } /// Returns ahead and behind counts for `target` relative to `base`. fn ahead_behind(&self, base: &Rev, target: &Rev) -> Result { let range = format!("{}...{}", base.as_str(), target.as_str()); let bytes = self.git("rev-list", &["--left-right", "--count", &range])?; let text = utf8(bytes)?; let mut fields = text.split_whitespace(); let behind = fields .next() .ok_or_else(|| RepoError::Git("missing behind count".to_owned()))? .parse() .map_err(|_| RepoError::Git("invalid behind count".to_owned()))?; let ahead = fields .next() .ok_or_else(|| RepoError::Git("missing ahead count".to_owned()))? .parse() .map_err(|_| RepoError::Git("invalid ahead count".to_owned()))?; Ok(AheadBehind { ahead, behind }) } /// Returns whether `target` would merge into `base` with conflicts. fn merge_status(&self, base: &Rev, target: &Rev) -> Result { let merge_base = self.git("merge-base", &[base.as_str(), target.as_str()])?; let merge_base = utf8(merge_base)?; let merge_base = merge_base.trim(); let bytes = self.git( "merge-tree", &[ "--trivial-merge", merge_base, base.as_str(), target.as_str(), ], )?; let text = utf8(bytes)?; if text.trim().is_empty() { Ok(MergeStatus::Clean) } else { Ok(MergeStatus::Conflicts) } } /// Returns the single parent of `commit`, or an error if it has more or fewer. fn parent(&self, commit: Oid) -> Result { let commit = commit.to_string(); let bytes = self.git("show", &["-s", "--format=%P", &commit])?; let text = utf8(bytes)?; let parents = text.split_whitespace().collect::>(); match parents.as_slice() { [parent] => parent .parse() .map_err(|_| RepoError::Git(format!("{commit} parent is not a valid hash"))), _ => Err(RepoError::Git(format!( "{commit} does not have exactly one parent" ))), } } /// Returns the full commit message for `commit`. fn commit_message(&self, commit: Oid) -> Result { let commit = commit.to_string(); self.git("show", &["-s", "--format=%B", &commit]) .and_then(utf8) } /// Returns the committer timestamp for `commit`. fn commit_time(&self, commit: Oid) -> Result { let commit = commit.to_string(); let text = self.git("show", &["-s", "--format=%ct", &commit])?; let seconds = utf8(text)? .trim() .parse() .map_err(|_| RepoError::Git("invalid commit timestamp".to_owned()))?; Ok(CommitTime { seconds }) } /// Returns each commit's aggregated diff size, in the given order. /// /// All stats come from one `git log --shortstat` invocation so callers can /// size a whole review range without a subprocess per commit. Merge commits /// are compared to their first parent, matching [`Self::commit_diff`]. fn commit_stats(&self, commits: &[Oid]) -> Result, RepoError> { if commits.is_empty() { return Ok(Vec::new()); } let mut args = vec![ "--no-walk=unsorted".to_owned(), "--first-parent".to_owned(), "--format=%H".to_owned(), "--shortstat".to_owned(), ]; args.extend(commits.iter().map(Oid::to_string)); let args = args.iter().map(String::as_str).collect::>(); let text = self.git("log", &args).and_then(utf8)?; let mut stats = BTreeMap::new(); let mut current = None; for line in text.lines() { if let Ok(oid) = line.trim().parse::() { current = Some(oid); } else if let Some(oid) = current && line.contains("changed") { stats.insert(oid, DiffStat::from_shortstat(line)); } } Ok(commits .iter() .map(|commit| stats.get(commit).copied().unwrap_or_default()) .collect()) } /// Reads a blob object's bytes. fn cat_blob(&self, blob: Oid) -> Result, RepoError> { let blob = blob.to_string(); self.git("cat-file", &["blob", &blob]) } /// Produces a unified diff between two objects as text. fn diff(&self, from: Oid, to: Oid) -> Result { let from = from.to_string(); let to = to.to_string(); let bytes = self.git( "diff", &[ "--no-ext-diff", "--no-textconv", "--no-color", "--full-index", &from, &to, ], )?; utf8(bytes) } /// Computes a stable Git patch id for `patch` text. fn patch_id(&self, patch: &str) -> Result { if patch.trim().is_empty() { return Ok(PatchId::default()); } let output = self.run( "patch-id", &["--stable"], Opts { stdin: Some(patch.as_bytes()), ..Opts::default() }, )?; if !output.status.success() { return Err(RepoError::git(&output)); } let stdout = utf8(output.stdout)?; let id = stdout.split_once(' ').map_or(stdout.trim(), |(id, _)| id); Ok(PatchId(id.to_owned())) } /// Computes stable Git patch ids for many patches in one invocation. /// /// The patches are streamed to a single `git patch-id` process, separated /// by synthetic `commit` headers whose ids map output rows back to input /// positions. Every input patch must produce one output row. fn patch_ids(&self, patches: &[String]) -> Result, RepoError> { if patches.is_empty() { return Ok(Vec::new()); } let width = self.object_id_width; let mut stream = String::new(); for (index, patch) in patches.iter().enumerate() { stream.push_str(&format!("commit {index:0width$x}\n")); stream.push_str(patch); if !patch.ends_with('\n') { stream.push('\n'); } } let output = self.run( "patch-id", &["--stable"], Opts { stdin: Some(stream.as_bytes()), ..Opts::default() }, )?; if !output.status.success() { return Err(RepoError::git(&output)); } let stdout = utf8(output.stdout)?; let mut by_commit = BTreeMap::new(); for line in stdout.lines() { if let Some((id, commit)) = line.split_once(' ') { by_commit.insert(commit.trim().to_owned(), PatchId(id.to_owned())); } } let mut ids = Vec::with_capacity(patches.len()); for index in 0..patches.len() { let commit = format!("{index:0width$x}"); let id = by_commit.remove(&commit).ok_or_else(|| { RepoError::Git(format!("git patch-id returned no id for patch {index}")) })?; ids.push(id); } Ok(ids) } /// Computes a three-way merge tree and returns the resulting tree id. fn merge_tree(&self, merge_base: Oid, ours: Oid, theirs: Oid) -> Result { let merge_base = merge_base.to_string(); let ours = ours.to_string(); let theirs = theirs.to_string(); let output = self.run( "merge-tree", &["--write-tree", "--merge-base", &merge_base, &ours, &theirs], Opts::default(), )?; if output.status.success() { let stdout = String::from_utf8_lossy(&output.stdout); // On success `--write-tree` prints the created tree id as the first // line. Conflict details only appear on failing output. return stdout .lines() .next() .map(str::trim) .filter(|line| !line.is_empty()) .and_then(|line| line.parse().ok()) .ok_or_else(|| RepoError::Git("git merge-tree did not return a tree".to_owned())); } let message = RepoError::git(&output).to_string(); if output.status.code() == Some(1) { Err(RepoError::MergeConflict(message)) } else { Err(RepoError::Git(message)) } } /// Returns commits in `base..target`, oldest first, as `(id, summary)` pairs. fn commits(&self, base: &Rev, target: &Rev) -> Result, RepoError> { let range = format!("{}..{}", base.as_str(), target.as_str()); let bytes = self.git("log", &["--reverse", "--format=%H%x00%s", &range])?; let text = utf8(bytes)?; let mut commits = Vec::new(); for line in text.lines() { let Some((id, summary)) = line.split_once('\0') else { return Err(RepoError::Git( "malformed commit line from git log".to_owned(), )); }; let id = id .trim() .parse() .map_err(|_| RepoError::Git("invalid oid from git log".to_owned()))?; commits.push((id, summary.to_owned())); } Ok(commits) } /// Returns the unified diff for `commit` against its first parent. /// /// Root commits are compared against the empty tree. fn commit_diff(&self, commit: Oid) -> Result, RepoError> { let commit = commit.to_string(); let parents = self.git("show", &["-s", "--format=%P", &commit])?; let parents = utf8(parents)?; let empty_tree = match self.object_id_width { SHA1_HEX_LEN => SHA1_EMPTY_TREE, SHA256_HEX_LEN => SHA256_EMPTY_TREE, _ => unreachable!("commit_diff: unsupported object identifier width"), }; let parent = parents.split_whitespace().next().unwrap_or(empty_tree); self.git( "diff", &[ "--no-ext-diff", "--no-textconv", "--full-index", parent, &commit, ], ) } } impl WriteRepository for Repository { /// Writes `bytes` as a blob object and returns its id. fn write_blob(&self, bytes: &[u8]) -> Result { let output = self.run( "hash-object", &["-w", "--stdin"], Opts { stdin: Some(bytes), ..Opts::default() }, )?; if !output.status.success() { return Err(RepoError::git(&output)); } Oid::try_from(output.stdout.as_slice()) .map_err(|_| RepoError::Git("invalid oid from hash-object".to_owned())) } /// Applies a Git-format patch to a temporary index and returns its tree id. /// /// The temporary index is seeded from `base`, patched with /// `git apply --cached`, then written with `git write-tree`. This keeps /// acceptance updates isolated from the user's working tree and real index. fn apply_patch_to_tree(&self, base: Oid, patch: &str) -> Result { if patch.trim().is_empty() { return self.tree_id(base); } let index = TempIndex::new()?; let index_path = index.path(); let base = base.to_string(); // `read-tree` initializes the temporary index to the exact tree being // updated; subsequent Git commands use only `GIT_INDEX_FILE`. let output = self.run( "read-tree", &[&base], Opts { index: Some(index_path), ..Opts::default() }, )?; if !output.status.success() { return Err(RepoError::git(&output)); } // `--recount` lets single-hunk patches keep working after context // filtering changes hunk line counts. let output = self.run( "apply", &["--cached", "--recount", "--whitespace=nowarn", "--binary"], Opts { index: Some(index_path), stdin: Some(patch.as_bytes()), ..Opts::default() }, )?; if !output.status.success() { return Err(RepoError::patch_apply(&output)); } let output = self.run( "write-tree", &[], Opts { index: Some(index_path), ..Opts::default() }, )?; if !output.status.success() { return Err(RepoError::git(&output)); } Oid::try_from(output.stdout.as_slice()) .map_err(|_| RepoError::Git("invalid oid from write-tree".to_owned())) } /// Creates a commit with `tree` and `parent`. fn commit( &self, tree: Oid, parent: Oid, author: &str, email: &str, message: &str, ) -> Result { let tree = tree.to_string(); let parent = parent.to_string(); let output = self.run( "commit-tree", &[&tree, "-p", &parent, "-m", message], Opts { env: &[ ("GIT_AUTHOR_NAME", author), ("GIT_AUTHOR_EMAIL", email), ("GIT_COMMITTER_NAME", author), ("GIT_COMMITTER_EMAIL", email), ], ..Opts::default() }, )?; if !output.status.success() { return Err(RepoError::git(&output)); } Oid::try_from(output.stdout.as_slice()) .map_err(|_| RepoError::Git("invalid oid from commit-tree".to_owned())) } /// Moves `updated` to `commit` and deletes `deleted` in one transaction. fn update_ref_and_delete( &self, updated: &Qualified<'_>, commit: Oid, deleted: &Qualified<'_>, ) -> Result<(), RepoError> { let transaction = format!( "update {} {}\ndelete {}\n", updated.as_str(), commit, deleted.as_str() ); let output = self.run( "update-ref", &["--stdin"], Opts { stdin: Some(transaction.as_bytes()), ..Opts::default() }, )?; if !output.status.success() { return Err(RepoError::git(&output)); } Ok(()) } /// Moves `reference` to point at `commit`. fn update_ref(&self, reference: &Qualified<'_>, commit: Oid) -> Result<(), RepoError> { let commit = commit.to_string(); let output = self.run( "update-ref", &[reference.as_str(), &commit], Opts::default(), )?; if !output.status.success() { return Err(RepoError::git(&output)); } Ok(()) } } impl Repository { /// Returns the default branch reported by `origin/HEAD`, if present. fn remote_default_branch(&self) -> Result, RepoError> { let output = self.run( "symbolic-ref", &["--quiet", "--short", "refs/remotes/origin/HEAD"], Opts::default(), )?; if !output.status.success() { return Ok(None); } let name = utf8(output.stdout)?; let name = name .trim() .strip_prefix("origin/") .unwrap_or_else(|| name.trim()) .to_owned(); Ok((!name.is_empty()).then_some(name)) } } impl DiffRepository for Repository { fn diff(&self, context_lines: usize, paths: &[&Path]) -> Result, RepoError> { let context = OsString::from(format!("-U{context_lines}")); let output = self .command("diff") .args(&self.selector_args) .arg("--no-ext-diff") .arg("--no-textconv") .arg("--full-index") .arg(context) .arg("--") .args(paths) .output()?; if !output.status.success() { return Err(RepoError::git(&output)); } Ok(output.stdout) } } /// Optional execution context for a single Git invocation. #[derive(Clone, Copy, Debug, Default)] struct Opts<'a> { /// Extra environment variables. env: &'a [(&'a str, &'a str)], /// Temporary index file written via `GIT_INDEX_FILE`. index: Option<&'a Path>, /// Stdin payload, if any. stdin: Option<&'a [u8]>, } /// Temporary index file path removed when dropped. #[derive(Debug)] struct TempIndex { /// Directory holding the temporary index file. dir: PathBuf, /// Path passed through `GIT_INDEX_FILE`. path: PathBuf, } impl TempIndex { /// Creates an empty temporary index path. fn new() -> io::Result { let suffix = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_nanos(); let dir = std::env::temp_dir().join(format!( "rustik-brain-index-{}-{suffix}", std::process::id() )); fs::create_dir(&dir)?; let path = dir.join("index"); Ok(Self { dir, path }) } /// Returns the temporary index path. fn path(&self) -> &Path { &self.path } } impl Drop for TempIndex { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.dir); } } /// Returns the hexadecimal object identifier width for a Git object format. fn object_id_width(format: &str) -> Result { match format { "sha1" => Ok(SHA1_HEX_LEN), "sha256" => Ok(SHA256_HEX_LEN), format => Err(RepoError::Git(format!( "unsupported Git object format: {format}" ))), } } /// Converts bytes to a UTF-8 string. fn utf8(bytes: Vec) -> Result { String::from_utf8(bytes).map_err(|e| RepoError::Git(e.to_string())) } /// Reads a bounded file prefix and returns its first line. fn read_head(reader: &mut impl io::Read) -> Result, RepoError> { let mut bytes = Vec::with_capacity(HEAD_BYTES); let read = reader.take(HEAD_BYTES as u64).read_to_end(&mut bytes)?; if read == 0 { return Ok(None); } if let Some(end) = bytes.iter().position(|byte| *byte == b'\n') { bytes.truncate(end); } if bytes.last() == Some(&b'\r') { bytes.pop(); } Ok(Some(String::from_utf8_lossy(&bytes).into_owned())) } #[cfg(test)] mod tests { use super::*; /// Temporary Git repository removed when its test finishes. struct TestRepository { /// Repository working tree. path: PathBuf, /// Repository API under test. repository: Repository, } impl TestRepository { /// Creates a repository with Git's default initial branch. fn new() -> Self { Self::init(&[]) } /// Creates a repository with `main` as its initial branch. fn with_main_branch() -> Self { Self::init(&["-b", "main"]) } /// Creates a repository with the requested object format. fn with_object_format(object_format: &str) -> Self { let format = format!("--object-format={object_format}"); Self::init(&[&format]) } /// Initializes a repository with additional `git init` arguments. fn init(args: &[&str]) -> Self { let nonce = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_nanos(); let path = std::env::temp_dir() .join(format!("rustik-repo-test-{}-{nonce}", std::process::id())); let status = Command::new("git") .args(["init", "-q"]) .args(args) .arg(&path) .status() .unwrap(); assert!(status.success()); let repository = Repository::discover(path.clone()).unwrap(); Self { path, repository } } /// Returns the repository working tree. fn path(&self) -> &Path { &self.path } /// Writes a working-tree file. fn write(&self, path: &str, contents: &str) { fs::write(self.path.join(path), contents).unwrap(); } /// Creates an empty commit. fn commit_empty(&self, message: &str) { self.git("commit", &["-q", "--allow-empty", "-m", message]); } /// Commits the selected working-tree files. fn commit(&self, paths: &[&str], message: &str) { self.git("add", paths); self.git("commit", &["-q", "-m", message]); } /// Writes and commits one file. fn commit_file(&self, path: &str, contents: &str, message: &str) { self.write(path, contents); self.commit(&[path], message); } /// Runs a Git subcommand and requires success. fn git(&self, subcommand: &str, args: &[&str]) { let output = self .repository .run( subcommand, args, Opts { env: &[ ("GIT_AUTHOR_NAME", "Rustik Test"), ("GIT_AUTHOR_EMAIL", "rustik@example.com"), ("GIT_COMMITTER_NAME", "Rustik Test"), ("GIT_COMMITTER_EMAIL", "rustik@example.com"), ], ..Opts::default() }, ) .unwrap(); assert!(output.status.success()); } } impl std::ops::Deref for TestRepository { type Target = Repository; fn deref(&self) -> &Self::Target { &self.repository } } impl Drop for TestRepository { fn drop(&mut self) { fs::remove_dir_all(&self.path).unwrap(); } } #[test] fn branch_base_prefers_non_trunk_upstream() { let repository = TestRepository::with_main_branch(); repository.commit_empty("main"); repository.git("switch", &["-q", "-c", "integration"]); repository.commit_empty("integration"); repository.git("switch", &["-q", "-c", "feature"]); repository.git("branch", &["--set-upstream-to=integration", "feature"]); repository.commit_empty("feature"); repository.git("branch", &["aaa"]); let feature = repository .commit_id(&Rev::try_from("feature").unwrap()) .unwrap(); let target = Rev::from(feature); let integration = Rev::try_from("integration").unwrap(); assert_eq!( repository.branch_base(&target).unwrap(), Some(repository.commit_id(&integration).unwrap()) ); } #[test] fn branch_base_ignores_missing_upstream() { let repository = TestRepository::with_main_branch(); repository.commit_empty("main"); repository.git("switch", &["-q", "-c", "feature"]); repository.commit_empty("feature"); repository.git("remote", &["add", "origin", "."]); repository.git("update-ref", &["refs/remotes/origin/feature", "feature"]); repository.git("branch", &["--set-upstream-to=origin/feature", "feature"]); repository.git("update-ref", &["-d", "refs/remotes/origin/feature"]); assert_eq!( repository.config("branch.feature.remote").unwrap(), Some("origin".to_owned()) ); assert_eq!( repository.config("branch.feature.merge").unwrap(), Some("refs/heads/feature".to_owned()) ); let feature = repository .commit_id(&Rev::try_from("feature").unwrap()) .unwrap(); let target = Rev::from(feature); let main = Rev::try_from("main").unwrap(); assert_eq!( repository.branch_base(&target).unwrap(), Some(repository.commit_id(&main).unwrap()) ); } #[test] fn branch_base_missing_exact_upstream_falls_back_to_trunk() { let repository = TestRepository::with_main_branch(); repository.commit_empty("main"); repository.git("switch", &["-q", "-c", "integration"]); repository.commit_empty("integration"); repository.git("switch", &["-q", "-c", "feature"]); repository.commit_empty("feature"); repository.git("remote", &["add", "origin", "."]); repository.git("update-ref", &["refs/remotes/origin/feature", "feature"]); repository.git("branch", &["--set-upstream-to=origin/feature", "feature"]); repository.git("update-ref", &["-d", "refs/remotes/origin/feature"]); repository.git("switch", &["-q", "-c", "container"]); repository.commit_empty("container"); repository.git("branch", &["--set-upstream-to=integration", "container"]); let feature = repository .commit_id(&Rev::try_from("feature").unwrap()) .unwrap(); let target = Rev::from(feature); let main = Rev::try_from("main").unwrap(); assert_eq!( repository.branch_base(&target).unwrap(), Some(repository.commit_id(&main).unwrap()) ); } #[test] fn branch_base_exact_branch_without_upstream_falls_back_to_trunk() { let repository = TestRepository::with_main_branch(); repository.commit_empty("main"); repository.git("switch", &["-q", "-c", "feature"]); repository.commit_empty("feature"); repository.git("switch", &["-q", "-c", "container"]); repository.commit_empty("container"); repository.git("remote", &["add", "origin", "."]); repository.git( "update-ref", &["refs/remotes/origin/container", "container"], ); repository.git( "branch", &["--set-upstream-to=origin/container", "container"], ); let feature = repository .commit_id(&Rev::try_from("feature").unwrap()) .unwrap(); let target = Rev::from(feature); let main = Rev::try_from("main").unwrap(); assert_eq!( repository.branch_base(&target).unwrap(), Some(repository.commit_id(&main).unwrap()) ); } #[test] fn commit_stats_uses_merge_first_parent() { let repository = TestRepository::with_main_branch(); repository.commit_file("base", "base\n", "base"); repository.git("switch", &["-q", "-c", "feature"]); repository.commit_file("feature", "first\nsecond\n", "feature"); repository.git("switch", &["-q", "main"]); repository.commit_file("main", "main\n", "main"); repository.git("merge", &["-q", "--no-ff", "feature", "-m", "merge"]); let merge = repository .commit_id(&Rev::try_from("HEAD").unwrap()) .unwrap(); assert_eq!( repository.commit_stats(&[merge]).unwrap(), vec![DiffStat { files_changed: 1, insertions: 2, deletions: 0, }] ); } #[test] fn commit_diff_returns_root_commit_file() { let repository = TestRepository::new(); repository.commit_file("root", "root\n", "root"); let root = repository .commit_id(&Rev::try_from("HEAD").unwrap()) .unwrap(); let diff = utf8(repository.commit_diff(root).unwrap()).unwrap(); assert!(diff.starts_with("diff --git a/root b/root\nnew file mode")); assert!(diff.contains("@@ -0,0 +1 @@\n+root\n")); } #[test] fn commit_diff_uses_builtin_diff_with_external_helper_configured() { let repository = TestRepository::new(); repository.commit_file("file", "old\n", "base"); repository.commit_file("file", "new\n", "change"); repository.git( "config", &["diff.external", "printf 'external diff output\n'"], ); let head = repository .commit_id(&Rev::try_from("HEAD").unwrap()) .unwrap(); let diff = utf8(repository.commit_diff(head).unwrap()).unwrap(); assert!(diff.starts_with("diff --git a/file b/file\n")); assert!(diff.contains("@@ -1 +1 @@\n-old\n+new\n")); } #[test] fn context_diff_uses_builtin_diff_with_external_helper_configured() { let repository = TestRepository::new(); repository.commit_file("file", "old\n", "base"); repository.write("file", "new\n"); repository.git( "config", &["diff.external", "printf 'external diff output\n'"], ); let diff = utf8(DiffRepository::diff(&*repository, 3, &[Path::new("file")]).unwrap()).unwrap(); assert!( diff.starts_with("diff --git a/file b/file\n"), "external helper replaced context diff:\n{diff}" ); assert!(diff.contains("@@ -1 +1 @@\n-old\n+new\n")); } #[test] fn context_diff_reports_git_stderr() { let repository = TestRepository::new(); let selected_repository = repository .repository .with_selector_args(vec![OsString::from("invalid revision")]); let error = DiffRepository::diff(&selected_repository, 3, &[]).unwrap_err(); assert!(error.to_string().starts_with("git: ")); assert!(error.to_string().contains("invalid revision")); } #[test] fn machine_readable_diffs_ignore_textconv_drivers() { let repository = TestRepository::new(); let repository_path = repository.path(); repository.write(".gitattributes", "file diff=fixture\n"); repository.write("file", "old\n"); repository.commit(&[".gitattributes", "file"], "base"); repository.commit_file("file", "new\n", "change"); repository.git( "config", &["diff.fixture.textconv", "printf 'textconv helper output\n'"], ); let base = repository .commit_id(&Rev::try_from("HEAD^").unwrap()) .unwrap(); let head = repository .commit_id(&Rev::try_from("HEAD").unwrap()) .unwrap(); let selected_repository = Repository::new( repository_path.to_owned(), vec![OsString::from("HEAD^"), OsString::from("HEAD")], ) .unwrap(); let initial = utf8(repository.commit_diff(head).unwrap()).unwrap(); let projected = ReadRepository::diff(&*repository, base, head).unwrap(); let refetched = utf8(DiffRepository::diff(&selected_repository, 3, &[Path::new("file")]).unwrap()) .unwrap(); for (path, diff) in [ ("initial", &initial), ("projected", &projected), ("refetched", &refetched), ] { assert!( diff.starts_with("diff --git a/file b/file\n"), "textconv replaced {path} diff:\n{diff}" ); assert!( diff.contains("@@ -1 +1 @@\n-old\n+new\n"), "textconv changed {path} diff:\n{diff}" ); } } #[test] fn trunk_ignores_stale_remote_default() { let repository = TestRepository::with_main_branch(); repository.commit_empty("main"); repository.git("switch", &["-q", "-c", "integration"]); repository.commit_empty("integration"); repository.git( "symbolic-ref", &[ "refs/remotes/origin/HEAD", "refs/remotes/origin/integration", ], ); let branches = repository.branches().unwrap(); assert_eq!( repository.trunk(&branches).unwrap().unwrap().name, "integration" ); repository.git( "symbolic-ref", &["refs/remotes/origin/HEAD", "refs/remotes/origin/master"], ); assert_eq!(repository.trunk(&branches).unwrap().unwrap().name, "main"); } #[test] fn commit_metadata_parses_four_fields() { let record = [ "0123456789abcdef0123456789abcdef01234567", "Alice", "-10", "20", ] .join("\0"); let (id, author, recency) = Repository::parse_commit_metadata(&record).unwrap(); assert_eq!( id, "0123456789abcdef0123456789abcdef01234567".parse().unwrap() ); assert_eq!(author, "Alice"); assert_eq!(recency, CommitTime { seconds: 20 }); } #[test] fn commit_metadata_rejects_extra_fields() { let record = [ "0123456789abcdef0123456789abcdef01234567", "Alice", "10", "20", "extra", ] .join("\0"); let error = Repository::parse_commit_metadata(&record).unwrap_err(); assert_eq!( error.to_string(), "git: malformed commit metadata line from git log" ); } #[test] fn patch_ids_map_sha1_and_sha256_streams() { let patches = [ "diff --git a/a b/a\n--- a/a\n+++ b/a\n@@ -1 +1 @@\n-old\n+new\n".to_owned(), "diff --git a/b b/b\n--- a/b\n+++ b/b\n@@ -0,0 +1 @@\n+line\n".to_owned(), ]; for object_format in ["sha1", "sha256"] { let repository = TestRepository::with_object_format(object_format); let ids = repository.patch_ids(&patches).unwrap(); assert_eq!(ids.len(), patches.len()); assert!(ids.iter().all(|id| !id.as_str().is_empty())); assert_ne!(ids[0], ids[1]); assert!(repository.patch_ids(&[String::new()]).is_err()); } } #[test] fn range_diff_pairs_rewritten_commits() { let repository = TestRepository::with_main_branch(); repository.commit_file("file", "base\n", "base"); let base = repository .commit_id(&Rev::try_from("HEAD").unwrap()) .unwrap(); repository.git("switch", &["-q", "-c", "old"]); repository.commit_file("file", "base\nold\nshared\n", "change"); let old = repository .commit_id(&Rev::try_from("HEAD").unwrap()) .unwrap(); repository.git("switch", &["-q", "main"]); repository.commit_file("other", "upstream\n", "upstream"); let new_base = repository .commit_id(&Rev::try_from("HEAD").unwrap()) .unwrap(); repository.git("switch", &["-q", "-c", "new"]); let old_arg = old.to_string(); repository.git("cherry-pick", &[&old_arg]); let new = repository .commit_id(&Rev::try_from("HEAD").unwrap()) .unwrap(); let pairs = repository.range_diff(base, old, new_base, new).unwrap(); assert_eq!(pairs.get(&old), Some(&new)); } }