14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
from bzrlib.lazy_import import lazy_import
17
from __future__ import absolute_import
22
from .lazy_import import lazy_import
19
24
lazy_import(globals(), """
23
from StringIO import StringIO
31
from bzrlib import bencode
33
from bzrlib.tuned_gzip import GzipFile
36
41
def topo_iter_keys(vf, keys=None):
162
169
"""Contruct a fulltext from this diff and its parents"""
163
170
mpvf = MultiMemoryVersionedFile()
164
171
for num, parent in enumerate(parents):
165
mpvf.add_version(StringIO(parent).readlines(), num, [])
166
mpvf.add_diff(self, 'a', range(len(parents)))
172
mpvf.add_version(BytesIO(parent).readlines(), num, [])
173
mpvf.add_diff(self, 'a', list(range(len(parents))))
167
174
return mpvf.get_line_list(['a'])[0]
170
177
def from_texts(cls, text, parents=()):
171
178
"""Produce a MultiParent from a text and list of parent text"""
172
return cls.from_lines(StringIO(text).readlines(),
173
[StringIO(p).readlines() for p in parents])
179
return cls.from_lines(BytesIO(text).readlines(),
180
[BytesIO(p).readlines() for p in parents])
175
182
def to_patch(self):
176
183
"""Yield text lines for a patch"""
188
195
def from_patch(cls, text):
189
196
"""Create a MultiParent from its string form"""
190
return cls._from_patch(StringIO(text))
197
return cls._from_patch(BytesIO(text))
193
200
def _from_patch(lines):
195
202
line_iter = iter(lines)
200
cur_line = line_iter.next()
207
cur_line = next(line_iter)
201
208
except StopIteration:
203
if cur_line[0] == 'i':
204
num_lines = int(cur_line.split(' ')[1])
205
hunk_lines = [line_iter.next() for x in xrange(num_lines)]
210
first_char = cur_line[0:1]
211
if first_char == b'i':
212
num_lines = int(cur_line.split(b' ')[1])
213
hunk_lines = [next(line_iter) for _ in range(num_lines)]
206
214
hunk_lines[-1] = hunk_lines[-1][:-1]
207
215
hunks.append(NewText(hunk_lines))
208
elif cur_line[0] == '\n':
209
hunks[-1].lines[-1] += '\n'
216
elif first_char == b'\n':
217
hunks[-1].lines[-1] += b'\n'
211
if not (cur_line[0] == 'c'):
212
raise AssertionError(cur_line[0])
219
if not (first_char == b'c'):
220
raise AssertionError(first_char)
213
221
parent, parent_pos, child_pos, num_lines =\
214
[int(v) for v in cur_line.split(' ')[1:]]
222
[int(v) for v in cur_line.split(b' ')[1:]]
215
223
hunks.append(ParentText(parent, parent_pos, child_pos,
217
225
return MultiParent(hunks)
270
280
return 'NewText(%r)' % self.lines
272
282
def to_patch(self):
273
yield 'i %d\n' % len(self.lines)
283
yield b'i %d\n' % len(self.lines)
274
284
for line in self.lines:
279
289
class ParentText(object):
280
290
"""A reference to text present in a parent text"""
292
__slots__ = ['parent', 'parent_pos', 'child_pos', 'num_lines']
282
294
def __init__(self, parent, parent_pos, child_pos, num_lines):
283
295
self.parent = parent
284
296
self.parent_pos = parent_pos
285
297
self.child_pos = child_pos
286
298
self.num_lines = num_lines
301
return {b'parent': self.parent,
302
b'parent_pos': self.parent_pos,
303
b'child_pos': self.child_pos,
304
b'num_lines': self.num_lines}
288
306
def __repr__(self):
289
return 'ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'\
290
' %(num_lines)r)' % self.__dict__
307
return ('ParentText(%(parent)r, %(parent_pos)r, %(child_pos)r,'
308
' %(num_lines)r)' % self._as_dict())
292
310
def __eq__(self, other):
293
311
if self.__class__ is not other.__class__:
295
return (self.__dict__ == other.__dict__)
313
return self._as_dict() == other._as_dict()
297
315
def to_patch(self):
298
yield 'c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'\
316
yield (b'c %(parent)d %(parent_pos)d %(child_pos)d %(num_lines)d\n'
302
320
class BaseVersionedFile(object):
388
406
raise ValueError()
389
407
revisions = set(vf.versions())
390
408
total = len(revisions)
391
pb = ui.ui_factory.nested_progress_bar()
409
with ui.ui_factory.nested_progress_bar() as pb:
393
410
while len(revisions) > 0:
395
412
for revision in revisions:
396
413
parents = vf.get_parents(revision)
397
414
if [p for p in parents if p not in self._parents] != []:
399
lines = [a + ' ' + l for a, l in
416
lines = [a + b' ' + l for a, l in
400
417
vf.annotate(revision)]
401
418
if snapshots is None:
402
419
force_snapshot = None
412
429
if not (lines == self.get_line_list([revision])[0]):
413
430
raise AssertionError()
414
431
self.clear_cache()
415
pb.update('Importing revisions',
432
pb.update(gettext('Importing revisions'),
416
433
(total - len(revisions)) + len(added), total)
417
434
revisions = [r for r in revisions if r not in added]
421
436
def select_snapshots(self, vf):
422
437
"""Determine which versions to add as snapshots"""
546
561
def get_diff(self, version_id):
547
562
start, count = self._diff_offset[version_id]
548
infile = open(self._filename + '.mpknit', 'rb')
563
with open(self._filename + '.mpknit', 'rb') as infile:
550
564
infile.seek(start)
551
sio = StringIO(infile.read(count))
554
zip_file = GzipFile(None, mode='rb', fileobj=sio)
565
sio = BytesIO(infile.read(count))
566
with gzip.GzipFile(None, mode='rb', fileobj=sio) as zip_file:
556
567
file_version_id = zip_file.readline()
557
return MultiParent.from_patch(zip_file.read())
568
content = zip_file.read()
569
return MultiParent.from_patch(content)
561
571
def add_diff(self, diff, version_id, parent_ids):
562
outfile = open(self._filename + '.mpknit', 'ab')
572
with open(self._filename + '.mpknit', 'ab') as outfile:
564
573
outfile.seek(0, 2) # workaround for windows bug:
565
574
# .tell() for files opened in 'ab' mode
566
575
# before any write returns 0
567
576
start = outfile.tell()
569
zipfile = GzipFile(None, mode='ab', fileobj=outfile)
577
with gzip.GzipFile(None, mode='ab', fileobj=outfile) as zipfile:
570
578
zipfile.writelines(itertools.chain(
571
['version %s\n' % version_id], diff.to_patch()))
579
[b'version %s\n' % version_id], diff.to_patch()))
574
580
end = outfile.tell()
577
581
self._diff_offset[version_id] = (start, end-start)
578
582
self._parents[version_id] = parent_ids
580
584
def destroy(self):
582
586
os.unlink(self._filename + '.mpknit')
584
588
if e.errno != errno.ENOENT:
587
591
os.unlink(self._filename + '.mpidx')
589
593
if e.errno != errno.ENOENT:
631
635
start, end, kind, data, iterator = self.cursor[req_version_id]
633
637
iterator = self.diffs.get_diff(req_version_id).range_iterator()
634
start, end, kind, data = iterator.next()
638
start, end, kind, data = next(iterator)
635
639
if start > req_start:
636
640
iterator = self.diffs.get_diff(req_version_id).range_iterator()
637
start, end, kind, data = iterator.next()
641
start, end, kind, data = next(iterator)
639
643
# find the first hunk relevant to the request
640
644
while end <= req_start:
641
start, end, kind, data = iterator.next()
645
start, end, kind, data = next(iterator)
642
646
self.cursor[req_version_id] = start, end, kind, data, iterator
643
647
# if the hunk can't satisfy the whole request, split it in two,
644
648
# and leave the second half for later.
664
668
def gzip_string(lines):
666
data_file = GzipFile(None, mode='wb', fileobj=sio)
667
data_file.writelines(lines)
670
with gzip.GzipFile(None, mode='wb', fileobj=sio) as data_file:
671
data_file.writelines(lines)
669
672
return sio.getvalue()