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?
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.
Usually git does not overwrite anything during merge.
If you remove a file in one branch, the merge will remove it in the target branch too.
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
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