How can you merge two branches in git, retaining necessary files from a branch?
When merging two branches, if a file was deleted in one branch and not in another, the file is ultimately deleted.
For example:
- A file exists in master when you make a new branch
- you remove the file from master since we don’t need it (yet)
- you make changes in the branch to add a feature, which relies on the file existing
- you make bug fixes in master (cannot be discarded)
- you merge some day, and the file is gone!
How to Reproduce:
-
Create a git repo with one file.
git init echo "test" > test.txt git add . git commit -m "initial commit" -
Create a branch
git branch branchA -
Delete the file in master
git rm test.txt git commit -m "removed file from master" -
Make ANY changes in branchA that don’t touch the deleted file (it has to be unchanged to avoid Conflict)
git checkout branchA touch something.txt git add . git commit -m "some branch changes"
From here, any way I’ve found to merge these two branches, the test.txt file is deleted. Assuming we were relying on the file for branchA, this is a big problem.
Failing examples:
Merge 1
git checkout branchA
git merge master
ls test.txt
Merge 2
git checkout master
git merge branchA
ls test.txt
Rebase 1
git checkout branchA
git rebase master
ls test.txt
This is an interesting issue. Because you deleted the file after
BranchAwas created, and then are mergingmasterintoBranchA, I’m not sure how Git would be able to realize there is a conflict.After the bad merge you can undo, and then re-merge, but add back the file: