Subject: Re: Merge selected files or folders

From: Junio C Hamano <[email-masked]>
Date: Thu, 21 Mar 2024 10:50:52 -0700

Richard Kerry <[email-masked]> writes:

> I'd like to merge only certain files, or folders, from another
> branch.  What command or options should I be looking at to get
> this done?

If you are using the verb "merge" in the way Git uses, then there is
*no* option to do so and that is very much deliberate, as allowing
such a operation will break your history.

A "merge" commit in Git records the fact that *all* changes that
were done in each parent since the merged branches diverged have
been considered and the tree recorded by the merge commit is the
result.  Hence, if you later change your mind and "merge" other
changes from the same branch, it will result in no change at all, by
definition.

But if you are porting some changes made on another branch to the
current branch, and then planning to record the result as a regular
single parent commit, then there is no fundamental reason to forbid
such an operation.  It is what cherry-pick ought to be able to do,
even though I do not think it accepts a pathspec to limit currently.

Assuming a history of this shape:

      x---x---X (that other branch)
     /
    O---o---o---o---H	(current branch)

such a "cherry-pick" would essentially be applying all the changes
lead to X since the histories forked at O on top of H:

    $ git checkout H
    $ O=$(git merge-base X H)
    $ git diff $O X | git apply
    $ git commit -m "picked changes from branch X"

And if you want to limit the paths involved in the operation, the
"git diff" step can be given a <pathspec> to limit the changes that
are ported.

    $ git checkout H
    $ O=$(git merge-base X H)
    $ git diff $O X -- thisdir/ that/file | git apply
    $ git commit -m "picked changes from branch X"

Teaching "git cherry-pick" to accept a pathspec and natively 
perform something like the above is left as an exercise.

HTH