Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

  1. Create a git repo with one file.

    git init
    echo "test" > test.txt
    git add .
    git commit -m "initial commit"
    
  2. Create a branch

    git branch branchA
    
  3. Delete the file in master

    git rm test.txt
    git commit -m "removed file from master"
    
  4. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
627 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...