view mercurial/simplemerge.py @ 42044:bb271ec2fbfb

compression: introduce a `storage.revlog.zstd.level` configuration This option control the zstd compression level used when compressing revlog chunk. The usage of zstd for revlog compression has not graduated from experimental yet, but we intend to fix that soon. The option name for the compression level is more straight forward to pick, so this changesets comes first. Having a dedicated option for each compression engine is useful because they don't support the same range of values. I ran the same measurement as for the zlib compression level (in the parent changesets). The variation in repository size is stay mostly in the same (small) range. The "read/write" performance see smallish variation, but are overall much better than zlib. Write performance show the same tend of having better write performance for when reaching high-end compression. Again, we don't intend to change the default zstd compression level (currently: 3) in this series. However this is worth investigating in the future. The Performance comparison of zlib vs zstd is quite impressive. The repository size stay in the same range, but the performance are much better in all situations. Comparison summary ================== We are looking at: - performance range for zlib - performance range for zstd - comparison of default zstd (level-3) to default zlib (level 6) - comparison of the slowest zstd time to the fastest zlib time Read performance: ----------------- | zlib | zstd | cmp | f2s mercurial | 0.170159 - 0.189219 | 0.144127 - 0.149624 | 80% | 88% pypy | 2.679217 - 2.768691 | 1.532317 - 1.705044 | 60% | 63% netbeans | 122.477027 - 141.620281 | 72.996346 - 89.731560 | 58% | 73% mozilla | 147.867662 - 170.572118 | 91.700995 - 105.853099 | 56% | 71% Write performance: ------------------ | zlib | zstd | cmp | f2s mercurial | 53.250304 - 56.2936129 | 40.877025 - 45.677286 | 75% | 86% pypy | 460.721984 - 476.589918 | 270.545409 - 301.002219 | 63% | 65% netbeans | 520.560316 - 715.930400 | 370.356311 - 428.329652 | 55% | 82% mozilla | 739.803002 - 987.056093 | 505.152906 - 591.930683 | 57% | 80% Raw data -------- repo alg lvl .hg/store size 00manifest.d read write mercurial zlib 1 49,402,813 5,963,475 0.170159 53.250304 mercurial zlib 6 47,197,397 5,875,730 0.182820 56.264320 mercurial zlib 9 47,121,596 5,849,781 0.189219 56.293612 mercurial zstd 1 49,737,084 5,966,355 0.144127 40.877025 mercurial zstd 3 48,961,867 5,895,208 0.146376 42.268142 mercurial zstd 5 48,200,592 5,938,676 0.149624 43.162875 mercurial zstd 10 47,833,520 5,913,353 0.145185 44.012489 mercurial zstd 15 47,314,604 5,728,679 0.147686 45.677286 mercurial zstd 20 47,330,502 5,830,539 0.145789 45.025407 mercurial zstd 22 47,330,076 5,830,539 0.143996 44.690460 pypy zlib 1 370,830,572 28,462,425 2.679217 460.721984 pypy zlib 6 340,112,317 27,648,747 2.768691 467.537158 pypy zlib 9 338,360,736 27,639,003 2.763495 476.589918 pypy zstd 1 362,377,479 27,916,214 1.532317 270.545409 pypy zstd 3 354,137,693 27,905,988 1.686718 294.951509 pypy zstd 5 342,640,043 27,655,774 1.705044 301.002219 pypy zstd 10 334,224,327 27,164,493 1.567287 285.186239 pypy zstd 15 329,000,363 26,645,965 1.637729 299.561332 pypy zstd 20 324,534,039 26,199,547 1.526813 302.149827 pypy zstd 22 324,530,595 26,198,932 1.525718 307.821218 netbeans zlib 1 1,281,847,810 165,495,457 122.477027 520.560316 netbeans zlib 6 1,205,284,353 159,161,207 139.876147 715.930400 netbeans zlib 9 1,197,135,671 155,034,586 141.620281 678.297064 netbeans zstd 1 1,259,581,737 160,840,613 72.996346 370.356311 netbeans zstd 3 1,232,978,122 157,691,551 81.622317 396.733087 netbeans zstd 5 1,208,034,075 160,246,880 83.080549 364.342626 netbeans zstd 10 1,188,624,176 156,083,417 79.323935 403.594602 netbeans zstd 15 1,176,973,589 153,859,477 89.731560 428.329652 netbeans zstd 20 1,162,958,258 151,147,535 82.842667 392.335349 netbeans zstd 22 1,162,707,029 151,150,220 82.565695 402.840655 mozilla zlib 1 2,775,497,186 298,527,987 147.867662 751.263721 mozilla zlib 6 2,596,856,420 286,597,671 170.572118 987.056093 mozilla zlib 9 2,587,542,494 287,018,264 163.622338 739.803002 mozilla zstd 1 2,723,159,348 286,617,532 91.700995 570.042751 mozilla zstd 3 2,665,055,001 286,152,013 95.240155 561.412805 mozilla zstd 5 2,607,819,817 288,060,030 101.978048 505.152906 mozilla zstd 10 2,558,761,085 283,967,648 104.113481 497.771202 mozilla zstd 15 2,526,216,060 275,581,300 105.853099 591.930683 mozilla zstd 20 2,485,114,806 266,478,859 95.268795 576.515389 mozilla zstd 22 2,484,869,080 266,456,505 94.429282 572.785537
author Pierre-Yves David <pierre-yves.david@octobus.net>
date Wed, 27 Mar 2019 18:35:59 +0100
parents aaad36b88298
children 2372284d9457
line wrap: on
line source

# Copyright (C) 2004, 2005 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.

# mbp: "you know that thing where cvs gives you conflict markers?"
# s: "i hate that."

from __future__ import absolute_import

from .i18n import _
from . import (
    error,
    mdiff,
    pycompat,
)
from .utils import (
    stringutil,
)

class CantReprocessAndShowBase(Exception):
    pass

def intersect(ra, rb):
    """Given two ranges return the range where they intersect or None.

    >>> intersect((0, 10), (0, 6))
    (0, 6)
    >>> intersect((0, 10), (5, 15))
    (5, 10)
    >>> intersect((0, 10), (10, 15))
    >>> intersect((0, 9), (10, 15))
    >>> intersect((0, 9), (7, 15))
    (7, 9)
    """
    assert ra[0] <= ra[1]
    assert rb[0] <= rb[1]

    sa = max(ra[0], rb[0])
    sb = min(ra[1], rb[1])
    if sa < sb:
        return sa, sb
    else:
        return None

def compare_range(a, astart, aend, b, bstart, bend):
    """Compare a[astart:aend] == b[bstart:bend], without slicing.
    """
    if (aend - astart) != (bend - bstart):
        return False
    for ia, ib in zip(pycompat.xrange(astart, aend),
                      pycompat.xrange(bstart, bend)):
        if a[ia] != b[ib]:
            return False
    else:
        return True

class Merge3Text(object):
    """3-way merge of texts.

    Given strings BASE, OTHER, THIS, tries to produce a combined text
    incorporating the changes from both BASE->OTHER and BASE->THIS."""
    def __init__(self, basetext, atext, btext, base=None, a=None, b=None):
        self.basetext = basetext
        self.atext = atext
        self.btext = btext
        if base is None:
            base = mdiff.splitnewlines(basetext)
        if a is None:
            a = mdiff.splitnewlines(atext)
        if b is None:
            b = mdiff.splitnewlines(btext)
        self.base = base
        self.a = a
        self.b = b

    def merge_lines(self,
                    name_a=None,
                    name_b=None,
                    name_base=None,
                    start_marker='<<<<<<<',
                    mid_marker='=======',
                    end_marker='>>>>>>>',
                    base_marker=None,
                    localorother=None,
                    minimize=False):
        """Return merge in cvs-like form.
        """
        self.conflicts = False
        newline = '\n'
        if len(self.a) > 0:
            if self.a[0].endswith('\r\n'):
                newline = '\r\n'
            elif self.a[0].endswith('\r'):
                newline = '\r'
        if name_a and start_marker:
            start_marker = start_marker + ' ' + name_a
        if name_b and end_marker:
            end_marker = end_marker + ' ' + name_b
        if name_base and base_marker:
            base_marker = base_marker + ' ' + name_base
        merge_regions = self.merge_regions()
        if minimize:
            merge_regions = self.minimize(merge_regions)
        for t in merge_regions:
            what = t[0]
            if what == 'unchanged':
                for i in range(t[1], t[2]):
                    yield self.base[i]
            elif what == 'a' or what == 'same':
                for i in range(t[1], t[2]):
                    yield self.a[i]
            elif what == 'b':
                for i in range(t[1], t[2]):
                    yield self.b[i]
            elif what == 'conflict':
                if localorother == 'local':
                    for i in range(t[3], t[4]):
                        yield self.a[i]
                elif localorother == 'other':
                    for i in range(t[5], t[6]):
                        yield self.b[i]
                else:
                    self.conflicts = True
                    if start_marker is not None:
                        yield start_marker + newline
                    for i in range(t[3], t[4]):
                        yield self.a[i]
                    if base_marker is not None:
                        yield base_marker + newline
                        for i in range(t[1], t[2]):
                            yield self.base[i]
                    if mid_marker is not None:
                        yield mid_marker + newline
                    for i in range(t[5], t[6]):
                        yield self.b[i]
                    if end_marker is not None:
                        yield end_marker + newline
            else:
                raise ValueError(what)

    def merge_groups(self):
        """Yield sequence of line groups.  Each one is a tuple:

        'unchanged', lines
             Lines unchanged from base

        'a', lines
             Lines taken from a

        'same', lines
             Lines taken from a (and equal to b)

        'b', lines
             Lines taken from b

        'conflict', base_lines, a_lines, b_lines
             Lines from base were changed to either a or b and conflict.
        """
        for t in self.merge_regions():
            what = t[0]
            if what == 'unchanged':
                yield what, self.base[t[1]:t[2]]
            elif what == 'a' or what == 'same':
                yield what, self.a[t[1]:t[2]]
            elif what == 'b':
                yield what, self.b[t[1]:t[2]]
            elif what == 'conflict':
                yield (what,
                       self.base[t[1]:t[2]],
                       self.a[t[3]:t[4]],
                       self.b[t[5]:t[6]])
            else:
                raise ValueError(what)

    def merge_regions(self):
        """Return sequences of matching and conflicting regions.

        This returns tuples, where the first value says what kind we
        have:

        'unchanged', start, end
             Take a region of base[start:end]

        'same', astart, aend
             b and a are different from base but give the same result

        'a', start, end
             Non-clashing insertion from a[start:end]

        'conflict', zstart, zend, astart, aend, bstart, bend
            Conflict between a and b, with z as common ancestor

        Method is as follows:

        The two sequences align only on regions which match the base
        and both descendants.  These are found by doing a two-way diff
        of each one against the base, and then finding the
        intersections between those regions.  These "sync regions"
        are by definition unchanged in both and easily dealt with.

        The regions in between can be in any of three cases:
        conflicted, or changed on only one side.
        """

        # section a[0:ia] has been disposed of, etc
        iz = ia = ib = 0

        for region in self.find_sync_regions():
            zmatch, zend, amatch, aend, bmatch, bend = region
            #print 'match base [%d:%d]' % (zmatch, zend)

            matchlen = zend - zmatch
            assert matchlen >= 0
            assert matchlen == (aend - amatch)
            assert matchlen == (bend - bmatch)

            len_a = amatch - ia
            len_b = bmatch - ib
            len_base = zmatch - iz
            assert len_a >= 0
            assert len_b >= 0
            assert len_base >= 0

            #print 'unmatched a=%d, b=%d' % (len_a, len_b)

            if len_a or len_b:
                # try to avoid actually slicing the lists
                equal_a = compare_range(self.a, ia, amatch,
                                        self.base, iz, zmatch)
                equal_b = compare_range(self.b, ib, bmatch,
                                        self.base, iz, zmatch)
                same = compare_range(self.a, ia, amatch,
                                     self.b, ib, bmatch)

                if same:
                    yield 'same', ia, amatch
                elif equal_a and not equal_b:
                    yield 'b', ib, bmatch
                elif equal_b and not equal_a:
                    yield 'a', ia, amatch
                elif not equal_a and not equal_b:
                    yield 'conflict', iz, zmatch, ia, amatch, ib, bmatch
                else:
                    raise AssertionError("can't handle a=b=base but unmatched")

                ia = amatch
                ib = bmatch
            iz = zmatch

            # if the same part of the base was deleted on both sides
            # that's OK, we can just skip it.


            if matchlen > 0:
                assert ia == amatch
                assert ib == bmatch
                assert iz == zmatch

                yield 'unchanged', zmatch, zend
                iz = zend
                ia = aend
                ib = bend

    def minimize(self, merge_regions):
        """Trim conflict regions of lines where A and B sides match.

        Lines where both A and B have made the same changes at the beginning
        or the end of each merge region are eliminated from the conflict
        region and are instead considered the same.
        """
        for region in merge_regions:
            if region[0] != "conflict":
                yield region
                continue
            issue, z1, z2, a1, a2, b1, b2 = region
            alen = a2 - a1
            blen = b2 - b1

            # find matches at the front
            ii = 0
            while (ii < alen and ii < blen and
                   self.a[a1 + ii] == self.b[b1 + ii]):
                ii += 1
            startmatches = ii

            # find matches at the end
            ii = 0
            while (ii < alen and ii < blen and
                   self.a[a2 - ii - 1] == self.b[b2 - ii - 1]):
                ii += 1
            endmatches = ii

            if startmatches > 0:
                yield 'same', a1, a1 + startmatches

            yield ('conflict', z1, z2,
                    a1 + startmatches, a2 - endmatches,
                    b1 + startmatches, b2 - endmatches)

            if endmatches > 0:
                yield 'same', a2 - endmatches, a2

    def find_sync_regions(self):
        """Return a list of sync regions, where both descendants match the base.

        Generates a list of (base1, base2, a1, a2, b1, b2).  There is
        always a zero-length sync region at the end of all the files.
        """

        ia = ib = 0
        amatches = mdiff.get_matching_blocks(self.basetext, self.atext)
        bmatches = mdiff.get_matching_blocks(self.basetext, self.btext)
        len_a = len(amatches)
        len_b = len(bmatches)

        sl = []

        while ia < len_a and ib < len_b:
            abase, amatch, alen = amatches[ia]
            bbase, bmatch, blen = bmatches[ib]

            # there is an unconflicted block at i; how long does it
            # extend?  until whichever one ends earlier.
            i = intersect((abase, abase + alen), (bbase, bbase + blen))
            if i:
                intbase = i[0]
                intend = i[1]
                intlen = intend - intbase

                # found a match of base[i[0], i[1]]; this may be less than
                # the region that matches in either one
                assert intlen <= alen
                assert intlen <= blen
                assert abase <= intbase
                assert bbase <= intbase

                asub = amatch + (intbase - abase)
                bsub = bmatch + (intbase - bbase)
                aend = asub + intlen
                bend = bsub + intlen

                assert self.base[intbase:intend] == self.a[asub:aend], (
                        (self.base[intbase:intend], self.a[asub:aend]))

                assert self.base[intbase:intend] == self.b[bsub:bend]

                sl.append((intbase, intend,
                           asub, aend,
                           bsub, bend))

            # advance whichever one ends first in the base text
            if (abase + alen) < (bbase + blen):
                ia += 1
            else:
                ib += 1

        intbase = len(self.base)
        abase = len(self.a)
        bbase = len(self.b)
        sl.append((intbase, intbase, abase, abase, bbase, bbase))

        return sl

    def find_unconflicted(self):
        """Return a list of ranges in base that are not conflicted."""
        am = mdiff.get_matching_blocks(self.basetext, self.atext)
        bm = mdiff.get_matching_blocks(self.basetext, self.btext)

        unc = []

        while am and bm:
            # there is an unconflicted block at i; how long does it
            # extend?  until whichever one ends earlier.
            a1 = am[0][0]
            a2 = a1 + am[0][2]
            b1 = bm[0][0]
            b2 = b1 + bm[0][2]
            i = intersect((a1, a2), (b1, b2))
            if i:
                unc.append(i)

            if a2 < b2:
                del am[0]
            else:
                del bm[0]

        return unc

def _verifytext(text, path, ui, opts):
    """verifies that text is non-binary (unless opts[text] is passed,
    then we just warn)"""
    if stringutil.binary(text):
        msg = _("%s looks like a binary file.") % path
        if not opts.get('quiet'):
            ui.warn(_('warning: %s\n') % msg)
        if not opts.get('text'):
            raise error.Abort(msg)
    return text

def _picklabels(defaults, overrides):
    if len(overrides) > 3:
        raise error.Abort(_("can only specify three labels."))
    result = defaults[:]
    for i, override in enumerate(overrides):
        result[i] = override
    return result

def simplemerge(ui, localctx, basectx, otherctx, **opts):
    """Performs the simplemerge algorithm.

    The merged result is written into `localctx`.
    """
    opts = pycompat.byteskwargs(opts)

    def readctx(ctx):
        # Merges were always run in the working copy before, which means
        # they used decoded data, if the user defined any repository
        # filters.
        #
        # Maintain that behavior today for BC, though perhaps in the future
        # it'd be worth considering whether merging encoded data (what the
        # repository usually sees) might be more useful.
        return _verifytext(ctx.decodeddata(), ctx.path(), ui, opts)

    mode = opts.get('mode','merge')
    name_a, name_b, name_base = None, None, None
    if mode != 'union':
        name_a, name_b, name_base = _picklabels([localctx.path(),
                                                 otherctx.path(), None],
                                                opts.get('label', []))

    try:
        localtext = readctx(localctx)
        basetext = readctx(basectx)
        othertext = readctx(otherctx)
    except error.Abort:
        return 1

    m3 = Merge3Text(basetext, localtext, othertext)
    extrakwargs = {
            "localorother": opts.get("localorother", None),
            'minimize': True,
        }
    if mode == 'union':
        extrakwargs['start_marker'] = None
        extrakwargs['mid_marker'] = None
        extrakwargs['end_marker'] = None
    elif name_base is not None:
        extrakwargs['base_marker'] = '|||||||'
        extrakwargs['name_base'] = name_base
        extrakwargs['minimize'] = False

    mergedtext = ""
    for line in m3.merge_lines(name_a=name_a, name_b=name_b,
                               **pycompat.strkwargs(extrakwargs)):
        if opts.get('print'):
            ui.fout.write(line)
        else:
            mergedtext += line

    if not opts.get('print'):
        localctx.write(mergedtext, localctx.flags())

    if m3.conflicts and not mode == 'union':
        return 1