# Merge

> Three-way tree merge and merge-base helpers in the diff and revwalk domains.

Merge **orchestration** (sequencer state, hooks, editors, messages) stays in `grit-cli`. The library exposes tree and index transforms embedders and porcelain reuse:

- [`RevWalk::merge_bases`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.merge_bases) and [`RevWalk::is_ancestor`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.is_ancestor) — common ancestors and ancestor checks.
- [`merge::merge_trees`](https://docs.rs/grit-lib/latest/grit_lib/merge/merge_trees/index.html) — rename-aware three-way tree merge ([`merge_trees_three_way`](https://docs.rs/grit-lib/latest/grit_lib/merge/merge_trees/fn.merge_trees_three_way.html)), conflict-marker blobs, and [`TreeMergeOutput`](https://docs.rs/grit-lib/latest/grit_lib/merge/merge_trees/struct.TreeMergeOutput.html).
- [`porcelain::merge`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/index.html) — fast-forward/octopus index composition, [`predict_merge`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/enum.MergePrediction.html) (in-memory conflict check via the ODB overlay), [`write_merge_tree`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/struct.WrittenMergeTree.html) (stored merge tree), and checkout helpers the CLI calls.

When two commits have several merge bases (criss-cross history), [`predict_merge`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/enum.MergePrediction.html), [`write_merge_tree`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/struct.WrittenMergeTree.html) and [`integrate_branch`](https://docs.rs/grit-lib/latest/grit_lib/merge/struct.Merge.html#method.integrate_into_branch) merge the bases into one virtual base and merge against that, as Git's recursive and ort strategies do. The bases are taken oldest first, in the order [`RevWalk::merge_bases`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.merge_bases) with `MergeBaseMode::All` reports them (equal commit dates keep Git's order). Content conflicts between the bases stay in the virtual base as nested conflict markers. Binary, modify/delete and symlink conflicts keep the older version, and the caller's `MergeFavor` applies only to the final merge. A single merge base is a plain three-way merge. `merge_trees_three_way` itself always takes one explicit base tree.

Pass explicit [`MergeFavor`](https://docs.rs/grit-lib/latest/grit_lib/diff/merge_file/enum.MergeFavor.html) and [`WhitespaceMergeOptions`](https://docs.rs/grit-lib/latest/grit_lib/merge/merge_trees/struct.WhitespaceMergeOptions.html) into tree merges; pass identity and timestamps into commit-writing porcelain.

## Predicting versus writing a merge

Both functions take two commits and [`MergePredictionOptions`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/struct.MergePredictionOptions.html), never touch refs, the index or the working tree, and work in bare repositories.

| Function | Objects written | Returns |
| --- | --- | --- |
| [`predict_merge`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/enum.MergePrediction.html) | None | Up to date, fast-forward, clean (with the tree id), conflicts, or unrelated |
| [`write_merge_tree`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/struct.WrittenMergeTree.html) | Every new tree and blob of the merge | [`WrittenMergeTree`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/struct.WrittenMergeTree.html): stored tree, conflicts, unmerged stages |

The tree id in [`MergePrediction::Clean`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/enum.MergePrediction.html) is the id `git merge-tree --write-tree` prints, but the tree is **not stored**: committing, diffing or reading it fails with `ObjectNotFound`. Use `predict_merge` to answer "would this merge cleanly?" cheaply (merge queues, `grit merge --check`). Use `write_merge_tree` when you need the result itself: it is the library form of `git merge-tree --write-tree`. A clean result can be committed straight away with `NewCommit::new(tree, ..).with_parents(vec![ours, theirs])`. On conflicts the stored tree holds conflict markers in the conflicted files, and [`WrittenMergeTree::stages`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/struct.WrittenMergeTree.html) lists the `mode`, `oid`, `stage` and `path` rows Git prints after the tree id. Set `ours_label` and `theirs_label` to choose the conflict-marker labels.

`write_merge_tree` always merges (the fast-forward option is ignored), merges several merge bases into a virtual base first (stage 1 entries then come from it, as with `git merge-tree`), and refuses commits with no common ancestor with `Error::UnrelatedHistories` unless `allow_unrelated_histories` is set.

## Directory renames

When one side moves every file out of a directory and the other side adds a file inside it, the new file most likely belongs in the directory's new home. Tree merges detect this the way Git's `ort` merge does, controlled by [`DirectoryRenameMode`](https://docs.rs/grit-lib/latest/grit_lib/merge/merge_trees/enum.DirectoryRenameMode.html):

| Mode | `merge.directoryRenames` | Result |
| --- | --- | --- |
| [`Conflict`](https://docs.rs/grit-lib/latest/grit_lib/merge/merge_trees/enum.DirectoryRenameMode.html#variant.Conflict) (default) | `conflict` or unset | The file moves to the new directory and stays unmerged at the adding side's stage (stage 3 when theirs added it), so the merge stops for confirmation. |
| [`Apply`](https://docs.rs/grit-lib/latest/grit_lib/merge/merge_trees/enum.DirectoryRenameMode.html#variant.Apply) | `true` | The file moves and the merge is clean. |
| [`Off`](https://docs.rs/grit-lib/latest/grit_lib/merge/merge_trees/enum.DirectoryRenameMode.html#variant.Off) | `false` | The file stays in the old directory. |

A directory counts as renamed only when the side removed it entirely; the destination is the directory that received the most of its files, and a tie is a split that moves nothing. A destination path the adding side already uses, or that several new files would share, blocks the move; a file the base or the renaming side has at the destination is instead three-way merged with the moved file there. Splits and blocked moves are conflicts in `Conflict` and `Apply` mode even though no index entry is unmerged. All of them are listed in [`TreeMergeOutput::directory_rename_conflicts`](https://docs.rs/grit-lib/latest/grit_lib/merge/merge_trees/struct.TreeMergeOutput.html#structfield.directory_rename_conflicts) and reported by [`conflicts_from_tree_merge`](https://docs.rs/grit-lib/latest/grit_lib/operation/fn.conflicts_from_tree_merge.html) as the `directory_rename_*` [`ConflictKind`](https://docs.rs/grit-lib/latest/grit_lib/operation/enum.ConflictKind.html)s.

[`merge_trees_three_way`](https://docs.rs/grit-lib/latest/grit_lib/merge/merge_trees/fn.merge_trees_three_way.html) takes the mode as an argument; read the configured one with [`DirectoryRenameMode::from_repo`](https://docs.rs/grit-lib/latest/grit_lib/merge/merge_trees/enum.DirectoryRenameMode.html#method.from_repo), which fails with [`ConfigError::InvalidDirectoryRenames`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.ConfigError.html#variant.InvalidDirectoryRenames) for an unknown value. [`MergePredictionOptions::directory_renames`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/struct.MergePredictionOptions.html#structfield.directory_renames) and [`MergeOptions::directory_renames`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/struct.MergeOptions.html#structfield.directory_renames) override the config for one merge; pick, revert, rebase and history edits always use the config.

## Example

The program resolves `ours` and `theirs` refs, stores the merge with `write_merge_tree`, prints the merged tree oid (compare with `git merge-tree --write-tree`) and, when the merge is clean, commits it with both parents:

```rust
//! Stored three-way merge (`write_merge_tree`) compared with `git merge-tree --write-tree`.
//!
//! Source for the library guide "Merge" page (included in the docs site).

use anyhow::Result;
use grit_lib::config::environment::RepositoryOptions;
use grit_lib::ident::Signature;
use grit_lib::merge::MergePredictionOptions;
use grit_lib::objects::{NewCommit, ObjectId};
use grit_lib::repo::Repository;
use grit_lib::revwalk::ResolveOptions;
use std::path::{Path, PathBuf};
use time::OffsetDateTime;

fn open_repo(root: &Path) -> Result<Repository> {
    let git_dir = if root.join(".git").is_dir() {
        root.join(".git")
    } else {
        root.to_path_buf()
    };
    let work_tree = if root.join(".git").is_dir() {
        Some(root)
    } else {
        None
    };
    let mut opts = RepositoryOptions::from_process();
    if let Some(wt) = work_tree {
        opts = opts.with_work_tree(wt);
    }
    Ok(Repository::open(&git_dir, &opts)?)
}

fn main() -> Result<()> {
    let root = std::env::args()
        .nth(1)
        .map(PathBuf::from)
        .or_else(|| std::env::current_dir().ok())
        .ok_or_else(|| anyhow::anyhow!("missing repository path"))?;
    let repo = open_repo(&root)?;

    let ours: ObjectId = repo.revwalk().resolve("ours", &ResolveOptions::default())?;
    let theirs: ObjectId = repo
        .revwalk()
        .resolve("theirs", &ResolveOptions::default())?;

    // Merges over the first merge base and stores the result, like `git merge-tree --write-tree`.
    let merged = repo
        .merge()
        .write_tree(ours, theirs, &MergePredictionOptions::default())?;

    println!("merged_tree={}", merged.tree.to_hex());
    println!("conflicted_paths={}", merged.conflicts.len());
    if merged.is_clean() {
        let committer = Signature::new(
            "Guide",
            "guide@example.com",
            OffsetDateTime::from_unix_timestamp(1_700_000_000)?,
        )?;
        let commit = repo.objects().write_commit(
            &NewCommit::new(
                merged.tree,
                committer.clone(),
                committer,
                "Merge theirs into ours",
            )
            .with_parents(vec![ours, theirs]),
        )?;
        println!("merge_commit={}", commit.to_hex());
    }

    Ok(())
}
```

The integration test builds non-conflicting `ours` / `theirs` branches, asserts the merged tree matches Git’s oracle, and runs `git fsck --strict` on the resulting merge commit.

## Integrating a branch (`integrate_branch`)

[`integrate_branch`](https://docs.rs/grit-lib/latest/grit_lib/merge/struct.Merge.html#method.integrate_into_branch) merges one commit into a local branch and updates the index and work tree (or records merge-in-progress state on conflicts). Pass `into_ref` as either a full ref (for example `refs/heads/main`) or a short branch name (for example `main` or `feature/topic`); short names map to `refs/heads/{name}` and missing branches return [`BranchError::NotFound`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/branch/enum.BranchError.html#variant.NotFound). The `label` argument names the other side in the default merge message (`Merge {label}` unless [`MergeOptions::message`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/struct.MergeOptions.html#structfield.message) overrides it) and in branch reflog lines (`merge {label}`, or `merge {label}: fast-forward` on fast-forward).

## Typed merge errors ([`MergeError`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.MergeError.html))

Branch integration, [`continue_merge`](https://docs.rs/grit-lib/latest/grit_lib/merge/struct.Merge.html#method.continue_sequence), and replay sequencing return [`Error::Merge`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#variant.Merge) wrapping [`MergeError`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.MergeError.html). Stable [`kind_name`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.MergeError.html#method.kind_name) slugs match the CLI `--json` error `kind` field (for example `not_fast_forward`, `unrelated_histories`, `continue_unmerged_paths`, `operation_in_progress`). Common variants:

| Variant | When |
| --- | --- |
| [`NotFastForward`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.MergeError.html#variant.NotFastForward) | [`FastForwardPolicy::Only`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/enum.FastForwardPolicy.html#variant.Only) but histories diverged |
| [`UnrelatedHistories`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.MergeError.html#variant.UnrelatedHistories) | No merge base and `allow_unrelated` is false |
| [`ContinueUnmergedPaths`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.MergeError.html#variant.ContinueUnmergedPaths) | [`continue_merge`](https://docs.rs/grit-lib/latest/grit_lib/merge/struct.Merge.html#method.continue_sequence) with conflict stages still in the index |
| [`NoMergeInProgress`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.MergeError.html#variant.NoMergeInProgress) | Continue/abort/skip with no active merge |
| [`OperationInProgress`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.MergeError.html#variant.OperationInProgress) | Another paused operation (merge, pick, rebase, …) blocks the call |

These arrive as [`Error::Merge`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#variant.Merge); repository read, object, and I/O failures arrive as their own area variants of the umbrella [`Error`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html).

## Integrating into detached `HEAD` (`integrate_detached_head`)

[`Merge::integrate`](https://docs.rs/grit-lib/latest/grit_lib/merge/struct.Merge.html#method.integrate) with [`MergeRequest::Detached { into_oid }`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/struct.MergeOptions.html) takes the current detached tip instead of a branch ref. Outcomes, conflict handling, hooks, and [`MergeOptions`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/struct.MergeOptions.html) match [`Merge::integrate_into_branch`](https://docs.rs/grit-lib/latest/grit_lib/merge/struct.Merge.html#method.integrate_into_branch), but only `HEAD` moves on a fast-forward or merge commit; no `refs/heads/*` ref is updated. Reflog lines use `merge {label}` / `merge {label}: fast-forward` on `HEAD` only.
