1
from bzrlib.lazy_import import lazy_import
3
lazy_import(globals(), """
7
from StringIO import StringIO
14
from bzrlib.util import bencode
16
from bzrlib.tuned_gzip import GzipFile
22
for version_id in vf.versions():
23
for parent_id in vf.get_parents(version_id):
24
descendants.setdefault(parent_id, []).append(version_id)
25
cur = [v for v in vf.versions() if len(vf.get_parents(v)) == 0]
28
for version_id in cur:
29
if version_id in seen:
31
parents = vf.get_parents(version_id)
32
if not seen.issuperset(parents):
34
next.extend(descendants.get(version_id, []))
40
class MultiParent(object):
42
def __init__(self, hunks=None):
49
return "MultiParent(%r)" % self.hunks
51
def __eq__(self, other):
52
if self.__class__ is not other.__class__:
54
return (self.hunks == other.hunks)
57
def from_lines(text, parents=()):
58
"""Produce a MultiParent from a list of lines and parents"""
60
matcher = patiencediff.PatienceSequenceMatcher(None, parent,
62
return matcher.get_matching_blocks()
63
parent_comparisons = [compare(p) for p in parents]
65
new_text = NewText([])
67
block_iter = [iter(i) for i in parent_comparisons]
68
diff = MultiParent([])
71
return block_iter[p].next()
74
cur_block = [next_block(p) for p, i in enumerate(block_iter)]
75
while cur_line < len(text):
77
for p, block in enumerate(cur_block):
81
while j + n < cur_line:
82
block = cur_block[p] = next_block(p)
96
if best_match is None or n > best_match.num_lines:
97
best_match = ParentText(p, i, j, n)
98
if best_match is None:
99
new_text.lines.append(text[cur_line])
102
if len(new_text.lines) > 0:
103
diff.hunks.append(new_text)
104
new_text = NewText([])
105
diff.hunks.append(best_match)
106
cur_line += best_match.num_lines
107
if len(new_text.lines) > 0:
108
diff.hunks.append(new_text)
112
def from_texts(cls, text, parents=()):
113
"""Produce a MultiParent from a text and list of parent text"""
114
return cls.from_lines(text.splitlines(True),
115
[p.splitlines(True) for p in parents])
118
"""Yield text lines for a patch"""
119
for hunk in self.hunks:
120
for line in hunk.to_patch():
124
return len(''.join(self.to_patch()))
126
def zipped_patch_len(self):
127
return len(gzip_string(self.to_patch()))
130
def from_patch(lines):
131
"""Produce a MultiParent from a sequence of lines"""
132
line_iter = iter(lines)
137
cur_line = line_iter.next()
138
except StopIteration:
140
if cur_line[0] == 'i':
141
num_lines = int(cur_line.split(' ')[1])
142
hunk_lines = [line_iter.next() for x in xrange(num_lines)]
143
hunk_lines[-1] = hunk_lines[-1][:-1]
144
hunks.append(NewText(hunk_lines))
145
elif cur_line[0] == '\n':
146
hunks[-1].lines[-1] += '\n'
148
assert cur_line[0] == 'c', cur_line[0]
149
parent, parent_pos, child_pos, num_lines =\
150
[int(v) for v in cur_line.split(' ')[1:]]
151
hunks.append(ParentText(parent, parent_pos, child_pos,
153
return MultiParent(hunks)
155
def range_iterator(self):
156
"""Iterate through the hunks, with range indicated
158
kind is "new" or "parent".
159
for "new", data is a list of lines.
160
for "parent", data is (parent, parent_start, parent_end)
161
:return: a generator of (start, end, kind, data)
164
for hunk in self.hunks:
165
if isinstance(hunk, NewText):
167
end = start + len(hunk.lines)
171
start = hunk.child_pos
172
end = start + hunk.num_lines
173
data = (hunk.parent, hunk.parent_pos, hunk.parent_pos +
175
yield start, end, kind, data
180
for hunk in reversed(self.hunks):
181
if isinstance(hunk, ParentText):
182
return hunk.child_pos + hunk.num_lines + extra_n
183
extra_n += len(hunk.lines)
186
def is_snapshot(self):
187
if len(self.hunks) != 1:
189
return (isinstance(self.hunks[0], NewText))
192
class NewText(object):
193
"""The contents of text that is introduced by this text"""
195
def __init__(self, lines):
198
def __eq__(self, other):
199
if self.__class__ is not other.__class__:
201
return (other.lines == self.lines)
204
return 'NewText(%r)' % self.lines
207
yield 'i %d\n' % len(self.lines)
208
for line in self.lines:
213
class ParentText(object):
214
"""A reference to text present in a parent text"""
216
def __init__(self, parent, parent_pos, child_pos, num_lines):
218
self.parent_pos = parent_pos
219
self.child_pos = child_pos
220
self.num_lines = num_lines
223
return 'ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'\
224
' %(num_lines)r)' % self.__dict__
226
def __eq__(self, other):
227
if self.__class__ != other.__class__:
229
return (self.__dict__ == other.__dict__)
232
yield 'c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'\
236
class BaseVersionedFile(object):
237
"""VersionedFile skeleton for MultiParent"""
239
def __init__(self, snapshot_interval=25, max_snapshots=None):
242
self._snapshots = set()
243
self.snapshot_interval = snapshot_interval
244
self.max_snapshots = max_snapshots
247
return iter(self._parents)
249
def do_snapshot(self, version_id, parent_ids):
250
if self.snapshot_interval is None:
252
if self.max_snapshots is not None and\
253
len(self._snapshots) == self.max_snapshots:
255
if len(parent_ids) == 0:
257
for ignored in xrange(self.snapshot_interval):
258
if len(parent_ids) == 0:
260
version_ids = parent_ids
262
for version_id in version_ids:
263
if version_id not in self._snapshots:
264
parent_ids.extend(self._parents[version_id])
268
def add_version(self, lines, version_id, parent_ids,
269
force_snapshot=None, single_parent=False):
270
if force_snapshot is None:
271
do_snapshot = self.do_snapshot(version_id, parent_ids)
273
do_snapshot = force_snapshot
275
self._snapshots.add(version_id)
276
diff = MultiParent([NewText(lines)])
279
parent_lines = self.get_line_list(parent_ids[:1])
281
parent_lines = self.get_line_list(parent_ids)
282
diff = MultiParent.from_lines(lines, parent_lines)
283
if diff.is_snapshot():
284
self._snapshots.add(version_id)
285
self.add_diff(diff, version_id, parent_ids)
286
self._lines[version_id] = lines
288
def get_parents(self, version_id):
289
return self._parents[version_id]
291
def make_snapshot(self, version_id):
292
snapdiff = MultiParent([NewText(self.cache_version(version_id))])
293
self.add_diff(snapdiff, version_id, self._parents[version_id])
294
self._snapshots.add(version_id)
296
def import_versionedfile(self, vf, snapshots, no_cache=True,
297
single_parent=False, verify=False):
298
"""Import all revisions of a versionedfile
300
:param vf: The versionedfile to import
301
:param snapshots: If provided, the revisions to make snapshots of.
302
Otherwise, this will be auto-determined
303
:param no_cache: If true, clear the cache after every add.
304
:param single_parent: If true, omit all but one parent text, (but
305
retain parent metadata).
307
assert no_cache or not verify
308
revisions = set(vf.versions())
309
total = len(revisions)
310
pb = ui.ui_factory.nested_progress_bar()
312
while len(revisions) > 0:
314
for revision in revisions:
315
parents = vf.get_parents(revision)
316
if [p for p in parents if p not in self._parents] != []:
318
lines = [a + ' ' + l for a, l in
319
vf.annotate_iter(revision)]
320
if snapshots is None:
321
force_snapshot = None
323
force_snapshot = (revision in snapshots)
324
self.add_version(lines, revision, parents, force_snapshot,
331
assert lines == self.get_line_list([revision])[0]
333
pb.update('Importing revisions',
334
(total - len(revisions)) + len(added), total)
335
revisions = [r for r in revisions if r not in added]
339
def select_snapshots(self, vf):
343
for version_id in topo_iter(vf):
344
potential_build_ancestors = set(vf.get_parents(version_id))
345
parents = vf.get_parents(version_id)
346
if len(parents) == 0:
347
snapshots.add(version_id)
348
build_ancestors[version_id] = set()
350
for parent in vf.get_parents(version_id):
351
potential_build_ancestors.update(build_ancestors[parent])
352
if len(potential_build_ancestors) > self.snapshot_interval:
353
snapshots.add(version_id)
354
build_ancestors[version_id] = set()
356
build_ancestors[version_id] = potential_build_ancestors
359
def select_by_size(self, num):
360
"""Select snapshots for minimum output size"""
361
num -= len(self._snapshots)
362
new_snapshots = self.get_size_ranking()[-num:]
363
return [v for n, v in new_snapshots]
365
def get_size_ranking(self):
367
new_snapshots = set()
368
for version_id in self.versions():
369
if version_id in self._snapshots:
371
diff_len = self.get_diff(version_id).patch_len()
372
snapshot_len = MultiParent([NewText(
373
self.cache_version(version_id))]).patch_len()
374
versions.append((snapshot_len - diff_len, version_id))
377
return [v for n, v in versions]
379
def import_diffs(self, vf):
380
for version_id in vf.versions():
381
self.add_diff(vf.get_diff(version_id), version_id,
382
vf._parents[version_id])
384
def get_build_ranking(self):
387
for version_id in topo_iter(self):
388
could_avoid[version_id] = set()
389
if version_id not in self._snapshots:
390
for parent_id in self._parents[version_id]:
391
could_avoid[version_id].update(could_avoid[parent_id])
392
could_avoid[version_id].update(self._parents)
393
could_avoid[version_id].discard(version_id)
394
for avoid_id in could_avoid[version_id]:
395
referenced_by.setdefault(avoid_id, set()).add(version_id)
396
available_versions = list(self.versions())
398
while len(available_versions) > 0:
399
available_versions.sort(key=lambda x:
400
len(could_avoid[x]) *
401
len(referenced_by.get(x, [])))
402
selected = available_versions.pop()
403
ranking.append(selected)
404
for version_id in referenced_by[selected]:
405
could_avoid[version_id].difference_update(
406
could_avoid[selected])
407
for version_id in could_avoid[selected]:
408
referenced_by[version_id].difference_update(
409
referenced_by[selected]
413
def clear_cache(self):
416
def get_line_list(self, version_ids):
417
return [self.cache_version(v) for v in version_ids]
419
def cache_version(self, version_id):
421
return self._lines[version_id]
424
diff = self.get_diff(version_id)
426
reconstructor = _Reconstructor(self, self._lines,
428
reconstructor.reconstruct_version(lines, version_id)
429
self._lines[version_id] = lines
433
class MultiMemoryVersionedFile(BaseVersionedFile):
435
def __init__(self, snapshot_interval=25, max_snapshots=None):
436
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
439
def add_diff(self, diff, version_id, parent_ids):
440
self._diffs[version_id] = diff
441
self._parents[version_id] = parent_ids
443
def get_diff(self, version_id):
444
return self._diffs[version_id]
450
class MultiVersionedFile(BaseVersionedFile):
452
def __init__(self, filename, snapshot_interval=25, max_snapshots=None):
453
BaseVersionedFile.__init__(self, snapshot_interval, max_snapshots)
454
self._filename = filename
455
self._diff_offset = {}
457
def get_diff(self, version_id):
458
start, count = self._diff_offset[version_id]
459
infile = open(self._filename + '.mpknit', 'rb')
462
sio = StringIO(infile.read(count))
465
zip_file = GzipFile(None, mode='rb', fileobj=sio)
467
file_version_id = zip_file.readline()
468
return MultiParent.from_patch(zip_file.readlines())
472
def add_diff(self, diff, version_id, parent_ids):
473
outfile = open(self._filename + '.mpknit', 'ab')
475
start = outfile.tell()
477
zipfile = GzipFile(None, mode='ab', fileobj=outfile)
478
zipfile.writelines(itertools.chain(
479
['version %s\n' % version_id], diff.to_patch()))
485
self._diff_offset[version_id] = (start, end-start)
486
self._parents[version_id] = parent_ids
490
os.unlink(self._filename + '.mpknit')
492
if e.errno != errno.ENOENT:
495
os.unlink(self._filename + '.mpidx')
497
if e.errno != errno.ENOENT:
501
open(self._filename + '.mpidx', 'wb').write(bencode.bencode(
502
(self._parents, list(self._snapshots), self._diff_offset)))
505
self._parents, snapshots, self._diff_offset = bencode.bdecode(
506
open(self._filename + '.mpidx', 'rb').read())
507
self._snapshots = set(snapshots)
510
class _Reconstructor(object):
511
"""Build a text from the diffs, ancestry graph and cached lines"""
513
def __init__(self, diffs, lines, parents):
516
self.parents = parents
519
def reconstruct(self, lines, parent_text, version_id):
520
"""Append the lines referred to by a ParentText to lines"""
521
parent_id = self.parents[version_id][parent_text.parent]
522
end = parent_text.parent_pos + parent_text.num_lines
523
return self._reconstruct(lines, parent_id, parent_text.parent_pos,
526
def _reconstruct(self, lines, req_version_id, req_start, req_end):
527
"""Append lines for the requested version_id range"""
528
# stack of pending range requests
529
pending_reqs = [(req_version_id, req_start, req_end)]
530
while len(pending_reqs) > 0:
531
req_version_id, req_start, req_end = pending_reqs.pop()
532
# lazily allocate cursors for versions
534
start, end, kind, data, iterator = self.cursor[req_version_id]
536
iterator = self.diffs.get_diff(req_version_id).range_iterator()
537
start, end, kind, data = iterator.next()
538
if start > req_start:
539
iterator = self.diffs.get_diff(req_version_id).range_iterator()
540
start, end, kind, data = iterator.next()
542
# find the first hunk relevant to the request
543
while end <= req_start:
544
start, end, kind, data = iterator.next()
545
self.cursor[req_version_id] = start, end, kind, data, iterator
546
# if the hunk can't satisfy the whole request, split it in two,
547
# and leave the second half for later.
549
pending_reqs.append((req_version_id, end, req_end))
552
lines.extend(data[req_start - start: (req_end - start)])
554
# If the hunk is a ParentText, rewrite it as a range request
555
# for the parent, and make it the next pending request.
556
parent, parent_start, parent_end = data
557
new_version_id = self.parents[req_version_id][parent]
558
new_start = parent_start + req_start - start
559
new_end = parent_end + req_end - end
560
pending_reqs.append((new_version_id, new_start, new_end))
562
def reconstruct_version(self, lines, version_id):
563
length = self.diffs.get_diff(version_id).num_lines()
564
return self._reconstruct(lines, version_id, 0, length)
567
def gzip_string(lines):
569
data_file = GzipFile(None, mode='wb', fileobj=sio)
570
data_file.writelines(lines)
572
return sio.getvalue()