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
22
from .lazy_import import lazy_import
24
lazy_import(globals(), """
35
from .i18n import gettext
42
def topo_iter_keys(vf, keys=None):
45
parents = vf.get_parent_map(keys)
46
return _topo_iter(parents, keys)
49
def topo_iter(vf, versions=None):
51
versions = vf.versions()
52
parents = vf.get_parent_map(versions)
53
return _topo_iter(parents, versions)
56
def _topo_iter(parents, versions):
60
def pending_parents(version):
61
if parents[version] is None:
63
return [v for v in parents[version] if v in versions and
65
for version_id in versions:
66
if parents[version_id] is None:
69
for parent_id in parents[version_id]:
70
descendants.setdefault(parent_id, []).append(version_id)
71
cur = [v for v in versions if len(pending_parents(v)) == 0]
74
for version_id in cur:
75
if version_id in seen:
77
if len(pending_parents(version_id)) != 0:
79
next.extend(descendants.get(version_id, []))
85
class MultiParent(object):
86
"""A multi-parent diff"""
90
def __init__(self, hunks=None):
97
return "MultiParent(%r)" % self.hunks
99
def __eq__(self, other):
100
if self.__class__ is not other.__class__:
102
return (self.hunks == other.hunks)
105
def from_lines(text, parents=(), left_blocks=None):
106
"""Produce a MultiParent from a list of lines and parents"""
108
matcher = patiencediff.PatienceSequenceMatcher(None, parent,
110
return matcher.get_matching_blocks()
112
if left_blocks is None:
113
left_blocks = compare(parents[0])
114
parent_comparisons = [left_blocks] + [compare(p) for p in
117
parent_comparisons = []
119
new_text = NewText([])
121
block_iter = [iter(i) for i in parent_comparisons]
122
diff = MultiParent([])
126
return next(block_iter[p])
127
except StopIteration:
129
cur_block = [next_block(p) for p, i in enumerate(block_iter)]
130
while cur_line < len(text):
132
for p, block in enumerate(cur_block):
136
while j + n <= cur_line:
137
block = cur_block[p] = next_block(p)
145
offset = cur_line - j
151
if best_match is None or n > best_match.num_lines:
152
best_match = ParentText(p, i, j, n)
153
if best_match is None:
154
new_text.lines.append(text[cur_line])
157
if len(new_text.lines) > 0:
158
diff.hunks.append(new_text)
159
new_text = NewText([])
160
diff.hunks.append(best_match)
161
cur_line += best_match.num_lines
162
if len(new_text.lines) > 0:
163
diff.hunks.append(new_text)
166
def get_matching_blocks(self, parent, parent_len):
167
for hunk in self.hunks:
168
if not isinstance(hunk, ParentText) or hunk.parent != parent:
170
yield (hunk.parent_pos, hunk.child_pos, hunk.num_lines)
171
yield parent_len, self.num_lines(), 0
173
def to_lines(self, parents=()):
174
"""Contruct a fulltext from this diff and its parents"""
175
mpvf = MultiMemoryVersionedFile()
176
for num, parent in enumerate(parents):
177
mpvf.add_version(BytesIO(parent).readlines(), num, [])
178
mpvf.add_diff(self, 'a', list(range(len(parents))))
179
return mpvf.get_line_list(['a'])[0]
182
def from_texts(cls, text, parents=()):
183
"""Produce a MultiParent from a text and list of parent text"""
184
return cls.from_lines(BytesIO(text).readlines(),
185
[BytesIO(p).readlines() for p in parents])
188
"""Yield text lines for a patch"""
189
for hunk in self.hunks:
190
for line in hunk.to_patch():
194
return len(b''.join(self.to_patch()))
196
def zipped_patch_len(self):
197
return len(gzip_string(self.to_patch()))
200
def from_patch(cls, text):
201
"""Create a MultiParent from its string form"""
202
return cls._from_patch(BytesIO(text))
205
def _from_patch(lines):
206
"""This is private because it is essential to split lines on \n only"""
207
line_iter = iter(lines)
212
cur_line = next(line_iter)
213
except StopIteration:
215
first_char = cur_line[0:1]
216
if first_char == b'i':
217
num_lines = int(cur_line.split(b' ')[1])
218
hunk_lines = [next(line_iter) for _ in range(num_lines)]
219
hunk_lines[-1] = hunk_lines[-1][:-1]
220
hunks.append(NewText(hunk_lines))
221
elif first_char == b'\n':
222
hunks[-1].lines[-1] += b'\n'
224
if not (first_char == b'c'):
225
raise AssertionError(first_char)
226
parent, parent_pos, child_pos, num_lines =\
227
[int(v) for v in cur_line.split(b' ')[1:]]
228
hunks.append(ParentText(parent, parent_pos, child_pos,
230
return MultiParent(hunks)
232
def range_iterator(self):
233
"""Iterate through the hunks, with range indicated
235
kind is "new" or "parent".
236
for "new", data is a list of lines.
237
for "parent", data is (parent, parent_start, parent_end)
238
:return: a generator of (start, end, kind, data)
241
for hunk in self.hunks:
242
if isinstance(hunk, NewText):
244
end = start + len(hunk.lines)
248
start = hunk.child_pos
249
end = start + hunk.num_lines
250
data = (hunk.parent, hunk.parent_pos, hunk.parent_pos +
252
yield start, end, kind, data
256
"""The number of lines in the output text"""
258
for hunk in reversed(self.hunks):
259
if isinstance(hunk, ParentText):
260
return hunk.child_pos + hunk.num_lines + extra_n
261
extra_n += len(hunk.lines)
264
def is_snapshot(self):
265
"""Return true of this hunk is effectively a fulltext"""
266
if len(self.hunks) != 1:
268
return (isinstance(self.hunks[0], NewText))
271
class NewText(object):
272
"""The contents of text that is introduced by this text"""
274
__slots__ = ['lines']
276
def __init__(self, lines):
279
def __eq__(self, other):
280
if self.__class__ is not other.__class__:
282
return (other.lines == self.lines)
285
return 'NewText(%r)' % self.lines
288
yield b'i %d\n' % len(self.lines)
289
for line in self.lines:
294
class ParentText(object):
295
"""A reference to text present in a parent text"""
297
__slots__ = ['parent', 'parent_pos', 'child_pos', 'num_lines']
299
def __init__(self, parent, parent_pos, child_pos, num_lines):
301
self.parent_pos = parent_pos
302
self.child_pos = child_pos
303
self.num_lines = num_lines
306
return {b'parent': self.parent,
307
b'parent_pos': self.parent_pos,
308
b'child_pos': self.child_pos,
309
b'num_lines': self.num_lines}
312
return ('ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'
313
' %(num_lines)r)' % self._as_dict())
315
def __eq__(self, other):
316
if self.__class__ is not other.__class__:
318
return self._as_dict() == other._as_dict()
321
yield (b'c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'
325
class BaseVersionedFile(object):
326
"""Pseudo-VersionedFile skeleton for MultiParent"""
328
def __init__(self, snapshot_interval=25, max_snapshots=None):
331
self._snapshots = set()
332
self.snapshot_interval = snapshot_interval
333
self.max_snapshots = max_snapshots
336
return iter(self._parents)
338
def has_version(self, version):
339
return version in self._parents
341
def do_snapshot(self, version_id, parent_ids):
342
"""Determine whether to perform a snapshot for this version"""
343
if self.snapshot_interval is None:
345
if self.max_snapshots is not None and\
346
len(self._snapshots) == self.max_snapshots:
348
if len(parent_ids) == 0:
350
for ignored in range(self.snapshot_interval):
351
if len(parent_ids) == 0:
353
version_ids = parent_ids
355
for version_id in version_ids:
356
if version_id not in self._snapshots:
357
parent_ids.extend(self._parents[version_id])
361
def add_version(self, lines, version_id, parent_ids,
362
force_snapshot=None, single_parent=False):
363
"""Add a version to the versionedfile
365
:param lines: The list of lines to add. Must be split on '\n'.
366
:param version_id: The version_id of the version to add
367
:param force_snapshot: If true, force this version to be added as a
368
snapshot version. If false, force this version to be added as a
369
diff. If none, determine this automatically.
370
:param single_parent: If true, use a single parent, rather than
373
if force_snapshot is None:
374
do_snapshot = self.do_snapshot(version_id, parent_ids)
376
do_snapshot = force_snapshot
378
self._snapshots.add(version_id)
379
diff = MultiParent([NewText(lines)])
382
parent_lines = self.get_line_list(parent_ids[:1])
384
parent_lines = self.get_line_list(parent_ids)
385
diff = MultiParent.from_lines(lines, parent_lines)
386
if diff.is_snapshot():
387
self._snapshots.add(version_id)
388
self.add_diff(diff, version_id, parent_ids)
389
self._lines[version_id] = lines
391
def get_parents(self, version_id):
392
return self._parents[version_id]
394
def make_snapshot(self, version_id):
395
snapdiff = MultiParent([NewText(self.cache_version(version_id))])
396
self.add_diff(snapdiff, version_id, self._parents[version_id])
397
self._snapshots.add(version_id)
399
def import_versionedfile(self, vf, snapshots, no_cache=True,
400
single_parent=False, verify=False):
401
"""Import all revisions of a versionedfile
403
:param vf: The versionedfile to import
404
:param snapshots: If provided, the revisions to make snapshots of.
405
Otherwise, this will be auto-determined
406
:param no_cache: If true, clear the cache after every add.
407
:param single_parent: If true, omit all but one parent text, (but
408
retain parent metadata).
410
if not (no_cache or not verify):
412
revisions = set(vf.versions())
413
total = len(revisions)
414
with ui.ui_factory.nested_progress_bar() as pb:
415
while len(revisions) > 0:
417
for revision in revisions:
418
parents = vf.get_parents(revision)
419
if [p for p in parents if p not in self._parents] != []:
421
lines = [a + b' ' + l for a, l in
422
vf.annotate(revision)]
423
if snapshots is None:
424
force_snapshot = None
426
force_snapshot = (revision in snapshots)
427
self.add_version(lines, revision, parents, force_snapshot,
434
if not (lines == self.get_line_list([revision])[0]):
435
raise AssertionError()
437
pb.update(gettext('Importing revisions'),
438
(total - len(revisions)) + len(added), total)
439
revisions = [r for r in revisions if r not in added]
441
def select_snapshots(self, vf):
442
"""Determine which versions to add as snapshots"""
445
for version_id in topo_iter(vf):
446
potential_build_ancestors = set(vf.get_parents(version_id))
447
parents = vf.get_parents(version_id)
448
if len(parents) == 0:
449
snapshots.add(version_id)
450
build_ancestors[version_id] = set()
452
for parent in vf.get_parents(version_id):
453
potential_build_ancestors.update(build_ancestors[parent])
454
if len(potential_build_ancestors) > self.snapshot_interval:
455
snapshots.add(version_id)
456
build_ancestors[version_id] = set()
458
build_ancestors[version_id] = potential_build_ancestors
461
def select_by_size(self, num):
462
"""Select snapshots for minimum output size"""
463
num -= len(self._snapshots)
464
new_snapshots = self.get_size_ranking()[-num:]
465
return [v for n, v in new_snapshots]
467
def get_size_ranking(self):
468
"""Get versions ranked by size"""
470
for version_id in self.versions():
471
if version_id in self._snapshots:
473
diff_len = self.get_diff(version_id).patch_len()
474
snapshot_len = MultiParent([NewText(
475
self.cache_version(version_id))]).patch_len()
476
versions.append((snapshot_len - diff_len, version_id))
480
def import_diffs(self, vf):
481
"""Import the diffs from another pseudo-versionedfile"""
482
for version_id in vf.versions():
483
self.add_diff(vf.get_diff(version_id), version_id,
484
vf._parents[version_id])
486
def get_build_ranking(self):
487
"""Return revisions sorted by how much they reduce build complexity"""
490
for version_id in topo_iter(self):
491
could_avoid[version_id] = set()
492
if version_id not in self._snapshots:
493
for parent_id in self._parents[version_id]:
494
could_avoid[version_id].update(could_avoid[parent_id])
495
could_avoid[version_id].update(self._parents)
496
could_avoid[version_id].discard(version_id)
497
for avoid_id in could_avoid[version_id]:
498
referenced_by.setdefault(avoid_id, set()).add(version_id)
499
available_versions = list(self.versions())
501
while len(available_versions) > 0:
502
available_versions.sort(key=lambda x:
503
len(could_avoid[x]) *
504
len(referenced_by.get(x, [])))
505
selected = available_versions.pop()
506
ranking.append(selected)
507
for version_id in referenced_by[selected]:
508
could_avoid[version_id].difference_update(
509
could_avoid[selected])
510
for version_id in could_avoid[selected]:
511
referenced_by[version_id].difference_update(
512
referenced_by[selected]
516
def clear_cache(self):
519
def get_line_list(self, version_ids):
520
return [self.cache_version(v) for v in version_ids]
522
def cache_version(self, version_id):
524
return self._lines[version_id]
527
diff = self.get_diff(version_id)
529
reconstructor = _Reconstructor(self, self._lines, self._parents)
530
reconstructor.reconstruct_version(lines, version_id)
531
self._lines[version_id] = lines
535
class MultiMemoryVersionedFile(BaseVersionedFile):
536
"""Memory-backed pseudo-versionedfile"""
538
def __init__(self, snapshot_interval=25, max_snapshots=None):
539
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
542
def add_diff(self, diff, version_id, parent_ids):
543
self._diffs[version_id] = diff
544
self._parents[version_id] = parent_ids
546
def get_diff(self, version_id):
548
return self._diffs[version_id]
550
raise errors.RevisionNotPresent(version_id, self)
556
class MultiVersionedFile(BaseVersionedFile):
557
"""Disk-backed pseudo-versionedfile"""
559
def __init__(self, filename, snapshot_interval=25, max_snapshots=None):
560
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
561
self._filename = filename
562
self._diff_offset = {}
564
def get_diff(self, version_id):
565
start, count = self._diff_offset[version_id]
566
with open(self._filename + '.mpknit', 'rb') as infile:
568
sio = BytesIO(infile.read(count))
569
with gzip.GzipFile(None, mode='rb', fileobj=sio) as zip_file:
570
file_version_id = zip_file.readline()
571
content = zip_file.read()
572
return MultiParent.from_patch(content)
574
def add_diff(self, diff, version_id, parent_ids):
575
with open(self._filename + '.mpknit', 'ab') as outfile:
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()
580
with gzip.GzipFile(None, mode='ab', fileobj=outfile) as zipfile:
581
zipfile.writelines(itertools.chain(
582
[b'version %s\n' % version_id], diff.to_patch()))
584
self._diff_offset[version_id] = (start, end - start)
585
self._parents[version_id] = parent_ids
589
os.unlink(self._filename + '.mpknit')
591
if e.errno != errno.ENOENT:
594
os.unlink(self._filename + '.mpidx')
596
if e.errno != errno.ENOENT:
600
open(self._filename + '.mpidx', 'wb').write(bencode.bencode(
601
(self._parents, list(self._snapshots), self._diff_offset)))
604
self._parents, snapshots, self._diff_offset = bencode.bdecode(
605
open(self._filename + '.mpidx', 'rb').read())
606
self._snapshots = set(snapshots)
609
class _Reconstructor(object):
610
"""Build a text from the diffs, ancestry graph and cached lines"""
612
def __init__(self, diffs, lines, parents):
615
self.parents = parents
618
def reconstruct(self, lines, parent_text, version_id):
619
"""Append the lines referred to by a ParentText to lines"""
620
parent_id = self.parents[version_id][parent_text.parent]
621
end = parent_text.parent_pos + parent_text.num_lines
622
return self._reconstruct(lines, parent_id, parent_text.parent_pos,
625
def _reconstruct(self, lines, req_version_id, req_start, req_end):
626
"""Append lines for the requested version_id range"""
627
# stack of pending range requests
628
if req_start == req_end:
630
pending_reqs = [(req_version_id, req_start, req_end)]
631
while len(pending_reqs) > 0:
632
req_version_id, req_start, req_end = pending_reqs.pop()
633
# lazily allocate cursors for versions
634
if req_version_id in self.lines:
635
lines.extend(self.lines[req_version_id][req_start:req_end])
638
start, end, kind, data, iterator = self.cursor[req_version_id]
640
iterator = self.diffs.get_diff(req_version_id).range_iterator()
641
start, end, kind, data = next(iterator)
642
if start > req_start:
643
iterator = self.diffs.get_diff(req_version_id).range_iterator()
644
start, end, kind, data = next(iterator)
646
# find the first hunk relevant to the request
647
while end <= req_start:
648
start, end, kind, data = next(iterator)
649
self.cursor[req_version_id] = start, end, kind, data, iterator
650
# if the hunk can't satisfy the whole request, split it in two,
651
# and leave the second half for later.
653
pending_reqs.append((req_version_id, end, req_end))
656
lines.extend(data[req_start - start: (req_end - start)])
658
# If the hunk is a ParentText, rewrite it as a range request
659
# for the parent, and make it the next pending request.
660
parent, parent_start, parent_end = data
661
new_version_id = self.parents[req_version_id][parent]
662
new_start = parent_start + req_start - start
663
new_end = parent_end + req_end - end
664
pending_reqs.append((new_version_id, new_start, new_end))
666
def reconstruct_version(self, lines, version_id):
667
length = self.diffs.get_diff(version_id).num_lines()
668
return self._reconstruct(lines, version_id, 0, length)
671
def gzip_string(lines):
673
with gzip.GzipFile(None, mode='wb', fileobj=sio) as data_file:
674
data_file.writelines(lines)
675
return sio.getvalue()