1
# Copyright (C) 2007-2010 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(), """
23
from StringIO import StringIO
31
from bzrlib import bencode
33
from bzrlib.tuned_gzip import GzipFile
36
def topo_iter_keys(vf, keys=None):
39
parents = vf.get_parent_map(keys)
40
return _topo_iter(parents, keys)
42
def topo_iter(vf, versions=None):
44
versions = vf.versions()
45
parents = vf.get_parent_map(versions)
46
return _topo_iter(parents, versions)
48
def _topo_iter(parents, versions):
51
def pending_parents(version):
52
if parents[version] is None:
54
return [v for v in parents[version] if v in versions and
56
for version_id in versions:
57
if parents[version_id] is None:
60
for parent_id in parents[version_id]:
61
descendants.setdefault(parent_id, []).append(version_id)
62
cur = [v for v in versions if len(pending_parents(v)) == 0]
65
for version_id in cur:
66
if version_id in seen:
68
if len(pending_parents(version_id)) != 0:
70
next.extend(descendants.get(version_id, []))
76
class MultiParent(object):
77
"""A multi-parent diff"""
81
def __init__(self, hunks=None):
88
return "MultiParent(%r)" % self.hunks
90
def __eq__(self, other):
91
if self.__class__ is not other.__class__:
93
return (self.hunks == other.hunks)
96
def from_lines(text, parents=(), left_blocks=None):
97
"""Produce a MultiParent from a list of lines and parents"""
99
matcher = patiencediff.PatienceSequenceMatcher(None, parent,
101
return matcher.get_matching_blocks()
103
if left_blocks is None:
104
left_blocks = compare(parents[0])
105
parent_comparisons = [left_blocks] + [compare(p) for p in
108
parent_comparisons = []
110
new_text = NewText([])
112
block_iter = [iter(i) for i in parent_comparisons]
113
diff = MultiParent([])
116
return block_iter[p].next()
117
except StopIteration:
119
cur_block = [next_block(p) for p, i in enumerate(block_iter)]
120
while cur_line < len(text):
122
for p, block in enumerate(cur_block):
126
while j + n <= cur_line:
127
block = cur_block[p] = next_block(p)
135
offset = cur_line - j
141
if best_match is None or n > best_match.num_lines:
142
best_match = ParentText(p, i, j, n)
143
if best_match is None:
144
new_text.lines.append(text[cur_line])
147
if len(new_text.lines) > 0:
148
diff.hunks.append(new_text)
149
new_text = NewText([])
150
diff.hunks.append(best_match)
151
cur_line += best_match.num_lines
152
if len(new_text.lines) > 0:
153
diff.hunks.append(new_text)
156
def get_matching_blocks(self, parent, parent_len):
157
for hunk in self.hunks:
158
if not isinstance(hunk, ParentText) or hunk.parent != parent:
160
yield (hunk.parent_pos, hunk.child_pos, hunk.num_lines)
161
yield parent_len, self.num_lines(), 0
163
def to_lines(self, parents=()):
164
"""Contruct a fulltext from this diff and its parents"""
165
mpvf = MultiMemoryVersionedFile()
166
for num, parent in enumerate(parents):
167
mpvf.add_version(StringIO(parent).readlines(), num, [])
168
mpvf.add_diff(self, 'a', range(len(parents)))
169
return mpvf.get_line_list(['a'])[0]
172
def from_texts(cls, text, parents=()):
173
"""Produce a MultiParent from a text and list of parent text"""
174
return cls.from_lines(StringIO(text).readlines(),
175
[StringIO(p).readlines() for p in parents])
178
"""Yield text lines for a patch"""
179
for hunk in self.hunks:
180
for line in hunk.to_patch():
184
return len(''.join(self.to_patch()))
186
def zipped_patch_len(self):
187
return len(gzip_string(self.to_patch()))
190
def from_patch(cls, text):
191
"""Create a MultiParent from its string form"""
192
return cls._from_patch(StringIO(text))
195
def _from_patch(lines):
196
"""This is private because it is essential to split lines on \n only"""
197
line_iter = iter(lines)
202
cur_line = line_iter.next()
203
except StopIteration:
205
if cur_line[0] == 'i':
206
num_lines = int(cur_line.split(' ')[1])
207
hunk_lines = [line_iter.next() for x in xrange(num_lines)]
208
hunk_lines[-1] = hunk_lines[-1][:-1]
209
hunks.append(NewText(hunk_lines))
210
elif cur_line[0] == '\n':
211
hunks[-1].lines[-1] += '\n'
213
if not (cur_line[0] == 'c'):
214
raise AssertionError(cur_line[0])
215
parent, parent_pos, child_pos, num_lines =\
216
[int(v) for v in cur_line.split(' ')[1:]]
217
hunks.append(ParentText(parent, parent_pos, child_pos,
219
return MultiParent(hunks)
221
def range_iterator(self):
222
"""Iterate through the hunks, with range indicated
224
kind is "new" or "parent".
225
for "new", data is a list of lines.
226
for "parent", data is (parent, parent_start, parent_end)
227
:return: a generator of (start, end, kind, data)
230
for hunk in self.hunks:
231
if isinstance(hunk, NewText):
233
end = start + len(hunk.lines)
237
start = hunk.child_pos
238
end = start + hunk.num_lines
239
data = (hunk.parent, hunk.parent_pos, hunk.parent_pos +
241
yield start, end, kind, data
245
"""The number of lines in the output text"""
247
for hunk in reversed(self.hunks):
248
if isinstance(hunk, ParentText):
249
return hunk.child_pos + hunk.num_lines + extra_n
250
extra_n += len(hunk.lines)
253
def is_snapshot(self):
254
"""Return true of this hunk is effectively a fulltext"""
255
if len(self.hunks) != 1:
257
return (isinstance(self.hunks[0], NewText))
260
class NewText(object):
261
"""The contents of text that is introduced by this text"""
263
__slots__ = ['lines']
265
def __init__(self, lines):
268
def __eq__(self, other):
269
if self.__class__ is not other.__class__:
271
return (other.lines == self.lines)
274
return 'NewText(%r)' % self.lines
277
yield 'i %d\n' % len(self.lines)
278
for line in self.lines:
283
class ParentText(object):
284
"""A reference to text present in a parent text"""
286
__slots__ = ['parent', 'parent_pos', 'child_pos', 'num_lines']
288
def __init__(self, parent, parent_pos, child_pos, num_lines):
290
self.parent_pos = parent_pos
291
self.child_pos = child_pos
292
self.num_lines = num_lines
295
return dict(parent=self.parent, parent_pos=self.parent_pos,
296
child_pos=self.child_pos, num_lines=self.num_lines)
299
return ('ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'
300
' %(num_lines)r)' % self._as_dict())
302
def __eq__(self, other):
303
if self.__class__ is not other.__class__:
305
return self._as_dict() == other._as_dict()
308
yield ('c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'
312
class BaseVersionedFile(object):
313
"""Pseudo-VersionedFile skeleton for MultiParent"""
315
def __init__(self, snapshot_interval=25, max_snapshots=None):
318
self._snapshots = set()
319
self.snapshot_interval = snapshot_interval
320
self.max_snapshots = max_snapshots
323
return iter(self._parents)
325
def has_version(self, version):
326
return version in self._parents
328
def do_snapshot(self, version_id, parent_ids):
329
"""Determine whether to perform a snapshot for this version"""
330
if self.snapshot_interval is None:
332
if self.max_snapshots is not None and\
333
len(self._snapshots) == self.max_snapshots:
335
if len(parent_ids) == 0:
337
for ignored in xrange(self.snapshot_interval):
338
if len(parent_ids) == 0:
340
version_ids = parent_ids
342
for version_id in version_ids:
343
if version_id not in self._snapshots:
344
parent_ids.extend(self._parents[version_id])
348
def add_version(self, lines, version_id, parent_ids,
349
force_snapshot=None, single_parent=False):
350
"""Add a version to the versionedfile
352
:param lines: The list of lines to add. Must be split on '\n'.
353
:param version_id: The version_id of the version to add
354
:param force_snapshot: If true, force this version to be added as a
355
snapshot version. If false, force this version to be added as a
356
diff. If none, determine this automatically.
357
:param single_parent: If true, use a single parent, rather than
360
if force_snapshot is None:
361
do_snapshot = self.do_snapshot(version_id, parent_ids)
363
do_snapshot = force_snapshot
365
self._snapshots.add(version_id)
366
diff = MultiParent([NewText(lines)])
369
parent_lines = self.get_line_list(parent_ids[:1])
371
parent_lines = self.get_line_list(parent_ids)
372
diff = MultiParent.from_lines(lines, parent_lines)
373
if diff.is_snapshot():
374
self._snapshots.add(version_id)
375
self.add_diff(diff, version_id, parent_ids)
376
self._lines[version_id] = lines
378
def get_parents(self, version_id):
379
return self._parents[version_id]
381
def make_snapshot(self, version_id):
382
snapdiff = MultiParent([NewText(self.cache_version(version_id))])
383
self.add_diff(snapdiff, version_id, self._parents[version_id])
384
self._snapshots.add(version_id)
386
def import_versionedfile(self, vf, snapshots, no_cache=True,
387
single_parent=False, verify=False):
388
"""Import all revisions of a versionedfile
390
:param vf: The versionedfile to import
391
:param snapshots: If provided, the revisions to make snapshots of.
392
Otherwise, this will be auto-determined
393
:param no_cache: If true, clear the cache after every add.
394
:param single_parent: If true, omit all but one parent text, (but
395
retain parent metadata).
397
if not (no_cache or not verify):
399
revisions = set(vf.versions())
400
total = len(revisions)
401
pb = ui.ui_factory.nested_progress_bar()
403
while len(revisions) > 0:
405
for revision in revisions:
406
parents = vf.get_parents(revision)
407
if [p for p in parents if p not in self._parents] != []:
409
lines = [a + ' ' + l for a, l in
410
vf.annotate(revision)]
411
if snapshots is None:
412
force_snapshot = None
414
force_snapshot = (revision in snapshots)
415
self.add_version(lines, revision, parents, force_snapshot,
422
if not (lines == self.get_line_list([revision])[0]):
423
raise AssertionError()
425
pb.update('Importing revisions',
426
(total - len(revisions)) + len(added), total)
427
revisions = [r for r in revisions if r not in added]
431
def select_snapshots(self, vf):
432
"""Determine which versions to add as snapshots"""
436
for version_id in topo_iter(vf):
437
potential_build_ancestors = set(vf.get_parents(version_id))
438
parents = vf.get_parents(version_id)
439
if len(parents) == 0:
440
snapshots.add(version_id)
441
build_ancestors[version_id] = set()
443
for parent in vf.get_parents(version_id):
444
potential_build_ancestors.update(build_ancestors[parent])
445
if len(potential_build_ancestors) > self.snapshot_interval:
446
snapshots.add(version_id)
447
build_ancestors[version_id] = set()
449
build_ancestors[version_id] = potential_build_ancestors
452
def select_by_size(self, num):
453
"""Select snapshots for minimum output size"""
454
num -= len(self._snapshots)
455
new_snapshots = self.get_size_ranking()[-num:]
456
return [v for n, v in new_snapshots]
458
def get_size_ranking(self):
459
"""Get versions ranked by size"""
461
new_snapshots = set()
462
for version_id in self.versions():
463
if version_id in self._snapshots:
465
diff_len = self.get_diff(version_id).patch_len()
466
snapshot_len = MultiParent([NewText(
467
self.cache_version(version_id))]).patch_len()
468
versions.append((snapshot_len - diff_len, version_id))
472
def import_diffs(self, vf):
473
"""Import the diffs from another pseudo-versionedfile"""
474
for version_id in vf.versions():
475
self.add_diff(vf.get_diff(version_id), version_id,
476
vf._parents[version_id])
478
def get_build_ranking(self):
479
"""Return revisions sorted by how much they reduce build complexity"""
482
for version_id in topo_iter(self):
483
could_avoid[version_id] = set()
484
if version_id not in self._snapshots:
485
for parent_id in self._parents[version_id]:
486
could_avoid[version_id].update(could_avoid[parent_id])
487
could_avoid[version_id].update(self._parents)
488
could_avoid[version_id].discard(version_id)
489
for avoid_id in could_avoid[version_id]:
490
referenced_by.setdefault(avoid_id, set()).add(version_id)
491
available_versions = list(self.versions())
493
while len(available_versions) > 0:
494
available_versions.sort(key=lambda x:
495
len(could_avoid[x]) *
496
len(referenced_by.get(x, [])))
497
selected = available_versions.pop()
498
ranking.append(selected)
499
for version_id in referenced_by[selected]:
500
could_avoid[version_id].difference_update(
501
could_avoid[selected])
502
for version_id in could_avoid[selected]:
503
referenced_by[version_id].difference_update(
504
referenced_by[selected]
508
def clear_cache(self):
511
def get_line_list(self, version_ids):
512
return [self.cache_version(v) for v in version_ids]
514
def cache_version(self, version_id):
516
return self._lines[version_id]
519
diff = self.get_diff(version_id)
521
reconstructor = _Reconstructor(self, self._lines, self._parents)
522
reconstructor.reconstruct_version(lines, version_id)
523
self._lines[version_id] = lines
527
class MultiMemoryVersionedFile(BaseVersionedFile):
528
"""Memory-backed pseudo-versionedfile"""
530
def __init__(self, snapshot_interval=25, max_snapshots=None):
531
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
534
def add_diff(self, diff, version_id, parent_ids):
535
self._diffs[version_id] = diff
536
self._parents[version_id] = parent_ids
538
def get_diff(self, version_id):
540
return self._diffs[version_id]
542
raise errors.RevisionNotPresent(version_id, self)
548
class MultiVersionedFile(BaseVersionedFile):
549
"""Disk-backed pseudo-versionedfile"""
551
def __init__(self, filename, snapshot_interval=25, max_snapshots=None):
552
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
553
self._filename = filename
554
self._diff_offset = {}
556
def get_diff(self, version_id):
557
start, count = self._diff_offset[version_id]
558
infile = open(self._filename + '.mpknit', 'rb')
561
sio = StringIO(infile.read(count))
564
zip_file = GzipFile(None, mode='rb', fileobj=sio)
566
file_version_id = zip_file.readline()
567
return MultiParent.from_patch(zip_file.read())
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 = 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 = GzipFile(None, mode='wb', fileobj=sio)
677
data_file.writelines(lines)
679
return sio.getvalue()