I’m sure you’ve all come across merge commits when using Git, those pesky commits with a message reading something like Merge branch 'master' of github.com:kernow/Project-X. We’ve all been guilty of creating git merge commits, but don’t worry there’s a way to stop being a “Git Twit” and make everyone in your team happy which will no doubt lead to them buying you cake! But first, how do these commits get into the repository in the first place? You start out being a good gitizen, git checkout master, git pull, feverishly code away, commit, commit, commit. Woo I’m done, everyone will love my wicked new code! git push rejection!! what! Other people have been working too, jerks. git pull, git push, and there we have it, a merge commit. So how do we stop this madness?
Rebase to the rescue
When running git pull we need to rebase, and so to the first way to avoid merge commits…
git pull --rebaseWhat’s happening here? Git will rewind (undo) all of your local commits, pull down the remote commits then replay your local commits on top of the newly pulled remote commits. If any conflicts arise that git can’t handle you’ll be given the opportunity to manually merge the commits then simply rungit rebase --continueto carry on replaying your local commits.Tell git to always rebase when pulling, to do this on a project level add this to your
.git/configfile:Or do it all on the command line with1 2
[branch “master”] rebase = truegit config branch.master.rebase trueAdd a global config option to always rebase when pulling
Or again do it all on the command line with1 2
[branch] autosetuprebase = alwaysgit config --global branch.autosetuprebase alwaysAnd the final way, which is what I personally use, in
~/.gitconfigI have a bunch of aliases setup so I can type less and save myself those valuable microseconds. This will allow you to type1 2
[alias] pl = pull --rebasegit pl(or in my caseg plas I havegitaliased tog) and it will automatically rebase. If I want to do a pull and not rebase for a specific reason I can use the commandgit pullwhich will do an pull without rebaseing.
Of course you could use the 3rd solution and run the command git pull --no-rebase but that involves more typing, and I’m a lazy typer!