1

I have 2 files which got committed in a certain branch and I would like to merge only a single file from the commit changeset. How should I do that?

Rpj
  • 5,348
  • 16
  • 62
  • 122

2 Answers2

2

There is no option to git-merge that takes a list of path(s) to merge.
Instead, you will have to do this manually, by

  1. instructing git to stop after the merge has taken place but before committing;
  2. resetting the second file to the contents of HEAD;
  3. placing those contents on disk, which will result in only merging the first file.

For example, if the commit in question is 0123abc and the file you wish to omit from the merge is file2.txt:

git merge --no-commit --no-ff 0123abc
git reset HEAD file2.txt
git checkout -- file2.txt
XavierStuvw
  • 1,294
  • 2
  • 15
  • 30
Edward Thomson
  • 74,857
  • 14
  • 158
  • 187
1

Assuming that what you're really after for one of your files to look like it does in the changed branch, and for the other file to look like it does in the current branch, then you can pull the changes from one branch without actually creating a merge. To do this interactively, you can use git rebase -i.

You can short-cut the interactive process by using git stash on the file you want to merge, git checkout to the unmodified branch, then git stash pop.

If you want to end up with one of the changes you made in the current branch, and for the other change to disappear, then you can manually revert the unwanted changes and then git commit --amend to edit your original commit so that only the other file remains changed.

There are more advanced options availble, using blobs and some of git's low-level merging powers, but they're to be avoided without great git-fu.

Paul Hicks
  • 13,289
  • 5
  • 51
  • 78
  • 1
    I don't understand - it doesn't look like you've actually performed a merge at all. None of these commands will actually produce a commit that is a merge of two parent commits? – Edward Thomson Feb 18 '14 at 07:01
  • The second one will, but the other two won't. However, when people say that they want to merge a file, usually they mean that they want that file "in the branch" going forward. The structure of the history is usually not as important as the end result. – Paul Hicks Feb 18 '14 at 07:03
  • 1
    Which command in your second paragraph creates a merge commit? – Edward Thomson Feb 18 '14 at 07:04
  • Ok that was painful.. I should have brought that script with me when I left my old place of work! You're right, none of the steps result in two parent histories. Also, the merge-one-file route is so fraught with risks (I deleted a file about 5 times trying to figure out the syntax) and so poorly-documented that I'm going to remove the option from my answer. I'll also point out that my solutions don't actually merge. – Paul Hicks Feb 18 '14 at 08:00