/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/multiparent.py

  • Committer: Jelmer Vernooij
  • Date: 2018-11-11 04:08:32 UTC
  • mto: (7143.16.20 even-more-cleanups)
  • mto: This revision was merged to the branch mainline in revision 7175.
  • Revision ID: jelmer@jelmer.uk-20181111040832-nsljjynzzwmznf3h
Run autopep8.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007 Canonical Ltd
 
1
# Copyright (C) 2007-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
from bzrlib.lazy_import import lazy_import
 
17
from __future__ import absolute_import
 
18
 
 
19
import errno
 
20
import os
 
21
 
 
22
from .lazy_import import lazy_import
18
23
 
19
24
lazy_import(globals(), """
20
 
import errno
 
25
import gzip
21
26
import itertools
22
 
import os
23
 
from StringIO import StringIO
24
27
 
25
 
from bzrlib import (
 
28
from breezy import (
 
29
    bencode,
26
30
    errors,
27
31
    patiencediff,
28
 
    trace,
29
32
    ui,
30
33
    )
31
 
from bzrlib import bencode
32
34
""")
33
 
from bzrlib.tuned_gzip import GzipFile
 
35
from .sixish import (
 
36
    BytesIO,
 
37
    range,
 
38
    )
34
39
 
35
40
 
36
41
def topo_iter_keys(vf, keys=None):
39
44
    parents = vf.get_parent_map(keys)
40
45
    return _topo_iter(parents, keys)
41
46
 
 
47
 
42
48
def topo_iter(vf, versions=None):
43
49
    if versions is None:
44
50
        versions = vf.versions()
45
51
    parents = vf.get_parent_map(versions)
46
52
    return _topo_iter(parents, versions)
47
53
 
 
54
 
48
55
def _topo_iter(parents, versions):
49
56
    seen = set()
50
57
    descendants = {}
 
58
 
51
59
    def pending_parents(version):
52
60
        if parents[version] is None:
53
61
            return []
76
84
class MultiParent(object):
77
85
    """A multi-parent diff"""
78
86
 
 
87
    __slots__ = ['hunks']
 
88
 
79
89
    def __init__(self, hunks=None):
80
90
        if hunks is not None:
81
91
            self.hunks = hunks
109
119
        parent_text = []
110
120
        block_iter = [iter(i) for i in parent_comparisons]
111
121
        diff = MultiParent([])
 
122
 
112
123
        def next_block(p):
113
124
            try:
114
 
                return block_iter[p].next()
 
125
                return next(block_iter[p])
115
126
            except StopIteration:
116
127
                return None
117
128
        cur_block = [next_block(p) for p, i in enumerate(block_iter)]
162
173
        """Contruct a fulltext from this diff and its parents"""
163
174
        mpvf = MultiMemoryVersionedFile()
164
175
        for num, parent in enumerate(parents):
165
 
            mpvf.add_version(StringIO(parent).readlines(), num, [])
166
 
        mpvf.add_diff(self, 'a', range(len(parents)))
 
176
            mpvf.add_version(BytesIO(parent).readlines(), num, [])
 
177
        mpvf.add_diff(self, 'a', list(range(len(parents))))
167
178
        return mpvf.get_line_list(['a'])[0]
168
179
 
169
180
    @classmethod
170
181
    def from_texts(cls, text, parents=()):
171
182
        """Produce a MultiParent from a text and list of parent text"""
172
 
        return cls.from_lines(StringIO(text).readlines(),
173
 
                              [StringIO(p).readlines() for p in parents])
 
183
        return cls.from_lines(BytesIO(text).readlines(),
 
184
                              [BytesIO(p).readlines() for p in parents])
174
185
 
175
186
    def to_patch(self):
176
187
        """Yield text lines for a patch"""
179
190
                yield line
180
191
 
181
192
    def patch_len(self):
182
 
        return len(''.join(self.to_patch()))
 
193
        return len(b''.join(self.to_patch()))
183
194
 
184
195
    def zipped_patch_len(self):
185
196
        return len(gzip_string(self.to_patch()))
187
198
    @classmethod
188
199
    def from_patch(cls, text):
189
200
        """Create a MultiParent from its string form"""
190
 
        return cls._from_patch(StringIO(text))
 
201
        return cls._from_patch(BytesIO(text))
191
202
 
192
203
    @staticmethod
193
204
    def _from_patch(lines):
195
206
        line_iter = iter(lines)
196
207
        hunks = []
197
208
        cur_line = None
198
 
        while(True):
 
209
        while True:
199
210
            try:
200
 
                cur_line = line_iter.next()
 
211
                cur_line = next(line_iter)
201
212
            except StopIteration:
202
213
                break
203
 
            if cur_line[0] == 'i':
204
 
                num_lines = int(cur_line.split(' ')[1])
205
 
                hunk_lines = [line_iter.next() for x in xrange(num_lines)]
 
214
            first_char = cur_line[0:1]
 
215
            if first_char == b'i':
 
216
                num_lines = int(cur_line.split(b' ')[1])
 
217
                hunk_lines = [next(line_iter) for _ in range(num_lines)]
206
218
                hunk_lines[-1] = hunk_lines[-1][:-1]
207
219
                hunks.append(NewText(hunk_lines))
208
 
            elif cur_line[0] == '\n':
209
 
                hunks[-1].lines[-1] += '\n'
 
220
            elif first_char == b'\n':
 
221
                hunks[-1].lines[-1] += b'\n'
210
222
            else:
211
 
                if not (cur_line[0] == 'c'):
212
 
                    raise AssertionError(cur_line[0])
 
223
                if not (first_char == b'c'):
 
224
                    raise AssertionError(first_char)
213
225
                parent, parent_pos, child_pos, num_lines =\
214
 
                    [int(v) for v in cur_line.split(' ')[1:]]
 
226
                    [int(v) for v in cur_line.split(b' ')[1:]]
215
227
                hunks.append(ParentText(parent, parent_pos, child_pos,
216
228
                                        num_lines))
217
229
        return MultiParent(hunks)
244
256
        extra_n = 0
245
257
        for hunk in reversed(self.hunks):
246
258
            if isinstance(hunk, ParentText):
247
 
               return hunk.child_pos + hunk.num_lines + extra_n
 
259
                return hunk.child_pos + hunk.num_lines + extra_n
248
260
            extra_n += len(hunk.lines)
249
261
        return extra_n
250
262
 
258
270
class NewText(object):
259
271
    """The contents of text that is introduced by this text"""
260
272
 
 
273
    __slots__ = ['lines']
 
274
 
261
275
    def __init__(self, lines):
262
276
        self.lines = lines
263
277
 
270
284
        return 'NewText(%r)' % self.lines
271
285
 
272
286
    def to_patch(self):
273
 
        yield 'i %d\n' % len(self.lines)
 
287
        yield b'i %d\n' % len(self.lines)
274
288
        for line in self.lines:
275
289
            yield line
276
 
        yield '\n'
 
290
        yield b'\n'
277
291
 
278
292
 
279
293
class ParentText(object):
280
294
    """A reference to text present in a parent text"""
281
295
 
 
296
    __slots__ = ['parent', 'parent_pos', 'child_pos', 'num_lines']
 
297
 
282
298
    def __init__(self, parent, parent_pos, child_pos, num_lines):
283
299
        self.parent = parent
284
300
        self.parent_pos = parent_pos
285
301
        self.child_pos = child_pos
286
302
        self.num_lines = num_lines
287
303
 
 
304
    def _as_dict(self):
 
305
        return {b'parent': self.parent,
 
306
                b'parent_pos': self.parent_pos,
 
307
                b'child_pos': self.child_pos,
 
308
                b'num_lines': self.num_lines}
 
309
 
288
310
    def __repr__(self):
289
 
        return 'ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'\
290
 
            ' %(num_lines)r)' % self.__dict__
 
311
        return ('ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'
 
312
                ' %(num_lines)r)' % self._as_dict())
291
313
 
292
314
    def __eq__(self, other):
293
315
        if self.__class__ is not other.__class__:
294
316
            return False
295
 
        return (self.__dict__ == other.__dict__)
 
317
        return self._as_dict() == other._as_dict()
296
318
 
297
319
    def to_patch(self):
298
 
        yield 'c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'\
299
 
            % self.__dict__
 
320
        yield (b'c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'
 
321
               % self._as_dict())
300
322
 
301
323
 
302
324
class BaseVersionedFile(object):
320
342
        if self.snapshot_interval is None:
321
343
            return False
322
344
        if self.max_snapshots is not None and\
323
 
            len(self._snapshots) == self.max_snapshots:
 
345
                len(self._snapshots) == self.max_snapshots:
324
346
            return False
325
347
        if len(parent_ids) == 0:
326
348
            return True
327
 
        for ignored in xrange(self.snapshot_interval):
 
349
        for ignored in range(self.snapshot_interval):
328
350
            if len(parent_ids) == 0:
329
351
                return False
330
352
            version_ids = parent_ids
388
410
            raise ValueError()
389
411
        revisions = set(vf.versions())
390
412
        total = len(revisions)
391
 
        pb = ui.ui_factory.nested_progress_bar()
392
 
        try:
 
413
        with ui.ui_factory.nested_progress_bar() as pb:
393
414
            while len(revisions) > 0:
394
415
                added = set()
395
416
                for revision in revisions:
396
417
                    parents = vf.get_parents(revision)
397
418
                    if [p for p in parents if p not in self._parents] != []:
398
419
                        continue
399
 
                    lines = [a + ' ' + l for a, l in
 
420
                    lines = [a + b' ' + l for a, l in
400
421
                             vf.annotate(revision)]
401
422
                    if snapshots is None:
402
423
                        force_snapshot = None
412
433
                            if not (lines == self.get_line_list([revision])[0]):
413
434
                                raise AssertionError()
414
435
                            self.clear_cache()
415
 
                    pb.update('Importing revisions',
 
436
                    pb.update(gettext('Importing revisions'),
416
437
                              (total - len(revisions)) + len(added), total)
417
438
                revisions = [r for r in revisions if r not in added]
418
 
        finally:
419
 
            pb.finished()
420
439
 
421
440
    def select_snapshots(self, vf):
422
441
        """Determine which versions to add as snapshots"""
482
501
        ranking = []
483
502
        while len(available_versions) > 0:
484
503
            available_versions.sort(key=lambda x:
485
 
                len(could_avoid[x]) *
486
 
                len(referenced_by.get(x, [])))
 
504
                                    len(could_avoid[x]) *
 
505
                                    len(referenced_by.get(x, [])))
487
506
            selected = available_versions.pop()
488
507
            ranking.append(selected)
489
508
            for version_id in referenced_by[selected]:
545
564
 
546
565
    def get_diff(self, version_id):
547
566
        start, count = self._diff_offset[version_id]
548
 
        infile = open(self._filename + '.mpknit', 'rb')
549
 
        try:
 
567
        with open(self._filename + '.mpknit', 'rb') as infile:
550
568
            infile.seek(start)
551
 
            sio = StringIO(infile.read(count))
552
 
        finally:
553
 
            infile.close()
554
 
        zip_file = GzipFile(None, mode='rb', fileobj=sio)
555
 
        try:
 
569
            sio = BytesIO(infile.read(count))
 
570
        with gzip.GzipFile(None, mode='rb', fileobj=sio) as zip_file:
556
571
            file_version_id = zip_file.readline()
557
 
            return MultiParent.from_patch(zip_file.read())
558
 
        finally:
559
 
            zip_file.close()
 
572
            content = zip_file.read()
 
573
            return MultiParent.from_patch(content)
560
574
 
561
575
    def add_diff(self, diff, version_id, parent_ids):
562
 
        outfile = open(self._filename + '.mpknit', 'ab')
563
 
        try:
 
576
        with open(self._filename + '.mpknit', 'ab') as outfile:
564
577
            outfile.seek(0, 2)      # workaround for windows bug:
565
 
                                    # .tell() for files opened in 'ab' mode
566
 
                                    # before any write returns 0
 
578
            # .tell() for files opened in 'ab' mode
 
579
            # before any write returns 0
567
580
            start = outfile.tell()
568
 
            try:
569
 
                zipfile = GzipFile(None, mode='ab', fileobj=outfile)
 
581
            with gzip.GzipFile(None, mode='ab', fileobj=outfile) as zipfile:
570
582
                zipfile.writelines(itertools.chain(
571
 
                    ['version %s\n' % version_id], diff.to_patch()))
572
 
            finally:
573
 
                zipfile.close()
 
583
                    [b'version %s\n' % version_id], diff.to_patch()))
574
584
            end = outfile.tell()
575
 
        finally:
576
 
            outfile.close()
577
 
        self._diff_offset[version_id] = (start, end-start)
 
585
        self._diff_offset[version_id] = (start, end - start)
578
586
        self._parents[version_id] = parent_ids
579
587
 
580
588
    def destroy(self):
581
589
        try:
582
590
            os.unlink(self._filename + '.mpknit')
583
 
        except OSError, e:
 
591
        except OSError as e:
584
592
            if e.errno != errno.ENOENT:
585
593
                raise
586
594
        try:
587
595
            os.unlink(self._filename + '.mpidx')
588
 
        except OSError, e:
 
596
        except OSError as e:
589
597
            if e.errno != errno.ENOENT:
590
598
                raise
591
599
 
631
639
                start, end, kind, data, iterator = self.cursor[req_version_id]
632
640
            except KeyError:
633
641
                iterator = self.diffs.get_diff(req_version_id).range_iterator()
634
 
                start, end, kind, data = iterator.next()
 
642
                start, end, kind, data = next(iterator)
635
643
            if start > req_start:
636
644
                iterator = self.diffs.get_diff(req_version_id).range_iterator()
637
 
                start, end, kind, data = iterator.next()
 
645
                start, end, kind, data = next(iterator)
638
646
 
639
647
            # find the first hunk relevant to the request
640
648
            while end <= req_start:
641
 
                start, end, kind, data = iterator.next()
 
649
                start, end, kind, data = next(iterator)
642
650
            self.cursor[req_version_id] = start, end, kind, data, iterator
643
651
            # if the hunk can't satisfy the whole request, split it in two,
644
652
            # and leave the second half for later.
662
670
 
663
671
 
664
672
def gzip_string(lines):
665
 
    sio = StringIO()
666
 
    data_file = GzipFile(None, mode='wb', fileobj=sio)
667
 
    data_file.writelines(lines)
668
 
    data_file.close()
 
673
    sio = BytesIO()
 
674
    with gzip.GzipFile(None, mode='wb', fileobj=sio) as data_file:
 
675
        data_file.writelines(lines)
669
676
    return sio.getvalue()