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:
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
If you remove a file in one branch, the merge will remove it in the target branch too.
Copy the cell with the CONCATENATE formula (D2). Paste the copied value in the top-left cell of the range you want to merge (A2). To do this, right click the cell and select Paste Special > Values from the context menu. Select the cells that you want to join (A2 and B2) and click Merge and Center.
Given that, there are multiple ways to remove a file from a Merge Request, such as: As you proposed, you can add a new commit to your source branch which effectively undoes the changes to the files you no longer wish to include. This could mean undoing the changes to existing tracked files, or deleting untracked files.
This is an interesting issue. Because you deleted the file after BranchA
was created, and then are merging master
into BranchA
, 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:
git checkout HEAD@{1} .
git merge --no-commit master
git checkout master test.txt
git add test.txt
git commit
Casey's example didn't work for my case - I couldn't checkout test.txt
from master
, because it was no longer in that branch:
$ git checkout master test.txt
error: pathspec 'test.txt' did not match any file(s) known to git.
Happily I could pull the file out of branchA
's own HEAD
:
$ git checkout branchA
$ git merge --no-commit master
$ git checkout HEAD test.txt
$ git add test.txt
$ git commit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With