Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does git merge sometimes remove changes when it shouldn't?

Tags:

git

git-merge

Every so often, I've been experiencing some strange behavior in git. where changes I make to a file in one branch are removed when I merge in another branch in which unrelated changes have been made to the same file.

Let's say I start in branch master. Here's the rough outline of what happens:

vim foo.txt
git add foo.txt
git commit

git checkout -b test
vim foo.txt
git commit -a -m added a new line to foo.txt

git checkout master
vim foo.txt
git commit -a -m made some unrelated change

git merge test

At this point, I will discover that the change I made in foo.txt in the master branch has been removed.

I am making many other changes and performing other git operations in the middle of all of this. Since merges like this are the entire point of git, I feel like I am probably doing something wrong, at some point.

Does anyone have any idea what?

like image 571
dwh Avatar asked Jan 21 '11 16:01

dwh


People also ask

Does merging branches delete it?

The more the branches and master diverge away from each other the farther away their “common ancestor” commit becomes. When you're done with a branch and it has been merged into master, delete it. A new branch can be made off of the most recent commit on the master branch.

Will git merge overwrite my changes?

Usually git does not overwrite anything during merge.

Does git merge remove files?

If you remove a file in one branch, the merge will remove it in the target branch too.


1 Answers

because the commit on the test branch was made last and test has a commit that can resolve a common ancestor commit, then the default behaviour is to use the new information from test as the most up-to-date information. you can force the behaviour by using the -s option. See this link for examples: http://www.kernel.org/pub/software/scm/git/docs/git-merge.html

EDITED with workflow example

mkdir showoff_git
cd showoff_git
git init
touch file_a
echo "line 1" >> file_a
git add .
git commit -m "initial commit"
git checkout -b test
sed -i='' s/1/2/ file_a
git add .
git commit -m "bluffing"
git checkout master
git merge -s ours test
like image 120
Jed Schneider Avatar answered Sep 28 '22 03:09

Jed Schneider