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 bzrlib.lazy_import import lazy_import
19
lazy_import(globals(), """
24
from StringIO import StringIO
35
def topo_iter_keys(vf, keys=None):
38
parents = vf.get_parent_map(keys)
39
return _topo_iter(parents, keys)
41
def topo_iter(vf, versions=None):
43
versions = vf.versions()
44
parents = vf.get_parent_map(versions)
45
return _topo_iter(parents, versions)
47
def _topo_iter(parents, versions):
50
def pending_parents(version):
51
if parents[version] is None:
53
return [v for v in parents[version] if v in versions and
55
for version_id in versions:
56
if parents[version_id] is None:
59
for parent_id in parents[version_id]:
60
descendants.setdefault(parent_id, []).append(version_id)
61
cur = [v for v in versions if len(pending_parents(v)) == 0]
64
for version_id in cur:
65
if version_id in seen:
67
if len(pending_parents(version_id)) != 0:
69
next.extend(descendants.get(version_id, []))
75
class MultiParent(object):
76
"""A multi-parent diff"""
80
def __init__(self, hunks=None):
87
return "MultiParent(%r)" % self.hunks
89
def __eq__(self, other):
90
if self.__class__ is not other.__class__:
92
return (self.hunks == other.hunks)
95
def from_lines(text, parents=(), left_blocks=None):
96
"""Produce a MultiParent from a list of lines and parents"""
98
matcher = patiencediff.PatienceSequenceMatcher(None, parent,
100
return matcher.get_matching_blocks()
102
if left_blocks is None:
103
left_blocks = compare(parents[0])
104
parent_comparisons = [left_blocks] + [compare(p) for p in
107
parent_comparisons = []
109
new_text = NewText([])
111
block_iter = [iter(i) for i in parent_comparisons]
112
diff = MultiParent([])
115
return block_iter[p].next()
116
except StopIteration:
118
cur_block = [next_block(p) for p, i in enumerate(block_iter)]
119
while cur_line < len(text):
121
for p, block in enumerate(cur_block):
125
while j + n <= cur_line:
126
block = cur_block[p] = next_block(p)
134
offset = cur_line - j
140
if best_match is None or n > best_match.num_lines:
141
best_match = ParentText(p, i, j, n)
142
if best_match is None:
143
new_text.lines.append(text[cur_line])
146
if len(new_text.lines) > 0:
147
diff.hunks.append(new_text)
148
new_text = NewText([])
149
diff.hunks.append(best_match)
150
cur_line += best_match.num_lines
151
if len(new_text.lines) > 0:
152
diff.hunks.append(new_text)
155
def get_matching_blocks(self, parent, parent_len):
156
for hunk in self.hunks:
157
if not isinstance(hunk, ParentText) or hunk.parent != parent:
159
yield (hunk.parent_pos, hunk.child_pos, hunk.num_lines)
160
yield parent_len, self.num_lines(), 0
162
def to_lines(self, parents=()):
163
"""Contruct a fulltext from this diff and its parents"""
164
mpvf = MultiMemoryVersionedFile()
165
for num, parent in enumerate(parents):
166
mpvf.add_version(StringIO(parent).readlines(), num, [])
167
mpvf.add_diff(self, 'a', range(len(parents)))
168
return mpvf.get_line_list(['a'])[0]
171
def from_texts(cls, text, parents=()):
172
"""Produce a MultiParent from a text and list of parent text"""
173
return cls.from_lines(StringIO(text).readlines(),
174
[StringIO(p).readlines() for p in parents])
177
"""Yield text lines for a patch"""
178
for hunk in self.hunks:
179
for line in hunk.to_patch():
183
return len(''.join(self.to_patch()))
185
def zipped_patch_len(self):
186
return len(gzip_string(self.to_patch()))
189
def from_patch(cls, text):
190
"""Create a MultiParent from its string form"""
191
return cls._from_patch(StringIO(text))
194
def _from_patch(lines):
195
"""This is private because it is essential to split lines on \n only"""
196
line_iter = iter(lines)
201
cur_line = line_iter.next()
202
except StopIteration:
204
if cur_line[0] == 'i':
205
num_lines = int(cur_line.split(' ')[1])
206
hunk_lines = [line_iter.next() for x in xrange(num_lines)]
207
hunk_lines[-1] = hunk_lines[-1][:-1]
208
hunks.append(NewText(hunk_lines))
209
elif cur_line[0] == '\n':
210
hunks[-1].lines[-1] += '\n'
212
if not (cur_line[0] == 'c'):
213
raise AssertionError(cur_line[0])
214
parent, parent_pos, child_pos, num_lines =\
215
[int(v) for v in cur_line.split(' ')[1:]]
216
hunks.append(ParentText(parent, parent_pos, child_pos,
218
return MultiParent(hunks)
220
def range_iterator(self):
221
"""Iterate through the hunks, with range indicated
223
kind is "new" or "parent".
224
for "new", data is a list of lines.
225
for "parent", data is (parent, parent_start, parent_end)
226
:return: a generator of (start, end, kind, data)
229
for hunk in self.hunks:
230
if isinstance(hunk, NewText):
232
end = start + len(hunk.lines)
236
start = hunk.child_pos
237
end = start + hunk.num_lines
238
data = (hunk.parent, hunk.parent_pos, hunk.parent_pos +
240
yield start, end, kind, data
244
"""The number of lines in the output text"""
246
for hunk in reversed(self.hunks):
247
if isinstance(hunk, ParentText):
248
return hunk.child_pos + hunk.num_lines + extra_n
249
extra_n += len(hunk.lines)
252
def is_snapshot(self):
253
"""Return true of this hunk is effectively a fulltext"""
254
if len(self.hunks) != 1:
256
return (isinstance(self.hunks[0], NewText))
259
class NewText(object):
260
"""The contents of text that is introduced by this text"""
262
__slots__ = ['lines']
264
def __init__(self, lines):
267
def __eq__(self, other):
268
if self.__class__ is not other.__class__:
270
return (other.lines == self.lines)
273
return 'NewText(%r)' % self.lines
276
yield 'i %d\n' % len(self.lines)
277
for line in self.lines:
282
class ParentText(object):
283
"""A reference to text present in a parent text"""
285
__slots__ = ['parent', 'parent_pos', 'child_pos', 'num_lines']
287
def __init__(self, parent, parent_pos, child_pos, num_lines):
289
self.parent_pos = parent_pos
290
self.child_pos = child_pos
291
self.num_lines = num_lines
294
return dict(parent=self.parent, parent_pos=self.parent_pos,
295
child_pos=self.child_pos, num_lines=self.num_lines)
298
return ('ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'
299
' %(num_lines)r)' % self._as_dict())
301
def __eq__(self, other):
302
if self.__class__ is not other.__class__:
304
return self._as_dict() == other._as_dict()
307
yield ('c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'
311
class BaseVersionedFile(object):
312
"""Pseudo-VersionedFile skeleton for MultiParent"""
314
def __init__(self, snapshot_interval=25, max_snapshots=None):
317
self._snapshots = set()
318
self.snapshot_interval = snapshot_interval
319
self.max_snapshots = max_snapshots
322
return iter(self._parents)
324
def has_version(self, version):
325
return version in self._parents
327
def do_snapshot(self, version_id, parent_ids):
328
"""Determine whether to perform a snapshot for this version"""
329
if self.snapshot_interval is None:
331
if self.max_snapshots is not None and\
332
len(self._snapshots) == self.max_snapshots:
334
if len(parent_ids) == 0:
336
for ignored in xrange(self.snapshot_interval):
337
if len(parent_ids) == 0:
339
version_ids = parent_ids
341
for version_id in version_ids:
342
if version_id not in self._snapshots:
343
parent_ids.extend(self._parents[version_id])
347
def add_version(self, lines, version_id, parent_ids,
348
force_snapshot=None, single_parent=False):
349
"""Add a version to the versionedfile
351
:param lines: The list of lines to add. Must be split on '\n'.
352
:param version_id: The version_id of the version to add
353
:param force_snapshot: If true, force this version to be added as a
354
snapshot version. If false, force this version to be added as a
355
diff. If none, determine this automatically.
356
:param single_parent: If true, use a single parent, rather than
359
if force_snapshot is None:
360
do_snapshot = self.do_snapshot(version_id, parent_ids)
362
do_snapshot = force_snapshot
364
self._snapshots.add(version_id)
365
diff = MultiParent([NewText(lines)])
368
parent_lines = self.get_line_list(parent_ids[:1])
370
parent_lines = self.get_line_list(parent_ids)
371
diff = MultiParent.from_lines(lines, parent_lines)
372
if diff.is_snapshot():
373
self._snapshots.add(version_id)
374
self.add_diff(diff, version_id, parent_ids)
375
self._lines[version_id] = lines
377
def get_parents(self, version_id):
378
return self._parents[version_id]
380
def make_snapshot(self, version_id):
381
snapdiff = MultiParent([NewText(self.cache_version(version_id))])
382
self.add_diff(snapdiff, version_id, self._parents[version_id])
383
self._snapshots.add(version_id)
385
def import_versionedfile(self, vf, snapshots, no_cache=True,
386
single_parent=False, verify=False):
387
"""Import all revisions of a versionedfile
389
:param vf: The versionedfile to import
390
:param snapshots: If provided, the revisions to make snapshots of.
391
Otherwise, this will be auto-determined
392
:param no_cache: If true, clear the cache after every add.
393
:param single_parent: If true, omit all but one parent text, (but
394
retain parent metadata).
396
if not (no_cache or not verify):
398
revisions = set(vf.versions())
399
total = len(revisions)
400
pb = ui.ui_factory.nested_progress_bar()
402
while len(revisions) > 0:
404
for revision in revisions:
405
parents = vf.get_parents(revision)
406
if [p for p in parents if p not in self._parents] != []:
408
lines = [a + ' ' + l for a, l in
409
vf.annotate(revision)]
410
if snapshots is None:
411
force_snapshot = None
413
force_snapshot = (revision in snapshots)
414
self.add_version(lines, revision, parents, force_snapshot,
421
if not (lines == self.get_line_list([revision])[0]):
422
raise AssertionError()
424
pb.update(gettext('Importing revisions'),
425
(total - len(revisions)) + len(added), total)
426
revisions = [r for r in revisions if r not in added]
430
def select_snapshots(self, vf):
431
"""Determine which versions to add as snapshots"""
435
for version_id in topo_iter(vf):
436
potential_build_ancestors = set(vf.get_parents(version_id))
437
parents = vf.get_parents(version_id)
438
if len(parents) == 0:
439
snapshots.add(version_id)
440
build_ancestors[version_id] = set()
442
for parent in vf.get_parents(version_id):
443
potential_build_ancestors.update(build_ancestors[parent])
444
if len(potential_build_ancestors) > self.snapshot_interval:
445
snapshots.add(version_id)
446
build_ancestors[version_id] = set()
448
build_ancestors[version_id] = potential_build_ancestors
451
def select_by_size(self, num):
452
"""Select snapshots for minimum output size"""
453
num -= len(self._snapshots)
454
new_snapshots = self.get_size_ranking()[-num:]
455
return [v for n, v in new_snapshots]
457
def get_size_ranking(self):
458
"""Get versions ranked by size"""
460
new_snapshots = set()
461
for version_id in self.versions():
462
if version_id in self._snapshots:
464
diff_len = self.get_diff(version_id).patch_len()
465
snapshot_len = MultiParent([NewText(
466
self.cache_version(version_id))]).patch_len()
467
versions.append((snapshot_len - diff_len, version_id))
471
def import_diffs(self, vf):
472
"""Import the diffs from another pseudo-versionedfile"""
473
for version_id in vf.versions():
474
self.add_diff(vf.get_diff(version_id), version_id,
475
vf._parents[version_id])
477
def get_build_ranking(self):
478
"""Return revisions sorted by how much they reduce build complexity"""
481
for version_id in topo_iter(self):
482
could_avoid[version_id] = set()
483
if version_id not in self._snapshots:
484
for parent_id in self._parents[version_id]:
485
could_avoid[version_id].update(could_avoid[parent_id])
486
could_avoid[version_id].update(self._parents)
487
could_avoid[version_id].discard(version_id)
488
for avoid_id in could_avoid[version_id]:
489
referenced_by.setdefault(avoid_id, set()).add(version_id)
490
available_versions = list(self.versions())
492
while len(available_versions) > 0:
493
available_versions.sort(key=lambda x:
494
len(could_avoid[x]) *
495
len(referenced_by.get(x, [])))
496
selected = available_versions.pop()
497
ranking.append(selected)
498
for version_id in referenced_by[selected]:
499
could_avoid[version_id].difference_update(
500
could_avoid[selected])
501
for version_id in could_avoid[selected]:
502
referenced_by[version_id].difference_update(
503
referenced_by[selected]
507
def clear_cache(self):
510
def get_line_list(self, version_ids):
511
return [self.cache_version(v) for v in version_ids]
513
def cache_version(self, version_id):
515
return self._lines[version_id]
518
diff = self.get_diff(version_id)
520
reconstructor = _Reconstructor(self, self._lines, self._parents)
521
reconstructor.reconstruct_version(lines, version_id)
522
self._lines[version_id] = lines
526
class MultiMemoryVersionedFile(BaseVersionedFile):
527
"""Memory-backed pseudo-versionedfile"""
529
def __init__(self, snapshot_interval=25, max_snapshots=None):
530
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
533
def add_diff(self, diff, version_id, parent_ids):
534
self._diffs[version_id] = diff
535
self._parents[version_id] = parent_ids
537
def get_diff(self, version_id):
539
return self._diffs[version_id]
541
raise errors.RevisionNotPresent(version_id, self)
547
class MultiVersionedFile(BaseVersionedFile):
548
"""Disk-backed pseudo-versionedfile"""
550
def __init__(self, filename, snapshot_interval=25, max_snapshots=None):
551
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
552
self._filename = filename
553
self._diff_offset = {}
555
def get_diff(self, version_id):
556
start, count = self._diff_offset[version_id]
557
infile = open(self._filename + '.mpknit', 'rb')
560
sio = StringIO(infile.read(count))
563
zip_file = gzip.GzipFile(None, mode='rb', fileobj=sio)
565
file_version_id = zip_file.readline()
566
content = zip_file.read()
567
return MultiParent.from_patch(content)
571
def add_diff(self, diff, version_id, parent_ids):
572
outfile = open(self._filename + '.mpknit', 'ab')
574
outfile.seek(0, 2) # workaround for windows bug:
575
# .tell() for files opened in 'ab' mode
576
# before any write returns 0
577
start = outfile.tell()
579
zipfile = gzip.GzipFile(None, mode='ab', fileobj=outfile)
580
zipfile.writelines(itertools.chain(
581
['version %s\n' % version_id], diff.to_patch()))
587
self._diff_offset[version_id] = (start, end-start)
588
self._parents[version_id] = parent_ids
592
os.unlink(self._filename + '.mpknit')
594
if e.errno != errno.ENOENT:
597
os.unlink(self._filename + '.mpidx')
599
if e.errno != errno.ENOENT:
603
open(self._filename + '.mpidx', 'wb').write(bencode.bencode(
604
(self._parents, list(self._snapshots), self._diff_offset)))
607
self._parents, snapshots, self._diff_offset = bencode.bdecode(
608
open(self._filename + '.mpidx', 'rb').read())
609
self._snapshots = set(snapshots)
612
class _Reconstructor(object):
613
"""Build a text from the diffs, ancestry graph and cached lines"""
615
def __init__(self, diffs, lines, parents):
618
self.parents = parents
621
def reconstruct(self, lines, parent_text, version_id):
622
"""Append the lines referred to by a ParentText to lines"""
623
parent_id = self.parents[version_id][parent_text.parent]
624
end = parent_text.parent_pos + parent_text.num_lines
625
return self._reconstruct(lines, parent_id, parent_text.parent_pos,
628
def _reconstruct(self, lines, req_version_id, req_start, req_end):
629
"""Append lines for the requested version_id range"""
630
# stack of pending range requests
631
if req_start == req_end:
633
pending_reqs = [(req_version_id, req_start, req_end)]
634
while len(pending_reqs) > 0:
635
req_version_id, req_start, req_end = pending_reqs.pop()
636
# lazily allocate cursors for versions
637
if req_version_id in self.lines:
638
lines.extend(self.lines[req_version_id][req_start:req_end])
641
start, end, kind, data, iterator = self.cursor[req_version_id]
643
iterator = self.diffs.get_diff(req_version_id).range_iterator()
644
start, end, kind, data = iterator.next()
645
if start > req_start:
646
iterator = self.diffs.get_diff(req_version_id).range_iterator()
647
start, end, kind, data = iterator.next()
649
# find the first hunk relevant to the request
650
while end <= req_start:
651
start, end, kind, data = iterator.next()
652
self.cursor[req_version_id] = start, end, kind, data, iterator
653
# if the hunk can't satisfy the whole request, split it in two,
654
# and leave the second half for later.
656
pending_reqs.append((req_version_id, end, req_end))
659
lines.extend(data[req_start - start: (req_end - start)])
661
# If the hunk is a ParentText, rewrite it as a range request
662
# for the parent, and make it the next pending request.
663
parent, parent_start, parent_end = data
664
new_version_id = self.parents[req_version_id][parent]
665
new_start = parent_start + req_start - start
666
new_end = parent_end + req_end - end
667
pending_reqs.append((new_version_id, new_start, new_end))
669
def reconstruct_version(self, lines, version_id):
670
length = self.diffs.get_diff(version_id).num_lines()
671
return self._reconstruct(lines, version_id, 0, length)
674
def gzip_string(lines):
676
data_file = gzip.GzipFile(None, mode='wb', fileobj=sio)
677
data_file.writelines(lines)
679
return sio.getvalue()