git/list[1] front-page[2] threads[3] people[4] search[5] about
 

Re: Merge selected files or folders

From
Junio C Hamano <gitster@pobox.com>
Date
Mar 21, 2024, 17:50 UTC
Message-ID
<xmqqbk778oeb.fsf@gitster.g>
In-Reply-To
<PA4PR07MB7406FAC1F8C00E29979FCFF59E322@PA4PR07MB7406.eurprd07.prod.outlook.com>
Richard Kerry <richard.kerry@eviden.com> 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
Previous: Richard KerryNext: Sergey Organov
Message 2 of 7 in “Merge selected files or folders”
  1. Richard KerryMar 21, 2024
  2. Junio C HamanoMar 21, 2024
  3. Sergey OrganovMar 22, 2024
  4. Konstantin KhomoutovMar 22, 2024
  5. Dragan SimicMar 22, 2024
  6. stefan.naewe@atlas-elektronik.comMar 22, 2024
  7. Junio C HamanoMar 22, 2024

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.