/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-02-18 21:42:57 UTC
  • mto: This revision was merged to the branch mainline in revision 6859.
  • Revision ID: jelmer@jelmer.uk-20180218214257-jpevutp1wa30tz3v
Update TODO to reference Breezy, not Bazaar.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
 
18
 
17
19
import errno
18
 
from io import (
19
 
    BytesIO,
20
 
    )
21
20
import os
22
21
 
23
22
from .lazy_import import lazy_import
25
24
lazy_import(globals(), """
26
25
import gzip
27
26
import itertools
28
 
import patiencediff
29
27
 
30
28
from breezy import (
31
29
    bencode,
 
30
    errors,
 
31
    patiencediff,
32
32
    ui,
33
33
    )
34
34
""")
35
 
from . import (
36
 
    errors,
 
35
from .sixish import (
 
36
    BytesIO,
 
37
    range,
37
38
    )
38
 
from .i18n import gettext
39
39
 
40
40
 
41
41
def topo_iter_keys(vf, keys=None):
44
44
    parents = vf.get_parent_map(keys)
45
45
    return _topo_iter(parents, keys)
46
46
 
47
 
 
48
47
def topo_iter(vf, versions=None):
49
48
    if versions is None:
50
49
        versions = vf.versions()
51
50
    parents = vf.get_parent_map(versions)
52
51
    return _topo_iter(parents, versions)
53
52
 
54
 
 
55
53
def _topo_iter(parents, versions):
56
54
    seen = set()
57
55
    descendants = {}
58
 
 
59
56
    def pending_parents(version):
60
57
        if parents[version] is None:
61
58
            return []
119
116
        parent_text = []
120
117
        block_iter = [iter(i) for i in parent_comparisons]
121
118
        diff = MultiParent([])
122
 
 
123
119
        def next_block(p):
124
120
            try:
125
121
                return next(block_iter[p])
190
186
                yield line
191
187
 
192
188
    def patch_len(self):
193
 
        return len(b''.join(self.to_patch()))
 
189
        return len(''.join(self.to_patch()))
194
190
 
195
191
    def zipped_patch_len(self):
196
192
        return len(gzip_string(self.to_patch()))
206
202
        line_iter = iter(lines)
207
203
        hunks = []
208
204
        cur_line = None
209
 
        while True:
 
205
        while(True):
210
206
            try:
211
207
                cur_line = next(line_iter)
212
208
            except StopIteration:
213
209
                break
214
 
            first_char = cur_line[0:1]
215
 
            if first_char == b'i':
216
 
                num_lines = int(cur_line.split(b' ')[1])
 
210
            if cur_line[0] == 'i':
 
211
                num_lines = int(cur_line.split(' ')[1])
217
212
                hunk_lines = [next(line_iter) for _ in range(num_lines)]
218
213
                hunk_lines[-1] = hunk_lines[-1][:-1]
219
214
                hunks.append(NewText(hunk_lines))
220
 
            elif first_char == b'\n':
221
 
                hunks[-1].lines[-1] += b'\n'
 
215
            elif cur_line[0] == '\n':
 
216
                hunks[-1].lines[-1] += '\n'
222
217
            else:
223
 
                if not (first_char == b'c'):
224
 
                    raise AssertionError(first_char)
 
218
                if not (cur_line[0] == 'c'):
 
219
                    raise AssertionError(cur_line[0])
225
220
                parent, parent_pos, child_pos, num_lines =\
226
 
                    [int(v) for v in cur_line.split(b' ')[1:]]
 
221
                    [int(v) for v in cur_line.split(' ')[1:]]
227
222
                hunks.append(ParentText(parent, parent_pos, child_pos,
228
223
                                        num_lines))
229
224
        return MultiParent(hunks)
256
251
        extra_n = 0
257
252
        for hunk in reversed(self.hunks):
258
253
            if isinstance(hunk, ParentText):
259
 
                return hunk.child_pos + hunk.num_lines + extra_n
 
254
               return hunk.child_pos + hunk.num_lines + extra_n
260
255
            extra_n += len(hunk.lines)
261
256
        return extra_n
262
257
 
284
279
        return 'NewText(%r)' % self.lines
285
280
 
286
281
    def to_patch(self):
287
 
        yield b'i %d\n' % len(self.lines)
 
282
        yield 'i %d\n' % len(self.lines)
288
283
        for line in self.lines:
289
284
            yield line
290
 
        yield b'\n'
 
285
        yield '\n'
291
286
 
292
287
 
293
288
class ParentText(object):
302
297
        self.num_lines = num_lines
303
298
 
304
299
    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}
 
300
        return dict(parent=self.parent, parent_pos=self.parent_pos,
 
301
                    child_pos=self.child_pos, num_lines=self.num_lines)
309
302
 
310
303
    def __repr__(self):
311
304
        return ('ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'
317
310
        return self._as_dict() == other._as_dict()
318
311
 
319
312
    def to_patch(self):
320
 
        yield (b'c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'
 
313
        yield ('c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'
321
314
               % self._as_dict())
322
315
 
323
316
 
342
335
        if self.snapshot_interval is None:
343
336
            return False
344
337
        if self.max_snapshots is not None and\
345
 
                len(self._snapshots) == self.max_snapshots:
 
338
            len(self._snapshots) == self.max_snapshots:
346
339
            return False
347
340
        if len(parent_ids) == 0:
348
341
            return True
410
403
            raise ValueError()
411
404
        revisions = set(vf.versions())
412
405
        total = len(revisions)
413
 
        with ui.ui_factory.nested_progress_bar() as pb:
 
406
        pb = ui.ui_factory.nested_progress_bar()
 
407
        try:
414
408
            while len(revisions) > 0:
415
409
                added = set()
416
410
                for revision in revisions:
417
411
                    parents = vf.get_parents(revision)
418
412
                    if [p for p in parents if p not in self._parents] != []:
419
413
                        continue
420
 
                    lines = [a + b' ' + l for a, l in
 
414
                    lines = [a + ' ' + l for a, l in
421
415
                             vf.annotate(revision)]
422
416
                    if snapshots is None:
423
417
                        force_snapshot = None
436
430
                    pb.update(gettext('Importing revisions'),
437
431
                              (total - len(revisions)) + len(added), total)
438
432
                revisions = [r for r in revisions if r not in added]
 
433
        finally:
 
434
            pb.finished()
439
435
 
440
436
    def select_snapshots(self, vf):
441
437
        """Determine which versions to add as snapshots"""
442
438
        build_ancestors = {}
 
439
        descendants = {}
443
440
        snapshots = set()
444
441
        for version_id in topo_iter(vf):
445
442
            potential_build_ancestors = set(vf.get_parents(version_id))
466
463
    def get_size_ranking(self):
467
464
        """Get versions ranked by size"""
468
465
        versions = []
 
466
        new_snapshots = set()
469
467
        for version_id in self.versions():
470
468
            if version_id in self._snapshots:
471
469
                continue
499
497
        ranking = []
500
498
        while len(available_versions) > 0:
501
499
            available_versions.sort(key=lambda x:
502
 
                                    len(could_avoid[x]) *
503
 
                                    len(referenced_by.get(x, [])))
 
500
                len(could_avoid[x]) *
 
501
                len(referenced_by.get(x, [])))
504
502
            selected = available_versions.pop()
505
503
            ranking.append(selected)
506
504
            for version_id in referenced_by[selected]:
562
560
 
563
561
    def get_diff(self, version_id):
564
562
        start, count = self._diff_offset[version_id]
565
 
        with open(self._filename + '.mpknit', 'rb') as infile:
 
563
        infile = open(self._filename + '.mpknit', 'rb')
 
564
        try:
566
565
            infile.seek(start)
567
566
            sio = BytesIO(infile.read(count))
568
 
        with gzip.GzipFile(None, mode='rb', fileobj=sio) as zip_file:
 
567
        finally:
 
568
            infile.close()
 
569
        zip_file = gzip.GzipFile(None, mode='rb', fileobj=sio)
 
570
        try:
569
571
            file_version_id = zip_file.readline()
570
572
            content = zip_file.read()
571
573
            return MultiParent.from_patch(content)
 
574
        finally:
 
575
            zip_file.close()
572
576
 
573
577
    def add_diff(self, diff, version_id, parent_ids):
574
 
        with open(self._filename + '.mpknit', 'ab') as outfile:
 
578
        outfile = open(self._filename + '.mpknit', 'ab')
 
579
        try:
575
580
            outfile.seek(0, 2)      # workaround for windows bug:
576
 
            # .tell() for files opened in 'ab' mode
577
 
            # before any write returns 0
 
581
                                    # .tell() for files opened in 'ab' mode
 
582
                                    # before any write returns 0
578
583
            start = outfile.tell()
579
 
            with gzip.GzipFile(None, mode='ab', fileobj=outfile) as zipfile:
 
584
            try:
 
585
                zipfile = gzip.GzipFile(None, mode='ab', fileobj=outfile)
580
586
                zipfile.writelines(itertools.chain(
581
 
                    [b'version %s\n' % version_id], diff.to_patch()))
 
587
                    ['version %s\n' % version_id], diff.to_patch()))
 
588
            finally:
 
589
                zipfile.close()
582
590
            end = outfile.tell()
583
 
        self._diff_offset[version_id] = (start, end - start)
 
591
        finally:
 
592
            outfile.close()
 
593
        self._diff_offset[version_id] = (start, end-start)
584
594
        self._parents[version_id] = parent_ids
585
595
 
586
596
    def destroy(self):
669
679
 
670
680
def gzip_string(lines):
671
681
    sio = BytesIO()
672
 
    with gzip.GzipFile(None, mode='wb', fileobj=sio) as data_file:
673
 
        data_file.writelines(lines)
 
682
    data_file = gzip.GzipFile(None, mode='wb', fileobj=sio)
 
683
    data_file.writelines(lines)
 
684
    data_file.close()
674
685
    return sio.getvalue()