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
30
from bzrlib.util import bencode
32
from bzrlib.tuned_gzip import GzipFile
35
def topo_iter(vf, versions=None):
39
versions = vf.versions()
40
def pending_parents(version):
41
return [v for v in vf.get_parents(version) if v in versions and
43
for version_id in versions:
44
for parent_id in vf.get_parents(version_id):
45
descendants.setdefault(parent_id, []).append(version_id)
46
cur = [v for v in versions if len(pending_parents(v)) == 0]
49
for version_id in cur:
50
if version_id in seen:
52
if len(pending_parents(version_id)) != 0:
54
next.extend(descendants.get(version_id, []))
58
assert len(seen) == len(versions)
61
class MultiParent(object):
62
"""A multi-parent diff"""
64
def __init__(self, hunks=None):
71
return "MultiParent(%r)" % self.hunks
73
def __eq__(self, other):
74
if self.__class__ is not other.__class__:
76
return (self.hunks == other.hunks)
79
def from_lines(text, parents=(), left_blocks=None):
80
"""Produce a MultiParent from a list of lines and parents"""
82
matcher = patiencediff.PatienceSequenceMatcher(None, parent,
84
return matcher.get_matching_blocks()
86
if left_blocks is None:
87
left_blocks = compare(parents[0])
88
parent_comparisons = [left_blocks] + [compare(p) for p in
91
parent_comparisons = []
93
new_text = NewText([])
95
block_iter = [iter(i) for i in parent_comparisons]
96
diff = MultiParent([])
99
return block_iter[p].next()
100
except StopIteration:
102
cur_block = [next_block(p) for p, i in enumerate(block_iter)]
103
while cur_line < len(text):
105
for p, block in enumerate(cur_block):
109
while j + n <= cur_line:
110
block = cur_block[p] = next_block(p)
118
offset = cur_line - j
124
if best_match is None or n > best_match.num_lines:
125
best_match = ParentText(p, i, j, n)
126
if best_match is None:
127
new_text.lines.append(text[cur_line])
130
if len(new_text.lines) > 0:
131
diff.hunks.append(new_text)
132
new_text = NewText([])
133
diff.hunks.append(best_match)
134
cur_line += best_match.num_lines
135
if len(new_text.lines) > 0:
136
diff.hunks.append(new_text)
139
def get_matching_blocks(self, parent, parent_len):
140
for hunk in self.hunks:
141
if not isinstance(hunk, ParentText) or hunk.parent != parent:
143
yield (hunk.parent_pos, hunk.child_pos, hunk.num_lines)
144
yield parent_len, self.num_lines(), 0
146
def to_lines(self, parents=()):
147
"""Contruct a fulltext from this diff and its parents"""
148
mpvf = MultiMemoryVersionedFile()
149
for num, parent in enumerate(parents):
150
mpvf.add_version(StringIO(parent).readlines(), num, [])
151
mpvf.add_diff(self, 'a', range(len(parents)))
152
return mpvf.get_line_list(['a'])[0]
155
def from_texts(cls, text, parents=()):
156
"""Produce a MultiParent from a text and list of parent text"""
157
return cls.from_lines(StringIO(text).readlines(),
158
[StringIO(p).readlines() for p in parents])
161
"""Yield text lines for a patch"""
162
for hunk in self.hunks:
163
for line in hunk.to_patch():
167
return len(''.join(self.to_patch()))
169
def zipped_patch_len(self):
170
return len(gzip_string(self.to_patch()))
173
def from_patch(cls, text):
174
"""Create a MultiParent from its string form"""
175
return cls._from_patch(StringIO(text))
178
def _from_patch(lines):
179
"""This is private because it is essential to split lines on \n only"""
180
line_iter = iter(lines)
185
cur_line = line_iter.next()
186
except StopIteration:
188
if cur_line[0] == 'i':
189
num_lines = int(cur_line.split(' ')[1])
190
hunk_lines = [line_iter.next() for x in xrange(num_lines)]
191
hunk_lines[-1] = hunk_lines[-1][:-1]
192
hunks.append(NewText(hunk_lines))
193
elif cur_line[0] == '\n':
194
hunks[-1].lines[-1] += '\n'
196
assert cur_line[0] == 'c', cur_line[0]
197
parent, parent_pos, child_pos, num_lines =\
198
[int(v) for v in cur_line.split(' ')[1:]]
199
hunks.append(ParentText(parent, parent_pos, child_pos,
201
return MultiParent(hunks)
203
def range_iterator(self):
204
"""Iterate through the hunks, with range indicated
206
kind is "new" or "parent".
207
for "new", data is a list of lines.
208
for "parent", data is (parent, parent_start, parent_end)
209
:return: a generator of (start, end, kind, data)
212
for hunk in self.hunks:
213
if isinstance(hunk, NewText):
215
end = start + len(hunk.lines)
219
start = hunk.child_pos
220
end = start + hunk.num_lines
221
data = (hunk.parent, hunk.parent_pos, hunk.parent_pos +
223
yield start, end, kind, data
227
"""The number of lines in the output text"""
229
for hunk in reversed(self.hunks):
230
if isinstance(hunk, ParentText):
231
return hunk.child_pos + hunk.num_lines + extra_n
232
extra_n += len(hunk.lines)
235
def is_snapshot(self):
236
"""Return true of this hunk is effectively a fulltext"""
237
if len(self.hunks) != 1:
239
return (isinstance(self.hunks[0], NewText))
242
class NewText(object):
243
"""The contents of text that is introduced by this text"""
245
def __init__(self, lines):
248
def __eq__(self, other):
249
if self.__class__ is not other.__class__:
251
return (other.lines == self.lines)
254
return 'NewText(%r)' % self.lines
257
yield 'i %d\n' % len(self.lines)
258
for line in self.lines:
263
class ParentText(object):
264
"""A reference to text present in a parent text"""
266
def __init__(self, parent, parent_pos, child_pos, num_lines):
268
self.parent_pos = parent_pos
269
self.child_pos = child_pos
270
self.num_lines = num_lines
273
return 'ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'\
274
' %(num_lines)r)' % self.__dict__
276
def __eq__(self, other):
277
if self.__class__ != other.__class__:
279
return (self.__dict__ == other.__dict__)
282
yield 'c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'\
286
class BaseVersionedFile(object):
287
"""Pseudo-VersionedFile skeleton for MultiParent"""
289
def __init__(self, snapshot_interval=25, max_snapshots=None):
292
self._snapshots = set()
293
self.snapshot_interval = snapshot_interval
294
self.max_snapshots = max_snapshots
297
return iter(self._parents)
299
def has_version(self, version):
300
return version in self._parents
302
def do_snapshot(self, version_id, parent_ids):
303
"""Determine whether to perform a a snapshot for this version"""
304
if self.snapshot_interval is None:
306
if self.max_snapshots is not None and\
307
len(self._snapshots) == self.max_snapshots:
309
if len(parent_ids) == 0:
311
for ignored in xrange(self.snapshot_interval):
312
if len(parent_ids) == 0:
314
version_ids = parent_ids
316
for version_id in version_ids:
317
if version_id not in self._snapshots:
318
parent_ids.extend(self._parents[version_id])
322
def add_version(self, lines, version_id, parent_ids,
323
force_snapshot=None, single_parent=False):
324
"""Add a version to the versionedfile
326
:param lines: The list of lines to add. Must be split on '\n'.
327
:param version_id: The version_id of the version to add
328
:param force_snapshot: If true, force this version to be added as a
329
snapshot version. If false, force this version to be added as a
330
diff. If none, determine this automatically.
331
:param single_parent: If true, use a single parent, rather than
334
if force_snapshot is None:
335
do_snapshot = self.do_snapshot(version_id, parent_ids)
337
do_snapshot = force_snapshot
339
self._snapshots.add(version_id)
340
diff = MultiParent([NewText(lines)])
343
parent_lines = self.get_line_list(parent_ids[:1])
345
parent_lines = self.get_line_list(parent_ids)
346
diff = MultiParent.from_lines(lines, parent_lines)
347
if diff.is_snapshot():
348
self._snapshots.add(version_id)
349
self.add_diff(diff, version_id, parent_ids)
350
self._lines[version_id] = lines
352
def get_parents(self, version_id):
353
return self._parents[version_id]
355
def make_snapshot(self, version_id):
356
snapdiff = MultiParent([NewText(self.cache_version(version_id))])
357
self.add_diff(snapdiff, version_id, self._parents[version_id])
358
self._snapshots.add(version_id)
360
def import_versionedfile(self, vf, snapshots, no_cache=True,
361
single_parent=False, verify=False):
362
"""Import all revisions of a versionedfile
364
:param vf: The versionedfile to import
365
:param snapshots: If provided, the revisions to make snapshots of.
366
Otherwise, this will be auto-determined
367
:param no_cache: If true, clear the cache after every add.
368
:param single_parent: If true, omit all but one parent text, (but
369
retain parent metadata).
371
assert no_cache or not verify
372
revisions = set(vf.versions())
373
total = len(revisions)
374
pb = ui.ui_factory.nested_progress_bar()
376
while len(revisions) > 0:
378
for revision in revisions:
379
parents = vf.get_parents(revision)
380
if [p for p in parents if p not in self._parents] != []:
382
lines = [a + ' ' + l for a, l in
383
vf.annotate_iter(revision)]
384
if snapshots is None:
385
force_snapshot = None
387
force_snapshot = (revision in snapshots)
388
self.add_version(lines, revision, parents, force_snapshot,
395
assert lines == self.get_line_list([revision])[0]
397
pb.update('Importing revisions',
398
(total - len(revisions)) + len(added), total)
399
revisions = [r for r in revisions if r not in added]
403
def select_snapshots(self, vf):
404
"""Determine which versions to add as snapshots"""
408
for version_id in topo_iter(vf):
409
potential_build_ancestors = set(vf.get_parents(version_id))
410
parents = vf.get_parents(version_id)
411
if len(parents) == 0:
412
snapshots.add(version_id)
413
build_ancestors[version_id] = set()
415
for parent in vf.get_parents(version_id):
416
potential_build_ancestors.update(build_ancestors[parent])
417
if len(potential_build_ancestors) > self.snapshot_interval:
418
snapshots.add(version_id)
419
build_ancestors[version_id] = set()
421
build_ancestors[version_id] = potential_build_ancestors
424
def select_by_size(self, num):
425
"""Select snapshots for minimum output size"""
426
num -= len(self._snapshots)
427
new_snapshots = self.get_size_ranking()[-num:]
428
return [v for n, v in new_snapshots]
430
def get_size_ranking(self):
431
"""Get versions ranked by size"""
433
new_snapshots = set()
434
for version_id in self.versions():
435
if version_id in self._snapshots:
437
diff_len = self.get_diff(version_id).patch_len()
438
snapshot_len = MultiParent([NewText(
439
self.cache_version(version_id))]).patch_len()
440
versions.append((snapshot_len - diff_len, version_id))
444
def import_diffs(self, vf):
445
"""Import the diffs from another pseudo-versionedfile"""
446
for version_id in vf.versions():
447
self.add_diff(vf.get_diff(version_id), version_id,
448
vf._parents[version_id])
450
def get_build_ranking(self):
451
"""Return revisions sorted by how much they reduce build complexity"""
454
for version_id in topo_iter(self):
455
could_avoid[version_id] = set()
456
if version_id not in self._snapshots:
457
for parent_id in self._parents[version_id]:
458
could_avoid[version_id].update(could_avoid[parent_id])
459
could_avoid[version_id].update(self._parents)
460
could_avoid[version_id].discard(version_id)
461
for avoid_id in could_avoid[version_id]:
462
referenced_by.setdefault(avoid_id, set()).add(version_id)
463
available_versions = list(self.versions())
465
while len(available_versions) > 0:
466
available_versions.sort(key=lambda x:
467
len(could_avoid[x]) *
468
len(referenced_by.get(x, [])))
469
selected = available_versions.pop()
470
ranking.append(selected)
471
for version_id in referenced_by[selected]:
472
could_avoid[version_id].difference_update(
473
could_avoid[selected])
474
for version_id in could_avoid[selected]:
475
referenced_by[version_id].difference_update(
476
referenced_by[selected]
480
def clear_cache(self):
483
def get_line_list(self, version_ids):
484
return [self.cache_version(v) for v in version_ids]
486
def cache_version(self, version_id):
488
return self._lines[version_id]
491
diff = self.get_diff(version_id)
493
reconstructor = _Reconstructor(self, self._lines, self._parents)
494
reconstructor.reconstruct_version(lines, version_id)
495
self._lines[version_id] = lines
499
class MultiMemoryVersionedFile(BaseVersionedFile):
500
"""Memory-backed pseudo-versionedfile"""
502
def __init__(self, snapshot_interval=25, max_snapshots=None):
503
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
506
def add_diff(self, diff, version_id, parent_ids):
507
self._diffs[version_id] = diff
508
self._parents[version_id] = parent_ids
510
def get_diff(self, version_id):
511
return self._diffs[version_id]
517
class MultiVersionedFile(BaseVersionedFile):
518
"""Disk-backed pseudo-versionedfile"""
520
def __init__(self, filename, snapshot_interval=25, max_snapshots=None):
521
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
522
self._filename = filename
523
self._diff_offset = {}
525
def get_diff(self, version_id):
526
start, count = self._diff_offset[version_id]
527
infile = open(self._filename + '.mpknit', 'rb')
530
sio = StringIO(infile.read(count))
533
zip_file = GzipFile(None, mode='rb', fileobj=sio)
535
file_version_id = zip_file.readline()
536
return MultiParent.from_patch(zip_file.read())
540
def add_diff(self, diff, version_id, parent_ids):
541
outfile = open(self._filename + '.mpknit', 'ab')
543
outfile.seek(0, 2) # workaround for windows bug:
544
# .tell() for files opened in 'ab' mode
545
# before any write returns 0
546
start = outfile.tell()
548
zipfile = GzipFile(None, mode='ab', fileobj=outfile)
549
zipfile.writelines(itertools.chain(
550
['version %s\n' % version_id], diff.to_patch()))
556
self._diff_offset[version_id] = (start, end-start)
557
self._parents[version_id] = parent_ids
561
os.unlink(self._filename + '.mpknit')
563
if e.errno != errno.ENOENT:
566
os.unlink(self._filename + '.mpidx')
568
if e.errno != errno.ENOENT:
572
open(self._filename + '.mpidx', 'wb').write(bencode.bencode(
573
(self._parents, list(self._snapshots), self._diff_offset)))
576
self._parents, snapshots, self._diff_offset = bencode.bdecode(
577
open(self._filename + '.mpidx', 'rb').read())
578
self._snapshots = set(snapshots)
581
class _Reconstructor(object):
582
"""Build a text from the diffs, ancestry graph and cached lines"""
584
def __init__(self, diffs, lines, parents):
587
self.parents = parents
590
def reconstruct(self, lines, parent_text, version_id):
591
"""Append the lines referred to by a ParentText to lines"""
592
parent_id = self.parents[version_id][parent_text.parent]
593
end = parent_text.parent_pos + parent_text.num_lines
594
return self._reconstruct(lines, parent_id, parent_text.parent_pos,
597
def _reconstruct(self, lines, req_version_id, req_start, req_end):
598
"""Append lines for the requested version_id range"""
599
# stack of pending range requests
600
if req_start == req_end:
602
pending_reqs = [(req_version_id, req_start, req_end)]
603
while len(pending_reqs) > 0:
604
req_version_id, req_start, req_end = pending_reqs.pop()
605
# lazily allocate cursors for versions
606
if req_version_id in self.lines:
607
lines.extend(self.lines[req_version_id][req_start:req_end])
610
start, end, kind, data, iterator = self.cursor[req_version_id]
612
iterator = self.diffs.get_diff(req_version_id).range_iterator()
613
start, end, kind, data = iterator.next()
614
if start > req_start:
615
iterator = self.diffs.get_diff(req_version_id).range_iterator()
616
start, end, kind, data = iterator.next()
618
# find the first hunk relevant to the request
619
while end <= req_start:
620
start, end, kind, data = iterator.next()
621
self.cursor[req_version_id] = start, end, kind, data, iterator
622
# if the hunk can't satisfy the whole request, split it in two,
623
# and leave the second half for later.
625
pending_reqs.append((req_version_id, end, req_end))
628
lines.extend(data[req_start - start: (req_end - start)])
630
# If the hunk is a ParentText, rewrite it as a range request
631
# for the parent, and make it the next pending request.
632
parent, parent_start, parent_end = data
633
new_version_id = self.parents[req_version_id][parent]
634
new_start = parent_start + req_start - start
635
new_end = parent_end + req_end - end
636
pending_reqs.append((new_version_id, new_start, new_end))
638
def reconstruct_version(self, lines, version_id):
639
length = self.diffs.get_diff(version_id).num_lines()
640
return self._reconstruct(lines, version_id, 0, length)
643
def gzip_string(lines):
645
data_file = GzipFile(None, mode='wb', fileobj=sio)
646
data_file.writelines(lines)
648
return sio.getvalue()