Ignore whitespace when doing a merge in mercurial

2019-04-25 02:09发布

问题:

We're hitting a problem when merging in Mercurial where whitespace changes are causing merge conflicts which mask any "real" conflicts we may have and makes merging a nightmare. We've recently conformed to a formatting style which changed the indentation of files in some branches and merging has become almost impossible since.

As an example, try:

hg init testrepo
cd testrepo/

echo "This is text." > newfile.txt
hg add newfile.txt
hg commit -m "Created a file."
hg branch newbranch
echo "This is some more text." > newfile.txt
hg commit -m "Changed text in the file."
hg update default
echo "   This is text." > newfile.txt
hg commit -m "Added indentation whitespace."

This results in two branches, one with whitespace changes, the other with textual changes:

@  2     "   This is text".
|    
|
| o  1   "This is some more text."
|/     
|
o  0     "This is text."

When trying an hg merge on this I get a merge conflict. If we have conflicts on every line it becomes difficult and time consuming to sort out the "real" conflicts. What I'd prefer is for the merge process to think "OK, changeset 2 line 1 differs from the parent only in whitespace so consider it unchanged. Pick changeset 1 line 1 as the merged result."

回答1:

Ignoring whitespace or not is a choice your merge tool makes. You can configure all manner of merge tools for use with mercurial as shown here: MergeToolConfiguration

Mercurial's internal pre-merge won't/can't ignore whitespace, but if your external merge tool does and it finds only whitespace changes it will exit immediately, and if it finds other that whitespace changes it can hide the whitespace changes when it does load.

For example, with the popular kdiff3 merge tool you'd enable the "White space 2/3-file merge" setting and tell it whether to pick left or right.

Tl;Dr: turn this on in your merge tool, not in mercurial.



回答2:

Is this a situation where scrubbing the whitespace would be difficult? If not, I would write a simple script that scrubs all whitespace before checkin to avoid this. The downside is that you would lose formatting, but most IDE's can easily restore that for you.

The alternative would be to use a standard formatter before checking in to do the opposite... add white space where it should be.