Speed Up Merges with Git’s Index

14 Jun 2012

We’ve all been there, running git merge only to have it spew CONFLICT all over the place and quit partway through. But if we already know that every time there is a conflict then all of “our” code that we are merging changes into should take precedence over “their” changes that we are pulling in, git 1.7.3 provides a handy shortcut for that:

% git merge -X ours theirbranch

If “their” changes that we are pulling in should always take precedence instead then things are equally easy:

% git merge -X theirs theirbranch

If “ours” or “theirs” style merges will work, but only for certain files, things get a bit more complicated. But with a bit of background knowledge of how git’s index works we can save ourselves a bunch of work.

The index stores what stage a file is in. Normally, a file’s stage is 0.

% git ls-files -s myfile
100644 4b48deed3a433909bfd6b6ab3d4b91348b6af464 0       myfile

A file with a merge conflict is different because the index actually has three different versions of it: the version that the two branches we are merging most recently had in common, the version on “our” side of the merge, and the version on “their” side of the merge. In git these correspond to stages 1, 2, and 3. This is one reason one has to run git add on every conflicting file before completing a merge.

% git ls-files -s myfile
100644 4b48deed3a433909bfd6b6ab3d4b91348b6af464 1       myfile
100644 5be4a414b32cf4204f889469942986d3d783da84 2       myfile
100644 39c5733494077ae8bc45c45c15a708ffe9871966 3       myfile

Rather than opening up the conflicting file and clearing out the parts that clash by hand, we can instead simply copy the version we want from the index into our working tree:

% git checkout-index -f --stage 3 myfile
% git add myfile
% git commit

One Response to “Speed Up Merges with Git’s Index”

  1. hspencer77 Says:

    Reblogged this on More Mind Spew-age from Harold Spencer Jr. and commented:
    Some more good Git Goodness!

Comments are closed.