Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge from trunk to branch but only files in the branch

I have branched off trunk to a feature branch. In order to keep my branch up to date, I would like to frequently merge back from trunk (always up to date), but I don't like everything in trunk getting merged into my branch.

Is it possible to somehow merge from trunk only the files I have in the branch?

E.g, before merge:

Trunk
  File 1
  File 2
  File 3
  File 4
Branch
  File 2
  File 3

After merge, I have the following, which I don't want. I want to only merge File 2 and File 3 from trunk.

Branch
  File 1
  File 2
  File 3
  File 4
like image 811
ProfK Avatar asked Mar 26 '20 10:03

ProfK


People also ask

Does merging a branch delete files?

Git does not apply deleted files when merging an old branch into the master.

Does merging change both branches?

Merging Branches. Once you've completed work on your branch, it is time to merge it into the main branch. Merging takes your branch changes and implements them into the main branch. Depending on the commit history, Git performs merges two ways: fast-forward and three-way merge.


2 Answers

git merge --no-commit --no-ff trunk
git diff --name-only -z --diff-filter=A @ | xargs -0 git rm -f
git commit
like image 139
jthill Avatar answered Oct 17 '22 04:10

jthill


Augmenting @jthill's approach, I would do

git merge --no-commit --no-ff trunk
git diff --name-only -z --diff-filter=A @ | xargs -0 git rm -f
rm .git/MERGE_*
git commit

This would make git forget that it's doing a merge and would prevent files from being deleted when you finally want to merge back into your trunk.

As a comment though, this is not a very sustainable workflow, even if you write your own script to automatically do this every time. It's worth asking the question of why you feel like you need to do this.

It might be that: - The repo is too large -- Then you should think about splitting up the code - Your work is logically separate -- Then you should definitely think about splitting up the code - There is broken work in trunk -- Then you should implement a new workflow that doesn't merge broken code into trunk

Alternative solutions if you don't want to modify your workflow would be to:

If you want to overwrite the changes completely

git checkout trunk -- *
git commit

If you want to completely overwrite some files

git checkout trunk -- file2
git commit

Or, interactive rebase gives you the option to only select the commts you want. This also won't result in files being deleted later on

git rebase -i trunk

Personally, I'd look into changing your workflow. If you have more information on your situation, we'd be able to help you figure out other solutions.

like image 36
Ben Thayer Avatar answered Oct 17 '22 06:10

Ben Thayer