Todays exercise is git rebase vs git merge. Often you will hear "always rebase never merge" and have no idea why people say don't merge when you are still merging. This exercise will show the difference between the two and why rebase is your friend.
First the exercise.
# create an empty server
mkdir server
cd server
git init --bare
cd ..
# make a client and do an initial checkin
git clone server client1
cd client1
touch README
git add README
git commit -m "Initial README"
git push --all
cd ..
# make a two new clients
git clone server merge_client
git clone server rebase_client
# create a conflict
# in each of the three clients edit the first line of README to say the name of the client
# then commit the change
cd client1
cat > README <<EOF
client1
EOF
git commit -a -m "client1-readme"
cd ..
cd merge_client
cat > README <<EOF
merge_client
EOF
git commit -a -m "merge-readme"
cd ..
cd ..
cd rebase_client
cat > README <<EOF
rebase_client
EOF
cat > README <<EOF
rebase_client
EOF
git commit -a -m "rebase-readme"
cd ..
cd ..
# in client1 push the change
cd client1 git push
cd ..
# in merge_client do a merge without a rebase
cd merge_client
git pull
git mergetool
git commit -a
git log
cd ..
# in rebase_client do a rebase. Rebases need you to fetch objects first.
cd rebase_client
git fetch
git rebase
git mergetool
git rebase --continue
git log
cd ..
Notice the difference in logs between rebase_client and merge_client? What happened was rebase updated your tree under your changes then reapplied your changes. All of your changes are modified to be as if you had done them against the tip of the tree. Do a git show in both trees. See what happened in merge_client and compare that to what happened in rebase_client?
It gets better, even if you don't have a merge conflict you want to rebase.
cd client1
touch README2
git add README2
git commit -m "client1-README2"
git push
cd ..
cd merge_client
git pull
# commit the merge
git log
cd ..
cd rebase_client
git fetch
git rebase
git log
cd ..
WAIT A SECOND! Why did you have to merge on merely adding a new file?!?!?
Let's get a better idea of what is happening.
cd rebase_client
git log --pretty=raw
cd ..
Notice the nice clean chain where each parent is prior commit? Compare that to merge_client
cd merge_client
git log --pretty=raw
cd ..
client1-README2 has a parent of client1. In merge_client that is not the prior patch so you have forked the tree and then have to merge back. Even though no single file is in conflict the tree as a whole has forked.
So, always rebase before pulling.
No comments:
Post a Comment