Search code examples
gitgit-merge

git - easy way to merge 3 trees without touching index or working tree


I have a rather devilish idea in my head that requires me to run different merge operations where I do not want to touch the index nor the working tree. I know about git merge-tree that I think used to do what I am requesting but it has been obsoleted (at least the possibility of providing the 3 trees and getting the resulting tree id as output). Are there other current ways to do it?

Just to be clear:

  • I do not want to mess up with histories.
  • I want to provide the base tree and the 2 tip trees.
  • And last but not least, I do not want to mess up with the index nor the working tree.

All I need as output is the resulting tree id if merge succeeds.... if there are conflicts it's ok that I get nothing.


Solution

  • While git merge-tree already improved with Git 2.37/2.38, only Git 2.40 (Q1 2023) adds the missing part you seek: "merge-tree" learns a new --merge-base option.

    See commit 4cc9eb3 (24 Nov 2022), and commit 501e3ba, commit 66265a6 (11 Nov 2022) by Kyle Zhao (yefengzkk).
    (Merged by Junio C Hamano -- gitster -- in commit 7576e51, 14 Dec 2022)

    merge-tree.c: add --merge-base= option

    Signed-off-by: Kyle Zhao
    Signed-off-by: Taylor Blau

    This patch will give our callers more flexibility to use git merge-tree(man), such as:

    git merge-tree --write-tree --merge-base=branch^ HEAD branch
    

    This does a merge of HEAD and branch, but uses branch^ as the merge-base.

    And the reason why using an option flag instead of a positional argument is to allow additional commits passed to merge-tree to be handled via an octopus merge in the future.

    Note: Specifying multiple bases is currently not supported

    And:

    merge-tree.c: allow specifying the merge-base when --stdin is passed

    Signed-off-by: Kyle Zhao
    Signed-off-by: Taylor Blau

    The previous commit added a --merge-base option in order to allow using a specified merge-base for the merge.
    Extend the input accepted by --stdin to also allow a specified merge-base with each merge requested.
    For example:

    printf "<b3> -- <b1> <b2>" | git merge-tree --stdin
    

    does a merge of b1 and b2, and uses b3 as the merge-base.

    git merge-tree now includes in its man page:

    INPUT FORMAT

    'git merge-tree --stdin' input format is fully text based. Each line has this format:

    [<base-commit> -- ]<branch1> <branch2>
    

    If one line is separated by --, the string before the separator is used for specifying a merge-base for the merge and the string after the separator describes the branches to be merged.