gix 0.91.0

Interact with git repositories just like git would
Documentation
use gix_merge::blob::builtin_driver::text;
use gix_object::Write;

use crate::{
    Error, Repository, Result,
    config::{cache::util::ApplyLeniencyDefault, tree},
    prelude::ObjectIdExt,
};

/// Merge-utilities
impl Repository {
    /// Create a resource cache that can hold the three resources needed for a three-way merge. `worktree_roots`
    /// determines which side of the merge is read from the worktree, or from which worktree.
    ///
    /// The platform can be used to set up resources and finally perform a merge among blobs.
    ///
    /// Note that the current index is used for attribute queries.
    pub fn merge_resource_cache(
        &self,
        worktree_roots: gix_merge::blob::pipeline::WorktreeRoots,
    ) -> Result<gix_merge::blob::Platform> {
        let index = self.index_or_load_from_head_or_empty()?;
        let mode = {
            let renormalize = tree::Merge::RENORMALIZE
                .enrich_error(self.config.resolved.boolean(tree::Merge::RENORMALIZE))
                .with_lenient_default(self.config.lenient_config)?
                .unwrap_or_default();
            if renormalize {
                gix_merge::blob::pipeline::Mode::Renormalize
            } else {
                gix_merge::blob::pipeline::Mode::ToGit
            }
        };
        let attrs = self
            .attributes_only(
                &index,
                if worktree_roots.is_unset() {
                    gix_worktree::stack::state::attributes::Source::IdMapping
                } else {
                    gix_worktree::stack::state::attributes::Source::WorktreeThenIdMapping
                },
            )?
            .inner;
        let filter = gix_filter::Pipeline::new(
            self.command_context()?,
            self.object_hash(),
            crate::filter::Pipeline::options(self)?,
        );
        // Git's diff size threshold does not change how text is merged.
        let filter = gix_merge::blob::Pipeline::new(worktree_roots, filter, Default::default());
        let options = gix_merge::blob::platform::Options {
            default_driver: self.config.resolved.string(tree::Merge::DEFAULT),
        };
        let drivers = self.config.merge_drivers()?;
        Ok(gix_merge::blob::Platform::new(filter, mode, attrs, drivers, options))
    }

    /// Return options for use with [`gix_merge::blob::PlatformRef::merge()`], accessible through
    /// [merge_resource_cache()](Self::merge_resource_cache).
    pub fn blob_merge_options(&self) -> Result<gix_merge::blob::platform::merge::Options> {
        Ok(gix_merge::blob::platform::merge::Options {
            is_virtual_ancestor: false,
            resolve_binary_with: None,
            text: gix_merge::blob::builtin_driver::text::Options {
                diff_algorithm: self.diff_algorithm()?,
                conflict: text::Conflict::Keep {
                    style: self
                        .config
                        .resolved
                        .string(tree::Merge::CONFLICT_STYLE)
                        .map(|value| {
                            tree::Merge::CONFLICT_STYLE
                                .try_into_conflict_style(value)
                                .with_lenient_default(self.config.lenient_config)
                        })
                        .transpose()?
                        .unwrap_or_default(),
                    marker_size: text::Conflict::DEFAULT_MARKER_SIZE.try_into().unwrap(),
                },
            },
        })
    }

    /// Read all relevant configuration options to instantiate options for use in [`merge_trees()`](Self::merge_trees).
    pub fn tree_merge_options(&self) -> Result<crate::merge::tree::Options> {
        let (mut rewrites, is_configured) = crate::diff::utils::new_rewrites_inner(
            &self.config.resolved,
            self.config.lenient_config,
            &tree::Merge::RENAMES,
            &tree::Merge::RENAME_LIMIT,
        )?;
        if !is_configured {
            rewrites = Some(Default::default());
        }
        Ok(gix_merge::tree::Options {
            rewrites,
            directory_renames: if rewrites.is_some() {
                tree::Merge::DIRECTORY_RENAMES
                    .try_into_directory_renames(self.config.resolved.boolean(tree::Merge::DIRECTORY_RENAMES))
                    .with_lenient_default(self.config.lenient_config)?
            } else {
                gix_merge::tree::DirectoryRenames::Disabled
            },
            blob_merge: self.blob_merge_options()?,
            blob_merge_command_ctx: self.command_context()?,
            fail_on_conflict: None,
            marker_size_multiplier: 0,
            symlink_conflicts: None,
            tree_conflicts: None,
        }
        .into())
    }

    /// Merge `our_tree` and `their_tree` together, assuming they have the same `ancestor_tree`, to yield a new tree
    /// which is provided as [tree editor](crate::object::tree::Editor) to inspect and finalize results at will.
    /// No change to the worktree or index is made, but objects may be written to the object database as merge results
    /// are stored.
    /// If these changes should not be observable outside of this instance, consider [enabling object memory](Self::with_object_memory).
    ///
    /// Note that `ancestor_tree` can be the [empty tree hash](gix_hash::ObjectId::empty_tree) to indicate no common ancestry.
    ///
    /// Available local submodule repositories provide history for resolving gitlink updates. Missing repositories
    /// or commits leave a submodule conflict; errors reading available history are returned.
    ///
    /// `labels` are typically chosen to identify the refs or names for `our_tree` and `their_tree` and `ancestor_tree` respectively.
    ///
    /// `options` should be initialized with [`tree_merge_options()`](Self::tree_merge_options()).
    ///
    /// ### Performance
    ///
    /// It's highly recommended to [set an object cache](Repository::compute_object_cache_size_for_tree_diffs)
    /// to avoid extracting the same object multiple times.
    pub fn merge_trees(
        &self,
        ancestor_tree: impl AsRef<gix_hash::oid>,
        our_tree: impl AsRef<gix_hash::oid>,
        their_tree: impl AsRef<gix_hash::oid>,
        labels: gix_merge::blob::builtin_driver::text::Labels<'_>,
        options: crate::merge::tree::Options,
    ) -> Result<crate::merge::tree::Outcome<'_>> {
        let mut diff_cache = self.diff_resource_cache_for_tree_diff()?;
        let mut blob_merge = self.merge_resource_cache(Default::default())?;
        let mut submodule = submodule::query(self);
        let context = gix_merge::tree::Context {
            submodule: Some(&mut submodule),
        };
        let gix_merge::tree::Outcome {
            tree,
            index,
            conflicts,
            failed_on_first_unresolved_conflict,
        } = gix_merge::tree(
            ancestor_tree.as_ref(),
            our_tree.as_ref(),
            their_tree.as_ref(),
            labels,
            self,
            |buf| self.write_buf(gix_object::Kind::Blob, buf),
            &mut Default::default(),
            &mut diff_cache,
            &mut blob_merge,
            context,
            options.into(),
        )?;

        let validate = self.config.protect_options()?;
        Ok(crate::merge::tree::Outcome {
            tree: crate::object::tree::Editor {
                inner: tree,
                validate,
                repo: self,
            },
            index,
            conflicts,
            failed_on_first_unresolved_conflict,
        })
    }

    /// Merge `our_commit` and `their_commit` together to yield a new tree which is provided as [tree editor](crate::object::tree::Editor)
    /// to inspect and finalize results at will. The merge-base will be determined automatically between both commits, along with special
    /// handling in case there are multiple merge-bases.
    /// No change to the worktree or index is made, but objects may be written to the object database as merge results
    /// are stored.
    /// If these changes should not be observable outside of this instance, consider [enabling object memory](Self::with_object_memory).
    ///
    /// `labels` are typically chosen to identify the refs or names for `our_commit` and `their_commit`, with the ancestor being set
    /// automatically as part of the merge-base handling.
    ///
    /// Submodule histories are resolved as in [`Self::merge_trees()`], including while constructing virtual merge-bases.
    ///
    /// `options` should be initialized with [`Repository::tree_merge_options().into()`](Self::tree_merge_options()).
    ///
    /// ### Performance
    ///
    /// It's highly recommended to [set an object cache](Repository::compute_object_cache_size_for_tree_diffs)
    /// to avoid extracting the same object multiple times.
    pub fn merge_commits(
        &self,
        our_commit: impl Into<gix_hash::ObjectId>,
        their_commit: impl Into<gix_hash::ObjectId>,
        labels: gix_merge::blob::builtin_driver::text::Labels<'_>,
        options: crate::merge::commit::Options,
    ) -> Result<crate::merge::commit::Outcome<'_>> {
        let mut diff_cache = self.diff_resource_cache_for_tree_diff()?;
        let mut blob_merge = self.merge_resource_cache(Default::default())?;
        let commit_graph = self.commit_graph_if_enabled()?;
        let mut graph = self.revision_graph(commit_graph.as_ref());
        let mut submodule = submodule::query(self);
        let context = gix_merge::tree::Context {
            submodule: Some(&mut submodule),
        };
        let gix_merge::commit::Outcome {
            tree_merge:
                gix_merge::tree::Outcome {
                    tree,
                    index,
                    conflicts,
                    failed_on_first_unresolved_conflict,
                },
            merge_base_tree_id,
            merge_bases,
            virtual_merge_bases,
        } = gix_merge::commit(
            our_commit.into(),
            their_commit.into(),
            labels,
            &mut graph,
            &mut diff_cache,
            &mut blob_merge,
            self,
            &mut |id| id.to_owned().attach(self).shorten_or_id().to_string(),
            context,
            options.into(),
        )?;

        let validate = self.config.protect_options()?;
        let tree_merge = crate::merge::tree::Outcome {
            tree: crate::object::tree::Editor {
                inner: tree,
                validate,
                repo: self,
            },
            index,
            conflicts,
            failed_on_first_unresolved_conflict,
        };
        Ok(crate::merge::commit::Outcome {
            tree_merge,
            merge_base_tree_id,
            merge_bases,
            virtual_merge_bases,
        })
    }

    /// Create a single virtual merge-base by merging all `merge_bases` into one.
    /// If the list is empty, an error will be returned as the histories are then unrelated.
    /// If there is only one commit in the list, it is returned directly with this case clearly marked in the outcome.
    ///
    /// Note that most of `options` are overwritten to match the requirements of a merge-base merge, but they can be useful
    /// to control the diff algorithm or rewrite tracking, for example.
    ///
    /// This method is useful in conjunction with [`Self::merge_trees()`], as the ancestor tree can be produced here.
    // TODO: test
    pub fn virtual_merge_base(
        &self,
        merge_bases: impl IntoIterator<Item = impl Into<gix_hash::ObjectId>>,
        options: crate::merge::tree::Options,
    ) -> Result<crate::merge::virtual_merge_base::Outcome<'_>> {
        let commit_graph = self.commit_graph_if_enabled()?;
        let mut graph = self.revision_graph(commit_graph.as_ref());
        self.virtual_merge_base_with_graph(merge_bases, &mut graph, options)
    }

    /// Like [`Self::virtual_merge_base()`], but also allows to reuse a `graph` for faster merge-base calculation,
    /// particularly if `graph` was used to find the `merge_bases`.
    pub fn virtual_merge_base_with_graph(
        &self,
        merge_bases: impl IntoIterator<Item = impl Into<gix_hash::ObjectId>>,
        graph: &mut gix_revwalk::Graph<'_, '_, gix_revwalk::graph::Commit<gix_revision::merge_base::Flags>>,
        options: crate::merge::tree::Options,
    ) -> Result<crate::merge::virtual_merge_base::Outcome<'_>> {
        let mut merge_bases: Vec<_> = merge_bases.into_iter().map(Into::into).collect();
        let first = merge_bases
            .pop()
            .ok_or_else(|| Error::from_error(gix_error::message("No commit was provided as merge-base")))?;
        let Some(second) = merge_bases.pop() else {
            let tree_id = self.find_commit(first)?.tree_id()?;
            let commit_id = first.attach(self);
            return Ok(crate::merge::virtual_merge_base::Outcome {
                virtual_merge_bases: Vec::new(),
                commit_id,
                tree_id,
            });
        };

        let mut diff_cache = self.diff_resource_cache_for_tree_diff()?;
        let mut blob_merge = self.merge_resource_cache(Default::default())?;
        let mut submodule = submodule::query(self);
        let context = gix_merge::tree::Context {
            submodule: Some(&mut submodule),
        };

        let gix_merge::commit::virtual_merge_base::Outcome {
            virtual_merge_bases,
            commit_id,
            tree_id,
        } = gix_merge::commit::virtual_merge_base(
            first,
            second,
            merge_bases,
            graph,
            &mut diff_cache,
            &mut blob_merge,
            self,
            &mut |id| id.to_owned().attach(self).shorten_or_id().to_string(),
            context,
            options.into(),
        )?;

        Ok(crate::merge::virtual_merge_base::Outcome {
            virtual_merge_bases: virtual_merge_bases.into_iter().map(|id| id.attach(self)).collect(),
            commit_id: commit_id.attach(self),
            tree_id: tree_id.attach(self),
        })
    }
}

mod submodule {
    use std::{collections::HashMap, ops::ControlFlow};

    use crate::{
        Repository, Result,
        bstr::{BStr, BString, ByteSlice},
    };

    pub(super) fn query(
        repo: &Repository,
    ) -> impl FnMut(&BStr, gix_merge::submodule::Query<'_>) -> Result<Option<bool>> + '_ {
        let mut repositories = HashMap::<BString, Option<Repository>>::new();
        move |path, query| {
            if !repositories.contains_key(path) {
                repositories.insert(path.to_owned(), open(repo, path)?);
            }
            let Some(repo) = repositories.get(path).and_then(Option::as_ref) else {
                return Ok(None);
            };
            Ok(Some(match query {
                gix_merge::submodule::Query::CommitsAvailable(commit_ids) => {
                    for commit_id in commit_ids {
                        let Some(object) = repo
                            .try_find_object(commit_id.to_owned())?
                            .filter(|object| object.kind.is_commit())
                        else {
                            return Ok(Some(false));
                        };
                        object.try_into_commit()?.decode()?;
                    }
                    true
                }
                gix_merge::submodule::Query::IsAncestor { ancestor, descendant } => {
                    let cache = repo.commit_graph_if_enabled()?;
                    let mut graph = gix_revwalk::Graph::new(
                        crate::revision::walk::Objects {
                            repo,
                            shallow: repo.shallow_commits()?,
                        },
                        cache.as_ref(),
                    );
                    gix_revision::merge_base::is_ancestor(ancestor.to_owned(), descendant.to_owned(), &mut graph)?
                }
            }))
        }
    }

    fn open(repo: &Repository, path: &BStr) -> Result<Option<Repository>> {
        // Git tries the checkout first, including unregistered or renamed submodules.
        if let Some(worktree_gitdir) = crate::submodule::worktree_gitdir(repo, path)?
            && let Some(git_dir) = crate::submodule::git_dir_from_worktree_gitdir(&worktree_gitdir, true)?
        {
            match crate::submodule::open(repo, &git_dir, path)? {
                ControlFlow::Break(_) => return Ok(None),
                ControlFlow::Continue(Some(subrepo)) => return Ok(Some(subrepo)),
                ControlFlow::Continue(None) => {}
            }
        }
        if let Some(submodules) = repo.submodules()? {
            for submodule in submodules {
                if submodule
                    .try_path()?
                    .is_some_and(|configured_path| configured_path.as_bstr() == path)
                {
                    return submodule.open();
                }
            }
        }
        Ok(None)
    }
}