1
# Copyright (C) 2007 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
from bzrlib.lazy_import import lazy_import
19
lazy_import(globals(), """
23
from StringIO import StringIO
31
from bzrlib.util import bencode
33
from bzrlib.tuned_gzip import GzipFile
36
def topo_iter(vf, versions=None):
40
versions = vf.versions()
41
parents = vf.get_parent_map(versions)
42
def pending_parents(version):
43
return [v for v in parents[version] if v in versions and
45
for version_id in versions:
46
for parent_id in parents[version_id]:
47
descendants.setdefault(parent_id, []).append(version_id)
48
cur = [v for v in versions if len(pending_parents(v)) == 0]
51
for version_id in cur:
52
if version_id in seen:
54
if len(pending_parents(version_id)) != 0:
56
next.extend(descendants.get(version_id, []))
62
class MultiParent(object):
63
"""A multi-parent diff"""
65
def __init__(self, hunks=None):
72
return "MultiParent(%r)" % self.hunks
74
def __eq__(self, other):
75
if self.__class__ is not other.__class__:
77
return (self.hunks == other.hunks)
80
def from_lines(text, parents=(), left_blocks=None):
81
"""Produce a MultiParent from a list of lines and parents"""
83
matcher = patiencediff.PatienceSequenceMatcher(None, parent,
85
return matcher.get_matching_blocks()
87
if left_blocks is None:
88
left_blocks = compare(parents[0])
89
parent_comparisons = [left_blocks] + [compare(p) for p in
92
parent_comparisons = []
94
new_text = NewText([])
96
block_iter = [iter(i) for i in parent_comparisons]
97
diff = MultiParent([])
100
return block_iter[p].next()
101
except StopIteration:
103
cur_block = [next_block(p) for p, i in enumerate(block_iter)]
104
while cur_line < len(text):
106
for p, block in enumerate(cur_block):
110
while j + n <= cur_line:
111
block = cur_block[p] = next_block(p)
119
offset = cur_line - j
125
if best_match is None or n > best_match.num_lines:
126
best_match = ParentText(p, i, j, n)
127
if best_match is None:
128
new_text.lines.append(text[cur_line])
131
if len(new_text.lines) > 0:
132
diff.hunks.append(new_text)
133
new_text = NewText([])
134
diff.hunks.append(best_match)
135
cur_line += best_match.num_lines
136
if len(new_text.lines) > 0:
137
diff.hunks.append(new_text)
140
def get_matching_blocks(self, parent, parent_len):
141
for hunk in self.hunks:
142
if not isinstance(hunk, ParentText) or hunk.parent != parent:
144
yield (hunk.parent_pos, hunk.child_pos, hunk.num_lines)
145
yield parent_len, self.num_lines(), 0
147
def to_lines(self, parents=()):
148
"""Contruct a fulltext from this diff and its parents"""
149
mpvf = MultiMemoryVersionedFile()
150
for num, parent in enumerate(parents):
151
mpvf.add_version(StringIO(parent).readlines(), num, [])
152
mpvf.add_diff(self, 'a', range(len(parents)))
153
return mpvf.get_line_list(['a'])[0]
156
def from_texts(cls, text, parents=()):
157
"""Produce a MultiParent from a text and list of parent text"""
158
return cls.from_lines(StringIO(text).readlines(),
159
[StringIO(p).readlines() for p in parents])
162
"""Yield text lines for a patch"""
163
for hunk in self.hunks:
164
for line in hunk.to_patch():
168
return len(''.join(self.to_patch()))
170
def zipped_patch_len(self):
171
return len(gzip_string(self.to_patch()))
174
def from_patch(cls, text):
175
"""Create a MultiParent from its string form"""
176
return cls._from_patch(StringIO(text))
179
def _from_patch(lines):
180
"""This is private because it is essential to split lines on \n only"""
181
line_iter = iter(lines)
186
cur_line = line_iter.next()
187
except StopIteration:
189
if cur_line[0] == 'i':
190
num_lines = int(cur_line.split(' ')[1])
191
hunk_lines = [line_iter.next() for x in xrange(num_lines)]
192
hunk_lines[-1] = hunk_lines[-1][:-1]
193
hunks.append(NewText(hunk_lines))
194
elif cur_line[0] == '\n':
195
hunks[-1].lines[-1] += '\n'
197
if not (cur_line[0] == 'c'):
198
raise AssertionError(cur_line[0])
199
parent, parent_pos, child_pos, num_lines =\
200
[int(v) for v in cur_line.split(' ')[1:]]
201
hunks.append(ParentText(parent, parent_pos, child_pos,
203
return MultiParent(hunks)
205
def range_iterator(self):
206
"""Iterate through the hunks, with range indicated
208
kind is "new" or "parent".
209
for "new", data is a list of lines.
210
for "parent", data is (parent, parent_start, parent_end)
211
:return: a generator of (start, end, kind, data)
214
for hunk in self.hunks:
215
if isinstance(hunk, NewText):
217
end = start + len(hunk.lines)
221
start = hunk.child_pos
222
end = start + hunk.num_lines
223
data = (hunk.parent, hunk.parent_pos, hunk.parent_pos +
225
yield start, end, kind, data
229
"""The number of lines in the output text"""
231
for hunk in reversed(self.hunks):
232
if isinstance(hunk, ParentText):
233
return hunk.child_pos + hunk.num_lines + extra_n
234
extra_n += len(hunk.lines)
237
def is_snapshot(self):
238
"""Return true of this hunk is effectively a fulltext"""
239
if len(self.hunks) != 1:
241
return (isinstance(self.hunks[0], NewText))
244
class NewText(object):
245
"""The contents of text that is introduced by this text"""
247
def __init__(self, lines):
250
def __eq__(self, other):
251
if self.__class__ is not other.__class__:
253
return (other.lines == self.lines)
256
return 'NewText(%r)' % self.lines
259
yield 'i %d\n' % len(self.lines)
260
for line in self.lines:
265
class ParentText(object):
266
"""A reference to text present in a parent text"""
268
def __init__(self, parent, parent_pos, child_pos, num_lines):
270
self.parent_pos = parent_pos
271
self.child_pos = child_pos
272
self.num_lines = num_lines
275
return 'ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'\
276
' %(num_lines)r)' % self.__dict__
278
def __eq__(self, other):
279
if self.__class__ != other.__class__:
281
return (self.__dict__ == other.__dict__)
284
yield 'c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'\
288
class BaseVersionedFile(object):
289
"""Pseudo-VersionedFile skeleton for MultiParent"""
291
def __init__(self, snapshot_interval=25, max_snapshots=None):
294
self._snapshots = set()
295
self.snapshot_interval = snapshot_interval
296
self.max_snapshots = max_snapshots
299
return iter(self._parents)
301
def has_version(self, version):
302
return version in self._parents
304
def do_snapshot(self, version_id, parent_ids):
305
"""Determine whether to perform a a snapshot for this version"""
306
if self.snapshot_interval is None:
308
if self.max_snapshots is not None and\
309
len(self._snapshots) == self.max_snapshots:
311
if len(parent_ids) == 0:
313
for ignored in xrange(self.snapshot_interval):
314
if len(parent_ids) == 0:
316
version_ids = parent_ids
318
for version_id in version_ids:
319
if version_id not in self._snapshots:
320
parent_ids.extend(self._parents[version_id])
324
def add_version(self, lines, version_id, parent_ids,
325
force_snapshot=None, single_parent=False):
326
"""Add a version to the versionedfile
328
:param lines: The list of lines to add. Must be split on '\n'.
329
:param version_id: The version_id of the version to add
330
:param force_snapshot: If true, force this version to be added as a
331
snapshot version. If false, force this version to be added as a
332
diff. If none, determine this automatically.
333
:param single_parent: If true, use a single parent, rather than
336
if force_snapshot is None:
337
do_snapshot = self.do_snapshot(version_id, parent_ids)
339
do_snapshot = force_snapshot
341
self._snapshots.add(version_id)
342
diff = MultiParent([NewText(lines)])
345
parent_lines = self.get_line_list(parent_ids[:1])
347
parent_lines = self.get_line_list(parent_ids)
348
diff = MultiParent.from_lines(lines, parent_lines)
349
if diff.is_snapshot():
350
self._snapshots.add(version_id)
351
self.add_diff(diff, version_id, parent_ids)
352
self._lines[version_id] = lines
354
def get_parents(self, version_id):
355
return self._parents[version_id]
357
def make_snapshot(self, version_id):
358
snapdiff = MultiParent([NewText(self.cache_version(version_id))])
359
self.add_diff(snapdiff, version_id, self._parents[version_id])
360
self._snapshots.add(version_id)
362
def import_versionedfile(self, vf, snapshots, no_cache=True,
363
single_parent=False, verify=False):
364
"""Import all revisions of a versionedfile
366
:param vf: The versionedfile to import
367
:param snapshots: If provided, the revisions to make snapshots of.
368
Otherwise, this will be auto-determined
369
:param no_cache: If true, clear the cache after every add.
370
:param single_parent: If true, omit all but one parent text, (but
371
retain parent metadata).
373
if not (no_cache or not verify):
375
revisions = set(vf.versions())
376
total = len(revisions)
377
pb = ui.ui_factory.nested_progress_bar()
379
while len(revisions) > 0:
381
for revision in revisions:
382
parents = vf.get_parents(revision)
383
if [p for p in parents if p not in self._parents] != []:
385
lines = [a + ' ' + l for a, l in
386
vf.annotate(revision)]
387
if snapshots is None:
388
force_snapshot = None
390
force_snapshot = (revision in snapshots)
391
self.add_version(lines, revision, parents, force_snapshot,
398
if not (lines == self.get_line_list([revision])[0]):
399
raise AssertionError()
401
pb.update('Importing revisions',
402
(total - len(revisions)) + len(added), total)
403
revisions = [r for r in revisions if r not in added]
407
def select_snapshots(self, vf):
408
"""Determine which versions to add as snapshots"""
412
for version_id in topo_iter(vf):
413
potential_build_ancestors = set(vf.get_parents(version_id))
414
parents = vf.get_parents(version_id)
415
if len(parents) == 0:
416
snapshots.add(version_id)
417
build_ancestors[version_id] = set()
419
for parent in vf.get_parents(version_id):
420
potential_build_ancestors.update(build_ancestors[parent])
421
if len(potential_build_ancestors) > self.snapshot_interval:
422
snapshots.add(version_id)
423
build_ancestors[version_id] = set()
425
build_ancestors[version_id] = potential_build_ancestors
428
def select_by_size(self, num):
429
"""Select snapshots for minimum output size"""
430
num -= len(self._snapshots)
431
new_snapshots = self.get_size_ranking()[-num:]
432
return [v for n, v in new_snapshots]
434
def get_size_ranking(self):
435
"""Get versions ranked by size"""
437
new_snapshots = set()
438
for version_id in self.versions():
439
if version_id in self._snapshots:
441
diff_len = self.get_diff(version_id).patch_len()
442
snapshot_len = MultiParent([NewText(
443
self.cache_version(version_id))]).patch_len()
444
versions.append((snapshot_len - diff_len, version_id))
448
def import_diffs(self, vf):
449
"""Import the diffs from another pseudo-versionedfile"""
450
for version_id in vf.versions():
451
self.add_diff(vf.get_diff(version_id), version_id,
452
vf._parents[version_id])
454
def get_build_ranking(self):
455
"""Return revisions sorted by how much they reduce build complexity"""
458
for version_id in topo_iter(self):
459
could_avoid[version_id] = set()
460
if version_id not in self._snapshots:
461
for parent_id in self._parents[version_id]:
462
could_avoid[version_id].update(could_avoid[parent_id])
463
could_avoid[version_id].update(self._parents)
464
could_avoid[version_id].discard(version_id)
465
for avoid_id in could_avoid[version_id]:
466
referenced_by.setdefault(avoid_id, set()).add(version_id)
467
available_versions = list(self.versions())
469
while len(available_versions) > 0:
470
available_versions.sort(key=lambda x:
471
len(could_avoid[x]) *
472
len(referenced_by.get(x, [])))
473
selected = available_versions.pop()
474
ranking.append(selected)
475
for version_id in referenced_by[selected]:
476
could_avoid[version_id].difference_update(
477
could_avoid[selected])
478
for version_id in could_avoid[selected]:
479
referenced_by[version_id].difference_update(
480
referenced_by[selected]
484
def clear_cache(self):
487
def get_line_list(self, version_ids):
488
return [self.cache_version(v) for v in version_ids]
490
def cache_version(self, version_id):
492
return self._lines[version_id]
495
diff = self.get_diff(version_id)
497
reconstructor = _Reconstructor(self, self._lines, self._parents)
498
reconstructor.reconstruct_version(lines, version_id)
499
self._lines[version_id] = lines
503
class MultiMemoryVersionedFile(BaseVersionedFile):
504
"""Memory-backed pseudo-versionedfile"""
506
def __init__(self, snapshot_interval=25, max_snapshots=None):
507
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
510
def add_diff(self, diff, version_id, parent_ids):
511
self._diffs[version_id] = diff
512
self._parents[version_id] = parent_ids
514
def get_diff(self, version_id):
516
return self._diffs[version_id]
518
raise errors.RevisionNotPresent(version_id, self)
524
class MultiVersionedFile(BaseVersionedFile):
525
"""Disk-backed pseudo-versionedfile"""
527
def __init__(self, filename, snapshot_interval=25, max_snapshots=None):
528
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
529
self._filename = filename
530
self._diff_offset = {}
532
def get_diff(self, version_id):
533
start, count = self._diff_offset[version_id]
534
infile = open(self._filename + '.mpknit', 'rb')
537
sio = StringIO(infile.read(count))
540
zip_file = GzipFile(None, mode='rb', fileobj=sio)
542
file_version_id = zip_file.readline()
543
return MultiParent.from_patch(zip_file.read())
547
def add_diff(self, diff, version_id, parent_ids):
548
outfile = open(self._filename + '.mpknit', 'ab')
550
outfile.seek(0, 2) # workaround for windows bug:
551
# .tell() for files opened in 'ab' mode
552
# before any write returns 0
553
start = outfile.tell()
555
zipfile = GzipFile(None, mode='ab', fileobj=outfile)
556
zipfile.writelines(itertools.chain(
557
['version %s\n' % version_id], diff.to_patch()))
563
self._diff_offset[version_id] = (start, end-start)
564
self._parents[version_id] = parent_ids
568
os.unlink(self._filename + '.mpknit')
570
if e.errno != errno.ENOENT:
573
os.unlink(self._filename + '.mpidx')
575
if e.errno != errno.ENOENT:
579
open(self._filename + '.mpidx', 'wb').write(bencode.bencode(
580
(self._parents, list(self._snapshots), self._diff_offset)))
583
self._parents, snapshots, self._diff_offset = bencode.bdecode(
584
open(self._filename + '.mpidx', 'rb').read())
585
self._snapshots = set(snapshots)
588
class _Reconstructor(object):
589
"""Build a text from the diffs, ancestry graph and cached lines"""
591
def __init__(self, diffs, lines, parents):
594
self.parents = parents
597
def reconstruct(self, lines, parent_text, version_id):
598
"""Append the lines referred to by a ParentText to lines"""
599
parent_id = self.parents[version_id][parent_text.parent]
600
end = parent_text.parent_pos + parent_text.num_lines
601
return self._reconstruct(lines, parent_id, parent_text.parent_pos,
604
def _reconstruct(self, lines, req_version_id, req_start, req_end):
605
"""Append lines for the requested version_id range"""
606
# stack of pending range requests
607
if req_start == req_end:
609
pending_reqs = [(req_version_id, req_start, req_end)]
610
while len(pending_reqs) > 0:
611
req_version_id, req_start, req_end = pending_reqs.pop()
612
# lazily allocate cursors for versions
613
if req_version_id in self.lines:
614
lines.extend(self.lines[req_version_id][req_start:req_end])
617
start, end, kind, data, iterator = self.cursor[req_version_id]
619
iterator = self.diffs.get_diff(req_version_id).range_iterator()
620
start, end, kind, data = iterator.next()
621
if start > req_start:
622
iterator = self.diffs.get_diff(req_version_id).range_iterator()
623
start, end, kind, data = iterator.next()
625
# find the first hunk relevant to the request
626
while end <= req_start:
627
start, end, kind, data = iterator.next()
628
self.cursor[req_version_id] = start, end, kind, data, iterator
629
# if the hunk can't satisfy the whole request, split it in two,
630
# and leave the second half for later.
632
pending_reqs.append((req_version_id, end, req_end))
635
lines.extend(data[req_start - start: (req_end - start)])
637
# If the hunk is a ParentText, rewrite it as a range request
638
# for the parent, and make it the next pending request.
639
parent, parent_start, parent_end = data
640
new_version_id = self.parents[req_version_id][parent]
641
new_start = parent_start + req_start - start
642
new_end = parent_end + req_end - end
643
pending_reqs.append((new_version_id, new_start, new_end))
645
def reconstruct_version(self, lines, version_id):
646
length = self.diffs.get_diff(version_id).num_lines()
647
return self._reconstruct(lines, version_id, 0, length)
650
def gzip_string(lines):
652
data_file = GzipFile(None, mode='wb', fileobj=sio)
653
data_file.writelines(lines)
655
return sio.getvalue()