/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 bzrlib/multiparent.py

  • Committer: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

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