1
# Copyright (C) 2005-2010 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
"""Read in a bundle stream, and process it into a BundleReader object."""
19
from __future__ import absolute_import
30
from . import apply_bundle
31
from ..errors import (
35
from ..inventory import (
41
from ..osutils import sha_string, pathjoin
42
from ..revision import Revision, NULL_REVISION
43
from ..sixish import (
47
from ..testament import StrictTestament
48
from ..trace import mutter, warning
49
from ..tree import Tree
50
from ..xml5 import serializer_v5
53
class RevisionInfo(object):
54
"""Gets filled out for each revision object that is read.
56
def __init__(self, revision_id):
57
self.revision_id = revision_id
63
self.inventory_sha1 = None
65
self.parent_ids = None
68
self.properties = None
69
self.tree_actions = None
72
return pprint.pformat(self.__dict__)
74
def as_revision(self):
75
rev = Revision(revision_id=self.revision_id,
76
committer=self.committer,
77
timestamp=float(self.timestamp),
78
timezone=int(self.timezone),
79
inventory_sha1=self.inventory_sha1,
80
message='\n'.join(self.message))
83
rev.parent_ids.extend(self.parent_ids)
86
for property in self.properties:
87
key_end = property.find(': ')
89
if not property.endswith(':'):
90
raise ValueError(property)
91
key = str(property[:-1])
94
key = str(property[:key_end])
95
value = property[key_end+2:]
96
rev.properties[key] = value
101
def from_revision(revision):
102
revision_info = RevisionInfo(revision.revision_id)
103
date = timestamp.format_highres_date(revision.timestamp,
105
revision_info.date = date
106
revision_info.timezone = revision.timezone
107
revision_info.timestamp = revision.timestamp
108
revision_info.message = revision.message.split('\n')
109
revision_info.properties = [': '.join(p) for p in
110
viewitems(revision.properties)]
114
class BundleInfo(object):
115
"""This contains the meta information. Stuff that allows you to
116
recreate the revision or inventory XML.
118
def __init__(self, bundle_format=None):
119
self.bundle_format = None
120
self.committer = None
124
# A list of RevisionInfo objects
127
# The next entries are created during complete_info() and
128
# other post-read functions.
130
# A list of real Revision objects
131
self.real_revisions = []
133
self.timestamp = None
136
# Have we checked the repository yet?
137
self._validated_revisions_against_repo = False
140
return pprint.pformat(self.__dict__)
142
def complete_info(self):
143
"""This makes sure that all information is properly
144
split up, based on the assumptions that can be made
145
when information is missing.
147
from breezy.timestamp import unpack_highres_date
148
# Put in all of the guessable information.
149
if not self.timestamp and self.date:
150
self.timestamp, self.timezone = unpack_highres_date(self.date)
152
self.real_revisions = []
153
for rev in self.revisions:
154
if rev.timestamp is None:
155
if rev.date is not None:
156
rev.timestamp, rev.timezone = \
157
unpack_highres_date(rev.date)
159
rev.timestamp = self.timestamp
160
rev.timezone = self.timezone
161
if rev.message is None and self.message:
162
rev.message = self.message
163
if rev.committer is None and self.committer:
164
rev.committer = self.committer
165
self.real_revisions.append(rev.as_revision())
167
def get_base(self, revision):
168
revision_info = self.get_revision_info(revision.revision_id)
169
if revision_info.base_id is not None:
170
return revision_info.base_id
171
if len(revision.parent_ids) == 0:
172
# There is no base listed, and
173
# the lowest revision doesn't have a parent
174
# so this is probably against the empty tree
175
# and thus base truly is NULL_REVISION
178
return revision.parent_ids[-1]
180
def _get_target(self):
181
"""Return the target revision."""
182
if len(self.real_revisions) > 0:
183
return self.real_revisions[0].revision_id
184
elif len(self.revisions) > 0:
185
return self.revisions[0].revision_id
188
target = property(_get_target, doc='The target revision id')
190
def get_revision(self, revision_id):
191
for r in self.real_revisions:
192
if r.revision_id == revision_id:
194
raise KeyError(revision_id)
196
def get_revision_info(self, revision_id):
197
for r in self.revisions:
198
if r.revision_id == revision_id:
200
raise KeyError(revision_id)
202
def revision_tree(self, repository, revision_id, base=None):
203
revision = self.get_revision(revision_id)
204
base = self.get_base(revision)
205
if base == revision_id:
206
raise AssertionError()
207
if not self._validated_revisions_against_repo:
208
self._validate_references_from_repository(repository)
209
revision_info = self.get_revision_info(revision_id)
210
inventory_revision_id = revision_id
211
bundle_tree = BundleTree(repository.revision_tree(base),
212
inventory_revision_id)
213
self._update_tree(bundle_tree, revision_id)
215
inv = bundle_tree.inventory
216
self._validate_inventory(inv, revision_id)
217
self._validate_revision(bundle_tree, revision_id)
221
def _validate_references_from_repository(self, repository):
222
"""Now that we have a repository which should have some of the
223
revisions we care about, go through and validate all of them
228
def add_sha(d, revision_id, sha1):
229
if revision_id is None:
231
raise BzrError('A Null revision should always'
232
'have a null sha1 hash')
235
# This really should have been validated as part
236
# of _validate_revisions but lets do it again
237
if sha1 != d[revision_id]:
238
raise BzrError('** Revision %r referenced with 2 different'
239
' sha hashes %s != %s' % (revision_id,
240
sha1, d[revision_id]))
242
d[revision_id] = sha1
244
# All of the contained revisions were checked
245
# in _validate_revisions
247
for rev_info in self.revisions:
248
checked[rev_info.revision_id] = True
249
add_sha(rev_to_sha, rev_info.revision_id, rev_info.sha1)
251
for (rev, rev_info) in zip(self.real_revisions, self.revisions):
252
add_sha(inv_to_sha, rev_info.revision_id, rev_info.inventory_sha1)
256
for revision_id, sha1 in viewitems(rev_to_sha):
257
if repository.has_revision(revision_id):
258
testament = StrictTestament.from_revision(repository,
260
local_sha1 = self._testament_sha1_from_revision(repository,
262
if sha1 != local_sha1:
263
raise BzrError('sha1 mismatch. For revision id {%s}'
264
'local: %s, bundle: %s' % (revision_id, local_sha1, sha1))
267
elif revision_id not in checked:
268
missing[revision_id] = sha1
271
# I don't know if this is an error yet
272
warning('Not all revision hashes could be validated.'
273
' Unable validate %d hashes' % len(missing))
274
mutter('Verified %d sha hashes for the bundle.' % count)
275
self._validated_revisions_against_repo = True
277
def _validate_inventory(self, inv, revision_id):
278
"""At this point we should have generated the BundleTree,
279
so build up an inventory, and make sure the hashes match.
281
# Now we should have a complete inventory entry.
282
s = serializer_v5.write_inventory_to_string(inv)
284
# Target revision is the last entry in the real_revisions list
285
rev = self.get_revision(revision_id)
286
if rev.revision_id != revision_id:
287
raise AssertionError()
288
if sha1 != rev.inventory_sha1:
289
f = open(',,bogus-inv', 'wb')
294
warning('Inventory sha hash mismatch for revision %s. %s'
295
' != %s' % (revision_id, sha1, rev.inventory_sha1))
297
def _validate_revision(self, tree, revision_id):
298
"""Make sure all revision entries match their checksum."""
300
# This is a mapping from each revision id to its sha hash
303
rev = self.get_revision(revision_id)
304
rev_info = self.get_revision_info(revision_id)
305
if not (rev.revision_id == rev_info.revision_id):
306
raise AssertionError()
307
if not (rev.revision_id == revision_id):
308
raise AssertionError()
309
sha1 = self._testament_sha1(rev, tree)
310
if sha1 != rev_info.sha1:
311
raise TestamentMismatch(rev.revision_id, rev_info.sha1, sha1)
312
if rev.revision_id in rev_to_sha1:
313
raise BzrError('Revision {%s} given twice in the list'
315
rev_to_sha1[rev.revision_id] = sha1
317
def _update_tree(self, bundle_tree, revision_id):
318
"""This fills out a BundleTree based on the information
321
:param bundle_tree: A BundleTree to update with the new information.
324
def get_rev_id(last_changed, path, kind):
325
if last_changed is not None:
326
# last_changed will be a Unicode string because of how it was
327
# read. Convert it back to utf8.
328
changed_revision_id = cache_utf8.encode(last_changed)
330
changed_revision_id = revision_id
331
bundle_tree.note_last_changed(path, changed_revision_id)
332
return changed_revision_id
334
def extra_info(info, new_path):
337
for info_item in info:
339
name, value = info_item.split(':', 1)
341
raise ValueError('Value %r has no colon' % info_item)
342
if name == 'last-changed':
344
elif name == 'executable':
345
val = (value == 'yes')
346
bundle_tree.note_executable(new_path, val)
347
elif name == 'target':
348
bundle_tree.note_target(new_path, value)
349
elif name == 'encoding':
351
return last_changed, encoding
353
def do_patch(path, lines, encoding):
354
if encoding == 'base64':
355
patch = base64.decodestring(''.join(lines))
356
elif encoding is None:
357
patch = ''.join(lines)
359
raise ValueError(encoding)
360
bundle_tree.note_patch(path, patch)
362
def renamed(kind, extra, lines):
363
info = extra.split(' // ')
365
raise BzrError('renamed action lines need both a from and to'
368
if info[1].startswith('=> '):
369
new_path = info[1][3:]
373
bundle_tree.note_rename(old_path, new_path)
374
last_modified, encoding = extra_info(info[2:], new_path)
375
revision = get_rev_id(last_modified, new_path, kind)
377
do_patch(new_path, lines, encoding)
379
def removed(kind, extra, lines):
380
info = extra.split(' // ')
382
# TODO: in the future we might allow file ids to be
383
# given for removed entries
384
raise BzrError('removed action lines should only have the path'
387
bundle_tree.note_deletion(path)
389
def added(kind, extra, lines):
390
info = extra.split(' // ')
392
raise BzrError('add action lines require the path and file id'
395
raise BzrError('add action lines have fewer than 5 entries.'
398
if not info[1].startswith('file-id:'):
399
raise BzrError('The file-id should follow the path for an add'
401
# This will be Unicode because of how the stream is read. Turn it
402
# back into a utf8 file_id
403
file_id = cache_utf8.encode(info[1][8:])
405
bundle_tree.note_id(file_id, path, kind)
406
# this will be overridden in extra_info if executable is specified.
407
bundle_tree.note_executable(path, False)
408
last_changed, encoding = extra_info(info[2:], path)
409
revision = get_rev_id(last_changed, path, kind)
410
if kind == 'directory':
412
do_patch(path, lines, encoding)
414
def modified(kind, extra, lines):
415
info = extra.split(' // ')
417
raise BzrError('modified action lines have at least'
418
'the path in them: %r' % extra)
421
last_modified, encoding = extra_info(info[1:], path)
422
revision = get_rev_id(last_modified, path, kind)
424
do_patch(path, lines, encoding)
432
for action_line, lines in \
433
self.get_revision_info(revision_id).tree_actions:
434
first = action_line.find(' ')
436
raise BzrError('Bogus action line'
437
' (no opening space): %r' % action_line)
438
second = action_line.find(' ', first+1)
440
raise BzrError('Bogus action line'
441
' (missing second space): %r' % action_line)
442
action = action_line[:first]
443
kind = action_line[first+1:second]
444
if kind not in ('file', 'directory', 'symlink'):
445
raise BzrError('Bogus action line'
446
' (invalid object kind %r): %r' % (kind, action_line))
447
extra = action_line[second+1:]
449
if action not in valid_actions:
450
raise BzrError('Bogus action line'
451
' (unrecognized action): %r' % action_line)
452
valid_actions[action](kind, extra, lines)
454
def install_revisions(self, target_repo, stream_input=True):
455
"""Install revisions and return the target revision
457
:param target_repo: The repository to install into
458
:param stream_input: Ignored by this implementation.
460
apply_bundle.install_bundle(target_repo, self)
463
def get_merge_request(self, target_repo):
464
"""Provide data for performing a merge
466
Returns suggested base, suggested target, and patch verification status
468
return None, self.target, 'inapplicable'
471
class BundleTree(Tree):
473
def __init__(self, base_tree, revision_id):
474
self.base_tree = base_tree
475
self._renamed = {} # Mapping from old_path => new_path
476
self._renamed_r = {} # new_path => old_path
477
self._new_id = {} # new_path => new_id
478
self._new_id_r = {} # new_id => new_path
479
self._kinds = {} # new_id => kind
480
self._last_changed = {} # new_id => revision_id
481
self._executable = {} # new_id => executable value
483
self._targets = {} # new path => new symlink target
485
self.contents_by_id = True
486
self.revision_id = revision_id
487
self._inventory = None
490
return pprint.pformat(self.__dict__)
492
def note_rename(self, old_path, new_path):
493
"""A file/directory has been renamed from old_path => new_path"""
494
if new_path in self._renamed:
495
raise AssertionError(new_path)
496
if old_path in self._renamed_r:
497
raise AssertionError(old_path)
498
self._renamed[new_path] = old_path
499
self._renamed_r[old_path] = new_path
501
def note_id(self, new_id, new_path, kind='file'):
502
"""Files that don't exist in base need a new id."""
503
self._new_id[new_path] = new_id
504
self._new_id_r[new_id] = new_path
505
self._kinds[new_id] = kind
507
def note_last_changed(self, file_id, revision_id):
508
if (file_id in self._last_changed
509
and self._last_changed[file_id] != revision_id):
510
raise BzrError('Mismatched last-changed revision for file_id {%s}'
511
': %s != %s' % (file_id,
512
self._last_changed[file_id],
514
self._last_changed[file_id] = revision_id
516
def note_patch(self, new_path, patch):
517
"""There is a patch for a given filename."""
518
self.patches[new_path] = patch
520
def note_target(self, new_path, target):
521
"""The symlink at the new path has the given target"""
522
self._targets[new_path] = target
524
def note_deletion(self, old_path):
525
"""The file at old_path has been deleted."""
526
self.deleted.append(old_path)
528
def note_executable(self, new_path, executable):
529
self._executable[new_path] = executable
531
def old_path(self, new_path):
532
"""Get the old_path (path in the base_tree) for the file at new_path"""
533
if new_path[:1] in ('\\', '/'):
534
raise ValueError(new_path)
535
old_path = self._renamed.get(new_path)
536
if old_path is not None:
538
dirname,basename = os.path.split(new_path)
539
# dirname is not '' doesn't work, because
540
# dirname may be a unicode entry, and is
541
# requires the objects to be identical
543
old_dir = self.old_path(dirname)
547
old_path = pathjoin(old_dir, basename)
550
#If the new path wasn't in renamed, the old one shouldn't be in
552
if old_path in self._renamed_r:
556
def new_path(self, old_path):
557
"""Get the new_path (path in the target_tree) for the file at old_path
560
if old_path[:1] in ('\\', '/'):
561
raise ValueError(old_path)
562
new_path = self._renamed_r.get(old_path)
563
if new_path is not None:
565
if new_path in self._renamed:
567
dirname,basename = os.path.split(old_path)
569
new_dir = self.new_path(dirname)
573
new_path = pathjoin(new_dir, basename)
576
#If the old path wasn't in renamed, the new one shouldn't be in
578
if new_path in self._renamed:
582
def get_root_id(self):
583
return self.path2id('')
585
def path2id(self, path):
586
"""Return the id of the file present at path in the target tree."""
587
file_id = self._new_id.get(path)
588
if file_id is not None:
590
old_path = self.old_path(path)
593
if old_path in self.deleted:
595
return self.base_tree.path2id(old_path)
597
def id2path(self, file_id):
598
"""Return the new path in the target tree of the file with id file_id"""
599
path = self._new_id_r.get(file_id)
602
old_path = self.base_tree.id2path(file_id)
605
if old_path in self.deleted:
607
return self.new_path(old_path)
609
def old_contents_id(self, file_id):
610
"""Return the id in the base_tree for the given file_id.
611
Return None if the file did not exist in base.
613
if self.contents_by_id:
614
if self.base_tree.has_id(file_id):
618
new_path = self.id2path(file_id)
619
return self.base_tree.path2id(new_path)
621
def get_file(self, file_id):
622
"""Return a file-like object containing the new contents of the
623
file given by file_id.
625
TODO: It might be nice if this actually generated an entry
626
in the text-store, so that the file contents would
629
base_id = self.old_contents_id(file_id)
630
if (base_id is not None and
631
base_id != self.base_tree.get_root_id()):
632
patch_original = self.base_tree.get_file(base_id)
634
patch_original = None
635
file_patch = self.patches.get(self.id2path(file_id))
636
if file_patch is None:
637
if (patch_original is None and
638
self.kind(file_id) == 'directory'):
640
if patch_original is None:
641
raise AssertionError("None: %s" % file_id)
642
return patch_original
644
if file_patch.startswith('\\'):
646
'Malformed patch for %s, %r' % (file_id, file_patch))
647
return patched_file(file_patch, patch_original)
649
def get_symlink_target(self, file_id, path=None):
651
path = self.id2path(file_id)
653
return self._targets[path]
655
return self.base_tree.get_symlink_target(file_id)
657
def kind(self, file_id):
658
if file_id in self._kinds:
659
return self._kinds[file_id]
660
return self.base_tree.kind(file_id)
662
def get_file_revision(self, file_id):
663
path = self.id2path(file_id)
664
if path in self._last_changed:
665
return self._last_changed[path]
667
return self.base_tree.get_file_revision(file_id)
669
def is_executable(self, file_id):
670
path = self.id2path(file_id)
671
if path in self._executable:
672
return self._executable[path]
674
return self.base_tree.is_executable(file_id)
676
def get_last_changed(self, file_id):
677
path = self.id2path(file_id)
678
if path in self._last_changed:
679
return self._last_changed[path]
680
return self.base_tree.get_file_revision(file_id)
682
def get_size_and_sha1(self, file_id):
683
"""Return the size and sha1 hash of the given file id.
684
If the file was not locally modified, this is extracted
685
from the base_tree. Rather than re-reading the file.
687
new_path = self.id2path(file_id)
690
if new_path not in self.patches:
691
# If the entry does not have a patch, then the
692
# contents must be the same as in the base_tree
693
text_size = self.base_tree.get_file_size(file_id)
694
text_sha1 = self.base_tree.get_file_sha1(file_id)
695
return text_size, text_sha1
696
fileobj = self.get_file(file_id)
697
content = fileobj.read()
698
return len(content), sha_string(content)
700
def _get_inventory(self):
701
"""Build up the inventory entry for the BundleTree.
703
This need to be called before ever accessing self.inventory
705
from os.path import dirname, basename
706
inv = Inventory(None, self.revision_id)
708
def add_entry(file_id):
709
path = self.id2path(file_id)
715
parent_path = dirname(path)
716
parent_id = self.path2id(parent_path)
718
kind = self.kind(file_id)
719
revision_id = self.get_last_changed(file_id)
721
name = basename(path)
722
if kind == 'directory':
723
ie = InventoryDirectory(file_id, name, parent_id)
725
ie = InventoryFile(file_id, name, parent_id)
726
ie.executable = self.is_executable(file_id)
727
elif kind == 'symlink':
728
ie = InventoryLink(file_id, name, parent_id)
729
ie.symlink_target = self.get_symlink_target(file_id, path)
730
ie.revision = revision_id
733
ie.text_size, ie.text_sha1 = self.get_size_and_sha1(file_id)
734
if ie.text_size is None:
736
'Got a text_size of None for file_id %r' % file_id)
739
sorted_entries = self.sorted_path_id()
740
for path, file_id in sorted_entries:
745
# Have to overload the inherited inventory property
746
# because _get_inventory is only called in the parent.
747
# Reading the docs, property() objects do not use
748
# overloading, they use the function as it was defined
750
inventory = property(_get_inventory)
752
root_inventory = property(_get_inventory)
754
def all_file_ids(self):
755
return {entry.file_id for path, entry in self.inventory.iter_entries()}
757
def list_files(self, include_root=False, from_dir=None, recursive=True):
758
# The only files returned by this are those from the version
763
from_dir_id = inv.path2id(from_dir)
764
if from_dir_id is None:
765
# Directory not versioned
767
entries = inv.iter_entries(from_dir=from_dir_id, recursive=recursive)
768
if inv.root is not None and not include_root and from_dir is None:
769
# skip the root for compatability with the current apis.
771
for path, entry in entries:
772
yield path, 'V', entry.kind, entry.file_id, entry
774
def sorted_path_id(self):
776
for result in viewitems(self._new_id):
778
for id in self.base_tree.all_file_ids():
779
path = self.id2path(id)
782
paths.append((path, id))
787
def patched_file(file_patch, original):
788
"""Produce a file-like object with the patched version of a text"""
789
from breezy.patches import iter_patched
790
from breezy.iterablefile import IterableFile
792
return IterableFile(())
793
# string.splitlines(True) also splits on '\r', but the iter_patched code
794
# only expects to iterate over '\n' style lines
795
return IterableFile(iter_patched(original,
796
BytesIO(file_patch).readlines()))