//! Merges and merge conflicts (M4.8): merging a branch into the current //! one, aborting a merge, the three versions of a conflicted file and //! marking files resolved. //! //! - [`Repo::merge`] runs `git merge --no-edit` (hooks run, 120 s). A merge //! that stops on conflicts is not an error: it returns the conflicted //! paths, read from the index's unmerged entries (`ls-files -u -z`). //! - [`Repo::conflict_versions`] reads the index stages of a conflicted //! file: `:1:` (the common ancestor), `:2:` (ours, the current branch) and //! `:3:` (theirs, the branch being merged), as stored, like //! [`Repo::show`]. //! - [`Repo::mark_resolved`] stages the files (`add -A`), which removes the //! unmerged entries; a file deleted in the work tree is staged as deleted. //! - [`Repo::merge_abort`] runs `git merge --abort`. use crate::VcsError; use crate::repo::{Contents, FILE_CAP, Repo, SMALL_CAP, check_name, decode}; use crate::runner::{Call, HOOK_TIMEOUT}; /// How a merge ended. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MergeResult { /// HEAD moved: a merge commit or a fast-forward. Merged, /// Nothing to merge: the branch is already contained in HEAD. UpToDate, /// The merge stopped on conflicts; resolve them and commit, or abort. Conflicts, } /// What [`Repo::merge`] did. #[derive(Debug, Clone, PartialEq, Eq)] pub struct MergeOutcome { /// How it ended. pub result: MergeResult, /// Project-relative conflicted paths, sorted; empty unless /// [`MergeResult::Conflicts`]. pub conflicts: Vec, } /// The versions of a conflicted file in the index. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct ConflictVersions { /// The common ancestor (`:1:`); `None` when the file was added on both /// sides. pub base: Option, /// The current branch's version (`:2:`); `None` when deleted there. pub ours: Option, /// The merged branch's version (`:3:`); `None` when deleted there. pub theirs: Option, /// One of the versions is binary (texts are then all `None`). pub binary: bool, /// One of the versions is larger than [`FILE_CAP`] (texts are then all /// `None`). pub too_large: bool, } /// One line of `git cat-file --batch-check`. #[derive(Debug, Clone, PartialEq, Eq)] pub enum CheckLine { /// The object does not exist. Missing, /// An object: its id, type and size in bytes. Object { /// The object id. oid: String, /// `blob`, `tree`, `commit` (a submodule) or `tag`. kind: String, /// Size in bytes. size: usize, }, } /// Reads one line of `git cat-file --batch-check` (` `, /// or ` missing`). /// /// # Returns /// `None` when the line is neither. pub fn parse_check_line(line: &str) -> Option { let line = line.trim_end_matches(['\r', '\n']); if line.ends_with(" missing") || line.ends_with(" ambiguous") { return Some(CheckLine::Missing); } let mut fields = line.rsplitn(3, ' '); let size = fields.next()?.parse().ok()?; let kind = fields.next()?.to_string(); let oid = fields.next()?.to_string(); if oid.is_empty() || oid.contains(' ') || kind.is_empty() { return None; } Some(CheckLine::Object { oid, kind, size }) } /// The paths of `git ls-files -u -z` output (` \t` /// records), each once, sorted. pub fn parse_unmerged(bytes: &[u8]) -> Vec { let mut paths: Vec = bytes .split(|b| *b == 0) .filter_map(|record| { let tab = record.iter().position(|b| *b == b'\t')?; let path = record.get(tab + 1..)?; (!path.is_empty()).then(|| String::from_utf8_lossy(path).into_owned()) }) .collect(); paths.sort(); paths.dedup(); paths } impl Repo { /// The commit HEAD points to; `None` before the first commit. fn head_commit(&self) -> Result, VcsError> { let output = self.run(Call::read( self.root(), &["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], 4096, ))?; Ok(output .success() .then(|| String::from_utf8_lossy(&output.stdout).trim().to_string())) } /// Whether a merge is in progress (`MERGE_HEAD` exists). /// /// # Errors /// The runner's errors. pub fn merging(&self) -> Result { Ok(self .run(Call::read( self.root(), &["rev-parse", "--verify", "--quiet", "MERGE_HEAD"], 4096, ))? .success()) } /// Unmerged paths in the index, project-relative and sorted (paths /// outside the project are left out). /// /// # Errors /// The runner's errors or git's refusal. pub fn unmerged(&self) -> Result, VcsError> { let output = self .run(Call::read( self.root(), &["ls-files", "-u", "-z"], SMALL_CAP, ))? .checked()?; Ok(parse_unmerged(&output.stdout) .into_iter() .filter_map(|path| self.from_repo_path(&path)) .collect()) } /// Merges `branch` into the current branch (`git merge --no-edit`; a /// fast-forward when possible, git's default). Hooks run (120 s). /// /// # Returns /// [`MergeResult::Conflicts`] with the conflicted paths when git stopped /// on conflicts; the work tree then holds the conflict markers. /// /// # Errors /// [`VcsError::InvalidName`]; [`VcsError::Git`] when a merge is already /// in progress or files are unmerged, or when git refuses (an unknown /// branch, local changes that would be overwritten, no commit yet); /// git's message is passed on. pub fn merge(&self, branch: &str) -> Result { check_name(branch)?; let _guard = self.lock(); if self.merging()? || !self.unmerged()?.is_empty() { return Err(VcsError::Git( "a merge is in progress: resolve its conflicts and commit, or abort it first" .into(), )); } let before = self.head_commit()?; let output = self.run( Call::write( self.root(), &[ "merge", "--no-edit", "--no-progress", "--end-of-options", branch, ], ) .timeout(HOOK_TIMEOUT), )?; if output.success() { let result = if self.head_commit()? == before { MergeResult::UpToDate } else { MergeResult::Merged }; return Ok(MergeOutcome { result, conflicts: Vec::new(), }); } let conflicts = self.unmerged()?; if conflicts.is_empty() && !self.merging()? { return Err(VcsError::Git(output.message())); } Ok(MergeOutcome { result: MergeResult::Conflicts, conflicts, }) } /// Aborts the merge in progress (`git merge --abort`): the work tree /// and index go back to the state before the merge. /// /// # Errors /// [`VcsError::Git`] when no merge is in progress, or git's refusal. pub fn merge_abort(&self) -> Result<(), VcsError> { let _guard = self.lock(); self.run(Call::write(self.root(), &["merge", "--abort"]))? .checked()?; Ok(()) } /// The three index versions of a conflicted file, as stored (no /// filters, no line-ending conversion). /// /// # Errors /// [`VcsError::InvalidPath`]; [`VcsError::Git`] when the file is not in /// conflict; the runner's errors. pub fn conflict_versions(&self, path: &str) -> Result { let repo_path = self.to_repo_path(path)?; let objects = format!(":1:{repo_path}\n:2:{repo_path}\n:3:{repo_path}\n"); let output = self .run( Call::read(self.root(), &["cat-file", "--batch-check"], SMALL_CAP) .stdin(objects.into_bytes()), )? .checked()?; let text = String::from_utf8_lossy(&output.stdout); let lines: Vec = text .lines() .map(|line| parse_check_line(line).ok_or_else(|| VcsError::BadOutput(line.to_string()))) .collect::>()?; if lines.len() != 3 { return Err(VcsError::BadOutput(text.to_string())); } if lines.iter().all(|line| *line == CheckLine::Missing) { return Err(VcsError::Git(format!("{path} is not in conflict"))); } let mut versions = ConflictVersions::default(); let mut texts = Vec::with_capacity(3); for line in &lines { let CheckLine::Object { oid, kind, size } = line else { texts.push(None); continue; }; if kind != "blob" { versions.binary = true; texts.push(None); continue; } if *size > FILE_CAP { versions.too_large = true; texts.push(None); continue; } let blob = self .run(Call::read( self.root(), &["cat-file", "blob", oid], FILE_CAP, ))? .checked()?; let Contents { text, binary, .. } = decode(blob.stdout); versions.binary |= binary; texts.push(text); } if versions.binary || versions.too_large { return Ok(versions); } let mut texts = texts.into_iter(); versions.base = texts.next().flatten(); versions.ours = texts.next().flatten(); versions.theirs = texts.next().flatten(); Ok(versions) } /// Marks files resolved by staging them (`add -A`): the unmerged index /// entries go away; a file deleted in the work tree is staged as /// deleted. Committing then concludes the merge. /// /// # Errors /// [`VcsError::InvalidPath`], or git's refusal. pub fn mark_resolved(&self, paths: &[String]) -> Result<(), VcsError> { self.stage(paths) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; use proptest::prelude::*; #[test] fn reads_check_lines() { assert_eq!( parse_check_line(":1:a b.php missing"), Some(CheckLine::Missing) ); assert_eq!( parse_check_line("0123abcd blob 42\n"), Some(CheckLine::Object { oid: "0123abcd".into(), kind: "blob".into(), size: 42 }) ); assert_eq!(parse_check_line("garbage"), None); assert_eq!(parse_check_line("a b c d"), None); } #[test] fn reads_unmerged_paths_once_each() { let out = b"100644 aaa 1\tsrc/a b.php\x00100644 bbb 2\tsrc/a b.php\x00100644 ccc 3\tsrc/a b.php\x00100644 ddd 2\tREADME\x00"; assert_eq!(parse_unmerged(out), vec!["README", "src/a b.php"]); assert!(parse_unmerged(b"").is_empty()); assert!(parse_unmerged(b"no tab here\0").is_empty()); } proptest! { #[test] fn parsers_never_panic(bytes in proptest::collection::vec(any::(), 0..256)) { let _ = parse_unmerged(&bytes); let _ = parse_check_line(&String::from_utf8_lossy(&bytes)); } } }