1
# Copyright (C) 2007-2011 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
from __future__ import absolute_import
19
from bzrlib.lazy_import import lazy_import
21
lazy_import(globals(), """
26
from StringIO import StringIO
37
def topo_iter_keys(vf, keys=None):
40
parents = vf.get_parent_map(keys)
41
return _topo_iter(parents, keys)
43
def topo_iter(vf, versions=None):
45
versions = vf.versions()
46
parents = vf.get_parent_map(versions)
47
return _topo_iter(parents, versions)
49
def _topo_iter(parents, versions):
52
def pending_parents(version):
53
if parents[version] is None:
55
return [v for v in parents[version] if v in versions and
57
for version_id in versions:
58
if parents[version_id] is None:
61
for parent_id in parents[version_id]:
62
descendants.setdefault(parent_id, []).append(version_id)
63
cur = [v for v in versions if len(pending_parents(v)) == 0]
66
for version_id in cur:
67
if version_id in seen:
69
if len(pending_parents(version_id)) != 0:
71
next.extend(descendants.get(version_id, []))
77
class MultiParent(object):
78
"""A multi-parent diff"""
82
def __init__(self, hunks=None):
89
return "MultiParent(%r)" % self.hunks
91
def __eq__(self, other):
92
if self.__class__ is not other.__class__:
94
return (self.hunks == other.hunks)
97
def from_lines(text, parents=(), left_blocks=None):
98
"""Produce a MultiParent from a list of lines and parents"""
100
matcher = patiencediff.PatienceSequenceMatcher(None, parent,
102
return matcher.get_matching_blocks()
104
if left_blocks is None:
105
left_blocks = compare(parents[0])
106
parent_comparisons = [left_blocks] + [compare(p) for p in
109
parent_comparisons = []
111
new_text = NewText([])
113
block_iter = [iter(i) for i in parent_comparisons]
114
diff = MultiParent([])
117
return block_iter[p].next()
118
except StopIteration:
120
cur_block = [next_block(p) for p, i in enumerate(block_iter)]
121
while cur_line < len(text):
123
for p, block in enumerate(cur_block):
127
while j + n <= cur_line:
128
block = cur_block[p] = next_block(p)
136
offset = cur_line - j
142
if best_match is None or n > best_match.num_lines:
143
best_match = ParentText(p, i, j, n)
144
if best_match is None:
145
new_text.lines.append(text[cur_line])
148
if len(new_text.lines) > 0:
149
diff.hunks.append(new_text)
150
new_text = NewText([])
151
diff.hunks.append(best_match)
152
cur_line += best_match.num_lines
153
if len(new_text.lines) > 0:
154
diff.hunks.append(new_text)
157
def get_matching_blocks(self, parent, parent_len):
158
for hunk in self.hunks:
159
if not isinstance(hunk, ParentText) or hunk.parent != parent:
161
yield (hunk.parent_pos, hunk.child_pos, hunk.num_lines)
162
yield parent_len, self.num_lines(), 0
164
def to_lines(self, parents=()):
165
"""Contruct a fulltext from this diff and its parents"""
166
mpvf = MultiMemoryVersionedFile()
167
for num, parent in enumerate(parents):
168
mpvf.add_version(StringIO(parent).readlines(), num, [])
169
mpvf.add_diff(self, 'a', range(len(parents)))
170
return mpvf.get_line_list(['a'])[0]
173
def from_texts(cls, text, parents=()):
174
"""Produce a MultiParent from a text and list of parent text"""
175
return cls.from_lines(StringIO(text).readlines(),
176
[StringIO(p).readlines() for p in parents])
179
"""Yield text lines for a patch"""
180
for hunk in self.hunks:
181
for line in hunk.to_patch():
185
return len(''.join(self.to_patch()))
187
def zipped_patch_len(self):
188
return len(gzip_string(self.to_patch()))
191
def from_patch(cls, text):
192
"""Create a MultiParent from its string form"""
193
return cls._from_patch(StringIO(text))
196
def _from_patch(lines):
197
"""This is private because it is essential to split lines on \n only"""
198
line_iter = iter(lines)
203
cur_line = line_iter.next()
204
except StopIteration:
206
if cur_line[0] == 'i':
207
num_lines = int(cur_line.split(' ')[1])
208
hunk_lines = [line_iter.next() for x in xrange(num_lines)]
209
hunk_lines[-1] = hunk_lines[-1][:-1]
210
hunks.append(NewText(hunk_lines))
211
elif cur_line[0] == '\n':
212
hunks[-1].lines[-1] += '\n'
214
if not (cur_line[0] == 'c'):
215
raise AssertionError(cur_line[0])
216
parent, parent_pos, child_pos, num_lines =\
217
[int(v) for v in cur_line.split(' ')[1:]]
218
hunks.append(ParentText(parent, parent_pos, child_pos,
220
return MultiParent(hunks)
222
def range_iterator(self):
223
"""Iterate through the hunks, with range indicated
225
kind is "new" or "parent".
226
for "new", data is a list of lines.
227
for "parent", data is (parent, parent_start, parent_end)
228
:return: a generator of (start, end, kind, data)
231
for hunk in self.hunks:
232
if isinstance(hunk, NewText):
234
end = start + len(hunk.lines)
238
start = hunk.child_pos
239
end = start + hunk.num_lines
240
data = (hunk.parent, hunk.parent_pos, hunk.parent_pos +
242
yield start, end, kind, data
246
"""The number of lines in the output text"""
248
for hunk in reversed(self.hunks):
249
if isinstance(hunk, ParentText):
250
return hunk.child_pos + hunk.num_lines + extra_n
251
extra_n += len(hunk.lines)
254
def is_snapshot(self):
255
"""Return true of this hunk is effectively a fulltext"""
256
if len(self.hunks) != 1:
258
return (isinstance(self.hunks[0], NewText))
261
class NewText(object):
262
"""The contents of text that is introduced by this text"""
264
__slots__ = ['lines']
266
def __init__(self, lines):
269
def __eq__(self, other):
270
if self.__class__ is not other.__class__:
272
return (other.lines == self.lines)
275
return 'NewText(%r)' % self.lines
278
yield 'i %d\n' % len(self.lines)
279
for line in self.lines:
284
class ParentText(object):
285
"""A reference to text present in a parent text"""
287
__slots__ = ['parent', 'parent_pos', 'child_pos', 'num_lines']
289
def __init__(self, parent, parent_pos, child_pos, num_lines):
291
self.parent_pos = parent_pos
292
self.child_pos = child_pos
293
self.num_lines = num_lines
296
return dict(parent=self.parent, parent_pos=self.parent_pos,
297
child_pos=self.child_pos, num_lines=self.num_lines)
300
return ('ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'
301
' %(num_lines)r)' % self._as_dict())
303
def __eq__(self, other):
304
if self.__class__ is not other.__class__:
306
return self._as_dict() == other._as_dict()
309
yield ('c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'
313
class BaseVersionedFile(object):
314
"""Pseudo-VersionedFile skeleton for MultiParent"""
316
def __init__(self, snapshot_interval=25, max_snapshots=None):
319
self._snapshots = set()
320
self.snapshot_interval = snapshot_interval
321
self.max_snapshots = max_snapshots
324
return iter(self._parents)
326
def has_version(self, version):
327
return version in self._parents
329
def do_snapshot(self, version_id, parent_ids):
330
"""Determine whether to perform a snapshot for this version"""
331
if self.snapshot_interval is None:
333
if self.max_snapshots is not None and\
334
len(self._snapshots) == self.max_snapshots:
336
if len(parent_ids) == 0:
338
for ignored in xrange(self.snapshot_interval):
339
if len(parent_ids) == 0:
341
version_ids = parent_ids
343
for version_id in version_ids:
344
if version_id not in self._snapshots:
345
parent_ids.extend(self._parents[version_id])
349
def add_version(self, lines, version_id, parent_ids,
350
force_snapshot=None, single_parent=False):
351
"""Add a version to the versionedfile
353
:param lines: The list of lines to add. Must be split on '\n'.
354
:param version_id: The version_id of the version to add
355
:param force_snapshot: If true, force this version to be added as a
356
snapshot version. If false, force this version to be added as a
357
diff. If none, determine this automatically.
358
:param single_parent: If true, use a single parent, rather than
361
if force_snapshot is None:
362
do_snapshot = self.do_snapshot(version_id, parent_ids)
364
do_snapshot = force_snapshot
366
self._snapshots.add(version_id)
367
diff = MultiParent([NewText(lines)])
370
parent_lines = self.get_line_list(parent_ids[:1])
372
parent_lines = self.get_line_list(parent_ids)
373
diff = MultiParent.from_lines(lines, parent_lines)
374
if diff.is_snapshot():
375
self._snapshots.add(version_id)
376
self.add_diff(diff, version_id, parent_ids)
377
self._lines[version_id] = lines
379
def get_parents(self, version_id):
380
return self._parents[version_id]
382
def make_snapshot(self, version_id):
383
snapdiff = MultiParent([NewText(self.cache_version(version_id))])
384
self.add_diff(snapdiff, version_id, self._parents[version_id])
385
self._snapshots.add(version_id)
387
def import_versionedfile(self, vf, snapshots, no_cache=True,
388
single_parent=False, verify=False):
389
"""Import all revisions of a versionedfile
391
:param vf: The versionedfile to import
392
:param snapshots: If provided, the revisions to make snapshots of.
393
Otherwise, this will be auto-determined
394
:param no_cache: If true, clear the cache after every add.
395
:param single_parent: If true, omit all but one parent text, (but
396
retain parent metadata).
398
if not (no_cache or not verify):
400
revisions = set(vf.versions())
401
total = len(revisions)
402
pb = ui.ui_factory.nested_progress_bar()
404
while len(revisions) > 0:
406
for revision in revisions:
407
parents = vf.get_parents(revision)
408
if [p for p in parents if p not in self._parents] != []:
410
lines = [a + ' ' + l for a, l in
411
vf.annotate(revision)]
412
if snapshots is None:
413
force_snapshot = None
415
force_snapshot = (revision in snapshots)
416
self.add_version(lines, revision, parents, force_snapshot,
423
if not (lines == self.get_line_list([revision])[0]):
424
raise AssertionError()
426
pb.update(gettext('Importing revisions'),
427
(total - len(revisions)) + len(added), total)
428
revisions = [r for r in revisions if r not in added]
432
def select_snapshots(self, vf):
433
"""Determine which versions to add as snapshots"""
437
for version_id in topo_iter(vf):
438
potential_build_ancestors = set(vf.get_parents(version_id))
439
parents = vf.get_parents(version_id)
440
if len(parents) == 0:
441
snapshots.add(version_id)
442
build_ancestors[version_id] = set()
444
for parent in vf.get_parents(version_id):
445
potential_build_ancestors.update(build_ancestors[parent])
446
if len(potential_build_ancestors) > self.snapshot_interval:
447
snapshots.add(version_id)
448
build_ancestors[version_id] = set()
450
build_ancestors[version_id] = potential_build_ancestors
453
def select_by_size(self, num):
454
"""Select snapshots for minimum output size"""
455
num -= len(self._snapshots)
456
new_snapshots = self.get_size_ranking()[-num:]
457
return [v for n, v in new_snapshots]
459
def get_size_ranking(self):
460
"""Get versions ranked by size"""
462
new_snapshots = set()
463
for version_id in self.versions():
464
if version_id in self._snapshots:
466
diff_len = self.get_diff(version_id).patch_len()
467
snapshot_len = MultiParent([NewText(
468
self.cache_version(version_id))]).patch_len()
469
versions.append((snapshot_len - diff_len, version_id))
473
def import_diffs(self, vf):
474
"""Import the diffs from another pseudo-versionedfile"""
475
for version_id in vf.versions():
476
self.add_diff(vf.get_diff(version_id), version_id,
477
vf._parents[version_id])
479
def get_build_ranking(self):
480
"""Return revisions sorted by how much they reduce build complexity"""
483
for version_id in topo_iter(self):
484
could_avoid[version_id] = set()
485
if version_id not in self._snapshots:
486
for parent_id in self._parents[version_id]:
487
could_avoid[version_id].update(could_avoid[parent_id])
488
could_avoid[version_id].update(self._parents)
489
could_avoid[version_id].discard(version_id)
490
for avoid_id in could_avoid[version_id]:
491
referenced_by.setdefault(avoid_id, set()).add(version_id)
492
available_versions = list(self.versions())
494
while len(available_versions) > 0:
495
available_versions.sort(key=lambda x:
496
len(could_avoid[x]) *
497
len(referenced_by.get(x, [])))
498
selected = available_versions.pop()
499
ranking.append(selected)
500
for version_id in referenced_by[selected]:
501
could_avoid[version_id].difference_update(
502
could_avoid[selected])
503
for version_id in could_avoid[selected]:
504
referenced_by[version_id].difference_update(
505
referenced_by[selected]
509
def clear_cache(self):
512
def get_line_list(self, version_ids):
513
return [self.cache_version(v) for v in version_ids]
515
def cache_version(self, version_id):
517
return self._lines[version_id]
520
diff = self.get_diff(version_id)
522
reconstructor = _Reconstructor(self, self._lines, self._parents)
523
reconstructor.reconstruct_version(lines, version_id)
524
self._lines[version_id] = lines
528
class MultiMemoryVersionedFile(BaseVersionedFile):
529
"""Memory-backed pseudo-versionedfile"""
531
def __init__(self, snapshot_interval=25, max_snapshots=None):
532
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
535
def add_diff(self, diff, version_id, parent_ids):
536
self._diffs[version_id] = diff
537
self._parents[version_id] = parent_ids
539
def get_diff(self, version_id):
541
return self._diffs[version_id]
543
raise errors.RevisionNotPresent(version_id, self)
549
class MultiVersionedFile(BaseVersionedFile):
550
"""Disk-backed pseudo-versionedfile"""
552
def __init__(self, filename, snapshot_interval=25, max_snapshots=None):
553
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
554
self._filename = filename
555
self._diff_offset = {}
557
def get_diff(self, version_id):
558
start, count = self._diff_offset[version_id]
559
infile = open(self._filename + '.mpknit', 'rb')
562
sio = StringIO(infile.read(count))
565
zip_file = gzip.GzipFile(None, mode='rb', fileobj=sio)
567
file_version_id = zip_file.readline()
568
content = zip_file.read()
569
return MultiParent.from_patch(content)
573
def add_diff(self, diff, version_id, parent_ids):
574
outfile = open(self._filename + '.mpknit', 'ab')
576
outfile.seek(0, 2) # workaround for windows bug:
577
# .tell() for files opened in 'ab' mode
578
# before any write returns 0
579
start = outfile.tell()
581
zipfile = gzip.GzipFile(None, mode='ab', fileobj=outfile)
582
zipfile.writelines(itertools.chain(
583
['version %s\n' % version_id], diff.to_patch()))
589
self._diff_offset[version_id] = (start, end-start)
590
self._parents[version_id] = parent_ids
594
os.unlink(self._filename + '.mpknit')
596
if e.errno != errno.ENOENT:
599
os.unlink(self._filename + '.mpidx')
601
if e.errno != errno.ENOENT:
605
open(self._filename + '.mpidx', 'wb').write(bencode.bencode(
606
(self._parents, list(self._snapshots), self._diff_offset)))
609
self._parents, snapshots, self._diff_offset = bencode.bdecode(
610
open(self._filename + '.mpidx', 'rb').read())
611
self._snapshots = set(snapshots)
614
class _Reconstructor(object):
615
"""Build a text from the diffs, ancestry graph and cached lines"""
617
def __init__(self, diffs, lines, parents):
620
self.parents = parents
623
def reconstruct(self, lines, parent_text, version_id):
624
"""Append the lines referred to by a ParentText to lines"""
625
parent_id = self.parents[version_id][parent_text.parent]
626
end = parent_text.parent_pos + parent_text.num_lines
627
return self._reconstruct(lines, parent_id, parent_text.parent_pos,
630
def _reconstruct(self, lines, req_version_id, req_start, req_end):
631
"""Append lines for the requested version_id range"""
632
# stack of pending range requests
633
if req_start == req_end:
635
pending_reqs = [(req_version_id, req_start, req_end)]
636
while len(pending_reqs) > 0:
637
req_version_id, req_start, req_end = pending_reqs.pop()
638
# lazily allocate cursors for versions
639
if req_version_id in self.lines:
640
lines.extend(self.lines[req_version_id][req_start:req_end])
643
start, end, kind, data, iterator = self.cursor[req_version_id]
645
iterator = self.diffs.get_diff(req_version_id).range_iterator()
646
start, end, kind, data = iterator.next()
647
if start > req_start:
648
iterator = self.diffs.get_diff(req_version_id).range_iterator()
649
start, end, kind, data = iterator.next()
651
# find the first hunk relevant to the request
652
while end <= req_start:
653
start, end, kind, data = iterator.next()
654
self.cursor[req_version_id] = start, end, kind, data, iterator
655
# if the hunk can't satisfy the whole request, split it in two,
656
# and leave the second half for later.
658
pending_reqs.append((req_version_id, end, req_end))
661
lines.extend(data[req_start - start: (req_end - start)])
663
# If the hunk is a ParentText, rewrite it as a range request
664
# for the parent, and make it the next pending request.
665
parent, parent_start, parent_end = data
666
new_version_id = self.parents[req_version_id][parent]
667
new_start = parent_start + req_start - start
668
new_end = parent_end + req_end - end
669
pending_reqs.append((new_version_id, new_start, new_end))
671
def reconstruct_version(self, lines, version_id):
672
length = self.diffs.get_diff(version_id).num_lines()
673
return self._reconstruct(lines, version_id, 0, length)
676
def gzip_string(lines):
678
data_file = gzip.GzipFile(None, mode='wb', fileobj=sio)
679
data_file.writelines(lines)
681
return sio.getvalue()