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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…