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):
63
def __init__(self, hunks=None):
70
return "MultiParent(%r)" % self.hunks
72
def __eq__(self, other):
73
if self.__class__ is not other.__class__:
75
return (self.hunks == other.hunks)
78
def from_lines(text, parents=(), left_blocks=None):
79
"""Produce a MultiParent from a list of lines and parents"""
81
matcher = patiencediff.PatienceSequenceMatcher(None, parent,
83
return matcher.get_matching_blocks()
85
if left_blocks is None:
86
left_blocks = compare(parents[0])
87
parent_comparisons = [left_blocks] + [compare(p) for p in
90
parent_comparisons = []
92
new_text = NewText([])
94
block_iter = [iter(i) for i in parent_comparisons]
95
diff = MultiParent([])
98
return block_iter[p].next()
101
cur_block = [next_block(p) for p, i in enumerate(block_iter)]
102
while cur_line < len(text):
104
for p, block in enumerate(cur_block):
108
while j + n < cur_line:
109
block = cur_block[p] = next_block(p)
117
offset = cur_line - j
123
if best_match is None or n > best_match.num_lines:
124
best_match = ParentText(p, i, j, n)
125
if best_match is None:
126
new_text.lines.append(text[cur_line])
129
if len(new_text.lines) > 0:
130
diff.hunks.append(new_text)
131
new_text = NewText([])
132
diff.hunks.append(best_match)
133
cur_line += best_match.num_lines
134
if len(new_text.lines) > 0:
135
diff.hunks.append(new_text)
139
def from_texts(cls, text, parents=()):
140
"""Produce a MultiParent from a text and list of parent text"""
141
return cls.from_lines(text.splitlines(True),
142
[p.splitlines(True) for p in parents])
145
"""Yield text lines for a patch"""
146
for hunk in self.hunks:
147
for line in hunk.to_patch():
151
return len(''.join(self.to_patch()))
153
def zipped_patch_len(self):
154
return len(gzip_string(self.to_patch()))
157
def from_patch(cls, text):
158
return cls._from_patch(StringIO(text))
161
def _from_patch(lines):
162
"""This is private because it is essential to split lines on \n only"""
163
line_iter = iter(lines)
168
cur_line = line_iter.next()
169
except StopIteration:
171
if cur_line[0] == 'i':
172
num_lines = int(cur_line.split(' ')[1])
173
hunk_lines = [line_iter.next() for x in xrange(num_lines)]
174
hunk_lines[-1] = hunk_lines[-1][:-1]
175
hunks.append(NewText(hunk_lines))
176
elif cur_line[0] == '\n':
177
hunks[-1].lines[-1] += '\n'
179
assert cur_line[0] == 'c', cur_line[0]
180
parent, parent_pos, child_pos, num_lines =\
181
[int(v) for v in cur_line.split(' ')[1:]]
182
hunks.append(ParentText(parent, parent_pos, child_pos,
184
return MultiParent(hunks)
186
def range_iterator(self):
187
"""Iterate through the hunks, with range indicated
189
kind is "new" or "parent".
190
for "new", data is a list of lines.
191
for "parent", data is (parent, parent_start, parent_end)
192
:return: a generator of (start, end, kind, data)
195
for hunk in self.hunks:
196
if isinstance(hunk, NewText):
198
end = start + len(hunk.lines)
202
start = hunk.child_pos
203
end = start + hunk.num_lines
204
data = (hunk.parent, hunk.parent_pos, hunk.parent_pos +
206
yield start, end, kind, data
211
for hunk in reversed(self.hunks):
212
if isinstance(hunk, ParentText):
213
return hunk.child_pos + hunk.num_lines + extra_n
214
extra_n += len(hunk.lines)
217
def is_snapshot(self):
218
if len(self.hunks) != 1:
220
return (isinstance(self.hunks[0], NewText))
223
class NewText(object):
224
"""The contents of text that is introduced by this text"""
226
def __init__(self, lines):
229
def __eq__(self, other):
230
if self.__class__ is not other.__class__:
232
return (other.lines == self.lines)
235
return 'NewText(%r)' % self.lines
238
yield 'i %d\n' % len(self.lines)
239
for line in self.lines:
244
class ParentText(object):
245
"""A reference to text present in a parent text"""
247
def __init__(self, parent, parent_pos, child_pos, num_lines):
249
self.parent_pos = parent_pos
250
self.child_pos = child_pos
251
self.num_lines = num_lines
254
return 'ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'\
255
' %(num_lines)r)' % self.__dict__
257
def __eq__(self, other):
258
if self.__class__ != other.__class__:
260
return (self.__dict__ == other.__dict__)
263
yield 'c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'\
267
class BaseVersionedFile(object):
268
"""VersionedFile skeleton for MultiParent"""
270
def __init__(self, snapshot_interval=25, max_snapshots=None):
273
self._snapshots = set()
274
self.snapshot_interval = snapshot_interval
275
self.max_snapshots = max_snapshots
278
return iter(self._parents)
280
def has_version(self, version):
281
return version in self._parents
283
def do_snapshot(self, version_id, parent_ids):
284
if self.snapshot_interval is None:
286
if self.max_snapshots is not None and\
287
len(self._snapshots) == self.max_snapshots:
289
if len(parent_ids) == 0:
291
for ignored in xrange(self.snapshot_interval):
292
if len(parent_ids) == 0:
294
version_ids = parent_ids
296
for version_id in version_ids:
297
if version_id not in self._snapshots:
298
parent_ids.extend(self._parents[version_id])
302
def add_version(self, lines, version_id, parent_ids,
303
force_snapshot=None, single_parent=False):
304
if force_snapshot is None:
305
do_snapshot = self.do_snapshot(version_id, parent_ids)
307
do_snapshot = force_snapshot
309
self._snapshots.add(version_id)
310
diff = MultiParent([NewText(lines)])
313
parent_lines = self.get_line_list(parent_ids[:1])
315
parent_lines = self.get_line_list(parent_ids)
316
diff = MultiParent.from_lines(lines, parent_lines)
317
if diff.is_snapshot():
318
self._snapshots.add(version_id)
319
self.add_diff(diff, version_id, parent_ids)
320
self._lines[version_id] = lines
322
def get_parents(self, version_id):
323
return self._parents[version_id]
325
def make_snapshot(self, version_id):
326
snapdiff = MultiParent([NewText(self.cache_version(version_id))])
327
self.add_diff(snapdiff, version_id, self._parents[version_id])
328
self._snapshots.add(version_id)
330
def import_versionedfile(self, vf, snapshots, no_cache=True,
331
single_parent=False, verify=False):
332
"""Import all revisions of a versionedfile
334
:param vf: The versionedfile to import
335
:param snapshots: If provided, the revisions to make snapshots of.
336
Otherwise, this will be auto-determined
337
:param no_cache: If true, clear the cache after every add.
338
:param single_parent: If true, omit all but one parent text, (but
339
retain parent metadata).
341
assert no_cache or not verify
342
revisions = set(vf.versions())
343
total = len(revisions)
344
pb = ui.ui_factory.nested_progress_bar()
346
while len(revisions) > 0:
348
for revision in revisions:
349
parents = vf.get_parents(revision)
350
if [p for p in parents if p not in self._parents] != []:
352
lines = [a + ' ' + l for a, l in
353
vf.annotate_iter(revision)]
354
if snapshots is None:
355
force_snapshot = None
357
force_snapshot = (revision in snapshots)
358
self.add_version(lines, revision, parents, force_snapshot,
365
assert lines == self.get_line_list([revision])[0]
367
pb.update('Importing revisions',
368
(total - len(revisions)) + len(added), total)
369
revisions = [r for r in revisions if r not in added]
373
def select_snapshots(self, vf):
377
for version_id in topo_iter(vf):
378
potential_build_ancestors = set(vf.get_parents(version_id))
379
parents = vf.get_parents(version_id)
380
if len(parents) == 0:
381
snapshots.add(version_id)
382
build_ancestors[version_id] = set()
384
for parent in vf.get_parents(version_id):
385
potential_build_ancestors.update(build_ancestors[parent])
386
if len(potential_build_ancestors) > self.snapshot_interval:
387
snapshots.add(version_id)
388
build_ancestors[version_id] = set()
390
build_ancestors[version_id] = potential_build_ancestors
393
def select_by_size(self, num):
394
"""Select snapshots for minimum output size"""
395
num -= len(self._snapshots)
396
new_snapshots = self.get_size_ranking()[-num:]
397
return [v for n, v in new_snapshots]
399
def get_size_ranking(self):
401
new_snapshots = set()
402
for version_id in self.versions():
403
if version_id in self._snapshots:
405
diff_len = self.get_diff(version_id).patch_len()
406
snapshot_len = MultiParent([NewText(
407
self.cache_version(version_id))]).patch_len()
408
versions.append((snapshot_len - diff_len, version_id))
411
return [v for n, v in versions]
413
def import_diffs(self, vf):
414
for version_id in vf.versions():
415
self.add_diff(vf.get_diff(version_id), version_id,
416
vf._parents[version_id])
418
def get_build_ranking(self):
421
for version_id in topo_iter(self):
422
could_avoid[version_id] = set()
423
if version_id not in self._snapshots:
424
for parent_id in self._parents[version_id]:
425
could_avoid[version_id].update(could_avoid[parent_id])
426
could_avoid[version_id].update(self._parents)
427
could_avoid[version_id].discard(version_id)
428
for avoid_id in could_avoid[version_id]:
429
referenced_by.setdefault(avoid_id, set()).add(version_id)
430
available_versions = list(self.versions())
432
while len(available_versions) > 0:
433
available_versions.sort(key=lambda x:
434
len(could_avoid[x]) *
435
len(referenced_by.get(x, [])))
436
selected = available_versions.pop()
437
ranking.append(selected)
438
for version_id in referenced_by[selected]:
439
could_avoid[version_id].difference_update(
440
could_avoid[selected])
441
for version_id in could_avoid[selected]:
442
referenced_by[version_id].difference_update(
443
referenced_by[selected]
447
def clear_cache(self):
450
def get_line_list(self, version_ids):
451
return [self.cache_version(v) for v in version_ids]
453
def cache_version(self, version_id):
455
return self._lines[version_id]
458
diff = self.get_diff(version_id)
460
reconstructor = _Reconstructor(self, self._lines,
462
reconstructor.reconstruct_version(lines, version_id)
463
self._lines[version_id] = lines
467
class MultiMemoryVersionedFile(BaseVersionedFile):
469
def __init__(self, snapshot_interval=25, max_snapshots=None):
470
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
473
def add_diff(self, diff, version_id, parent_ids):
474
self._diffs[version_id] = diff
475
self._parents[version_id] = parent_ids
477
def get_diff(self, version_id):
478
return self._diffs[version_id]
484
class MultiVersionedFile(BaseVersionedFile):
486
def __init__(self, filename, snapshot_interval=25, max_snapshots=None):
487
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
488
self._filename = filename
489
self._diff_offset = {}
491
def get_diff(self, version_id):
492
start, count = self._diff_offset[version_id]
493
infile = open(self._filename + '.mpknit', 'rb')
496
sio = StringIO(infile.read(count))
499
zip_file = GzipFile(None, mode='rb', fileobj=sio)
501
file_version_id = zip_file.readline()
502
return MultiParent.from_patch(zip_file.read())
506
def add_diff(self, diff, version_id, parent_ids):
507
outfile = open(self._filename + '.mpknit', 'ab')
509
start = outfile.tell()
511
zipfile = GzipFile(None, mode='ab', fileobj=outfile)
512
zipfile.writelines(itertools.chain(
513
['version %s\n' % version_id], diff.to_patch()))
519
self._diff_offset[version_id] = (start, end-start)
520
self._parents[version_id] = parent_ids
524
os.unlink(self._filename + '.mpknit')
526
if e.errno != errno.ENOENT:
529
os.unlink(self._filename + '.mpidx')
531
if e.errno != errno.ENOENT:
535
open(self._filename + '.mpidx', 'wb').write(bencode.bencode(
536
(self._parents, list(self._snapshots), self._diff_offset)))
539
self._parents, snapshots, self._diff_offset = bencode.bdecode(
540
open(self._filename + '.mpidx', 'rb').read())
541
self._snapshots = set(snapshots)
544
class _Reconstructor(object):
545
"""Build a text from the diffs, ancestry graph and cached lines"""
547
def __init__(self, diffs, lines, parents):
550
self.parents = parents
553
def reconstruct(self, lines, parent_text, version_id):
554
"""Append the lines referred to by a ParentText to lines"""
555
parent_id = self.parents[version_id][parent_text.parent]
556
end = parent_text.parent_pos + parent_text.num_lines
557
return self._reconstruct(lines, parent_id, parent_text.parent_pos,
560
def _reconstruct(self, lines, req_version_id, req_start, req_end):
561
"""Append lines for the requested version_id range"""
562
# stack of pending range requests
563
if req_start == req_end:
565
pending_reqs = [(req_version_id, req_start, req_end)]
566
while len(pending_reqs) > 0:
567
req_version_id, req_start, req_end = pending_reqs.pop()
568
# lazily allocate cursors for versions
570
start, end, kind, data, iterator = self.cursor[req_version_id]
572
iterator = self.diffs.get_diff(req_version_id).range_iterator()
573
start, end, kind, data = iterator.next()
574
if start > req_start:
575
iterator = self.diffs.get_diff(req_version_id).range_iterator()
576
start, end, kind, data = iterator.next()
578
# find the first hunk relevant to the request
579
while end <= req_start:
580
start, end, kind, data = iterator.next()
581
self.cursor[req_version_id] = start, end, kind, data, iterator
582
# if the hunk can't satisfy the whole request, split it in two,
583
# and leave the second half for later.
585
pending_reqs.append((req_version_id, end, req_end))
588
lines.extend(data[req_start - start: (req_end - start)])
590
# If the hunk is a ParentText, rewrite it as a range request
591
# for the parent, and make it the next pending request.
592
parent, parent_start, parent_end = data
593
new_version_id = self.parents[req_version_id][parent]
594
new_start = parent_start + req_start - start
595
new_end = parent_end + req_end - end
596
pending_reqs.append((new_version_id, new_start, new_end))
598
def reconstruct_version(self, lines, version_id):
599
length = self.diffs.get_diff(version_id).num_lines()
600
return self._reconstruct(lines, version_id, 0, length)
603
def gzip_string(lines):
605
data_file = GzipFile(None, mode='wb', fileobj=sio)
606
data_file.writelines(lines)
608
return sio.getvalue()