/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: Breezy landing bot
  • Author(s): Jelmer Vernooij
  • Date: 2018-11-16 11:31:40 UTC
  • mfrom: (7143.12.3 annotated-tags)
  • Revision ID: breezy.the.bot@gmail.com-20181116113140-618u04763u0dyxnh
Fix fetching of revisions that are referenced by annotated tags.

Merged from https://code.launchpad.net/~jelmer/brz/annotated-tags/+merge/358536

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):
76
81
class MultiParent(object):
77
82
    """A multi-parent diff"""
78
83
 
 
84
    __slots__ = ['hunks']
 
85
 
79
86
    def __init__(self, hunks=None):
80
87
        if hunks is not None:
81
88
            self.hunks = hunks
111
118
        diff = MultiParent([])
112
119
        def next_block(p):
113
120
            try:
114
 
                return block_iter[p].next()
 
121
                return next(block_iter[p])
115
122
            except StopIteration:
116
123
                return None
117
124
        cur_block = [next_block(p) for p, i in enumerate(block_iter)]
162
169
        """Contruct a fulltext from this diff and its parents"""
163
170
        mpvf = MultiMemoryVersionedFile()
164
171
        for num, parent in enumerate(parents):
165
 
            mpvf.add_version(StringIO(parent).readlines(), num, [])
166
 
        mpvf.add_diff(self, 'a', range(len(parents)))
 
172
            mpvf.add_version(BytesIO(parent).readlines(), num, [])
 
173
        mpvf.add_diff(self, 'a', list(range(len(parents))))
167
174
        return mpvf.get_line_list(['a'])[0]
168
175
 
169
176
    @classmethod
170
177
    def from_texts(cls, text, parents=()):
171
178
        """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])
 
179
        return cls.from_lines(BytesIO(text).readlines(),
 
180
                              [BytesIO(p).readlines() for p in parents])
174
181
 
175
182
    def to_patch(self):
176
183
        """Yield text lines for a patch"""
179
186
                yield line
180
187
 
181
188
    def patch_len(self):
182
 
        return len(''.join(self.to_patch()))
 
189
        return len(b''.join(self.to_patch()))
183
190
 
184
191
    def zipped_patch_len(self):
185
192
        return len(gzip_string(self.to_patch()))
187
194
    @classmethod
188
195
    def from_patch(cls, text):
189
196
        """Create a MultiParent from its string form"""
190
 
        return cls._from_patch(StringIO(text))
 
197
        return cls._from_patch(BytesIO(text))
191
198
 
192
199
    @staticmethod
193
200
    def _from_patch(lines):
195
202
        line_iter = iter(lines)
196
203
        hunks = []
197
204
        cur_line = None
198
 
        while(True):
 
205
        while True:
199
206
            try:
200
 
                cur_line = line_iter.next()
 
207
                cur_line = next(line_iter)
201
208
            except StopIteration:
202
209
                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)]
 
210
            first_char = cur_line[0:1]
 
211
            if first_char == b'i':
 
212
                num_lines = int(cur_line.split(b' ')[1])
 
213
                hunk_lines = [next(line_iter) for _ in range(num_lines)]
206
214
                hunk_lines[-1] = hunk_lines[-1][:-1]
207
215
                hunks.append(NewText(hunk_lines))
208
 
            elif cur_line[0] == '\n':
209
 
                hunks[-1].lines[-1] += '\n'
 
216
            elif first_char == b'\n':
 
217
                hunks[-1].lines[-1] += b'\n'
210
218
            else:
211
 
                if not (cur_line[0] == 'c'):
212
 
                    raise AssertionError(cur_line[0])
 
219
                if not (first_char == b'c'):
 
220
                    raise AssertionError(first_char)
213
221
                parent, parent_pos, child_pos, num_lines =\
214
 
                    [int(v) for v in cur_line.split(' ')[1:]]
 
222
                    [int(v) for v in cur_line.split(b' ')[1:]]
215
223
                hunks.append(ParentText(parent, parent_pos, child_pos,
216
224
                                        num_lines))
217
225
        return MultiParent(hunks)
258
266
class NewText(object):
259
267
    """The contents of text that is introduced by this text"""
260
268
 
 
269
    __slots__ = ['lines']
 
270
 
261
271
    def __init__(self, lines):
262
272
        self.lines = lines
263
273
 
270
280
        return 'NewText(%r)' % self.lines
271
281
 
272
282
    def to_patch(self):
273
 
        yield 'i %d\n' % len(self.lines)
 
283
        yield b'i %d\n' % len(self.lines)
274
284
        for line in self.lines:
275
285
            yield line
276
 
        yield '\n'
 
286
        yield b'\n'
277
287
 
278
288
 
279
289
class ParentText(object):
280
290
    """A reference to text present in a parent text"""
281
291
 
 
292
    __slots__ = ['parent', 'parent_pos', 'child_pos', 'num_lines']
 
293
 
282
294
    def __init__(self, parent, parent_pos, child_pos, num_lines):
283
295
        self.parent = parent
284
296
        self.parent_pos = parent_pos
285
297
        self.child_pos = child_pos
286
298
        self.num_lines = num_lines
287
299
 
 
300
    def _as_dict(self):
 
301
        return {b'parent': self.parent,
 
302
                b'parent_pos': self.parent_pos,
 
303
                b'child_pos': self.child_pos,
 
304
                b'num_lines': self.num_lines}
 
305
 
288
306
    def __repr__(self):
289
 
        return 'ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'\
290
 
            ' %(num_lines)r)' % self.__dict__
 
307
        return ('ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'
 
308
                ' %(num_lines)r)' % self._as_dict())
291
309
 
292
310
    def __eq__(self, other):
293
311
        if self.__class__ is not other.__class__:
294
312
            return False
295
 
        return (self.__dict__ == other.__dict__)
 
313
        return self._as_dict() == other._as_dict()
296
314
 
297
315
    def to_patch(self):
298
 
        yield 'c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'\
299
 
            % self.__dict__
 
316
        yield (b'c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'
 
317
               % self._as_dict())
300
318
 
301
319
 
302
320
class BaseVersionedFile(object):
324
342
            return False
325
343
        if len(parent_ids) == 0:
326
344
            return True
327
 
        for ignored in xrange(self.snapshot_interval):
 
345
        for ignored in range(self.snapshot_interval):
328
346
            if len(parent_ids) == 0:
329
347
                return False
330
348
            version_ids = parent_ids
388
406
            raise ValueError()
389
407
        revisions = set(vf.versions())
390
408
        total = len(revisions)
391
 
        pb = ui.ui_factory.nested_progress_bar()
392
 
        try:
 
409
        with ui.ui_factory.nested_progress_bar() as pb:
393
410
            while len(revisions) > 0:
394
411
                added = set()
395
412
                for revision in revisions:
396
413
                    parents = vf.get_parents(revision)
397
414
                    if [p for p in parents if p not in self._parents] != []:
398
415
                        continue
399
 
                    lines = [a + ' ' + l for a, l in
 
416
                    lines = [a + b' ' + l for a, l in
400
417
                             vf.annotate(revision)]
401
418
                    if snapshots is None:
402
419
                        force_snapshot = None
412
429
                            if not (lines == self.get_line_list([revision])[0]):
413
430
                                raise AssertionError()
414
431
                            self.clear_cache()
415
 
                    pb.update('Importing revisions',
 
432
                    pb.update(gettext('Importing revisions'),
416
433
                              (total - len(revisions)) + len(added), total)
417
434
                revisions = [r for r in revisions if r not in added]
418
 
        finally:
419
 
            pb.finished()
420
435
 
421
436
    def select_snapshots(self, vf):
422
437
        """Determine which versions to add as snapshots"""
545
560
 
546
561
    def get_diff(self, version_id):
547
562
        start, count = self._diff_offset[version_id]
548
 
        infile = open(self._filename + '.mpknit', 'rb')
549
 
        try:
 
563
        with open(self._filename + '.mpknit', 'rb') as infile:
550
564
            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:
 
565
            sio = BytesIO(infile.read(count))
 
566
        with gzip.GzipFile(None, mode='rb', fileobj=sio) as zip_file:
556
567
            file_version_id = zip_file.readline()
557
 
            return MultiParent.from_patch(zip_file.read())
558
 
        finally:
559
 
            zip_file.close()
 
568
            content = zip_file.read()
 
569
            return MultiParent.from_patch(content)
560
570
 
561
571
    def add_diff(self, diff, version_id, parent_ids):
562
 
        outfile = open(self._filename + '.mpknit', 'ab')
563
 
        try:
 
572
        with open(self._filename + '.mpknit', 'ab') as outfile:
564
573
            outfile.seek(0, 2)      # workaround for windows bug:
565
574
                                    # .tell() for files opened in 'ab' mode
566
575
                                    # before any write returns 0
567
576
            start = outfile.tell()
568
 
            try:
569
 
                zipfile = GzipFile(None, mode='ab', fileobj=outfile)
 
577
            with gzip.GzipFile(None, mode='ab', fileobj=outfile) as zipfile:
570
578
                zipfile.writelines(itertools.chain(
571
 
                    ['version %s\n' % version_id], diff.to_patch()))
572
 
            finally:
573
 
                zipfile.close()
 
579
                    [b'version %s\n' % version_id], diff.to_patch()))
574
580
            end = outfile.tell()
575
 
        finally:
576
 
            outfile.close()
577
581
        self._diff_offset[version_id] = (start, end-start)
578
582
        self._parents[version_id] = parent_ids
579
583
 
580
584
    def destroy(self):
581
585
        try:
582
586
            os.unlink(self._filename + '.mpknit')
583
 
        except OSError, e:
 
587
        except OSError as e:
584
588
            if e.errno != errno.ENOENT:
585
589
                raise
586
590
        try:
587
591
            os.unlink(self._filename + '.mpidx')
588
 
        except OSError, e:
 
592
        except OSError as e:
589
593
            if e.errno != errno.ENOENT:
590
594
                raise
591
595
 
631
635
                start, end, kind, data, iterator = self.cursor[req_version_id]
632
636
            except KeyError:
633
637
                iterator = self.diffs.get_diff(req_version_id).range_iterator()
634
 
                start, end, kind, data = iterator.next()
 
638
                start, end, kind, data = next(iterator)
635
639
            if start > req_start:
636
640
                iterator = self.diffs.get_diff(req_version_id).range_iterator()
637
 
                start, end, kind, data = iterator.next()
 
641
                start, end, kind, data = next(iterator)
638
642
 
639
643
            # find the first hunk relevant to the request
640
644
            while end <= req_start:
641
 
                start, end, kind, data = iterator.next()
 
645
                start, end, kind, data = next(iterator)
642
646
            self.cursor[req_version_id] = start, end, kind, data, iterator
643
647
            # if the hunk can't satisfy the whole request, split it in two,
644
648
            # and leave the second half for later.
662
666
 
663
667
 
664
668
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()
 
669
    sio = BytesIO()
 
670
    with gzip.GzipFile(None, mode='wb', fileobj=sio) as data_file:
 
671
        data_file.writelines(lines)
669
672
    return sio.getvalue()