-
Notifications
You must be signed in to change notification settings - Fork 1
/
fetch.py
1778 lines (1546 loc) · 67.3 KB
/
fetch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2005-2009 Jelmer Vernooij <jelmer@samba.org>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""Fetching revisions from Subversion repositories in batches.
Everywhere in this file 'bzr_base_ie' refers to the entry with the
same file_id in the old revision (left hand side parent revision).
'svn_base_ie' refers to the inventory entry from the svn revision
that the copy happened.
'new_ie' refers to the inventory entry that is newly created, as part
of the inventory delta.
"""
from __future__ import absolute_import
from collections import defaultdict, deque
import subvertpy
from subvertpy import (
ERR_FS_NOT_DIRECTORY,
NODE_FILE,
SubversionException,
properties,
)
from subvertpy.delta import (
apply_txdelta_handler_chunks,
)
from breezy import (
debug,
delta,
lru_cache,
osutils,
trace,
ui,
urlutils,
)
from breezy.errors import (
NoSuchId,
NoSuchRevision,
)
from breezy.bzr.inventory import (
InventoryDirectory,
InventoryFile,
InventoryLink,
)
from breezy.revision import (
NULL_REVISION,
)
from six import (
text_type,
)
from breezy.bzr.inventorytree import InventoryRevisionTree
from breezy.repository import (
InterRepository,
)
from breezy.bzr.versionedfile import (
ChunkedContentFactory,
FulltextContentFactory,
)
from . import changes
from .errors import (
AbsentPath,
InvalidFileName,
SymlinkTargetContainsNewline,
TextChecksumMismatch,
convert_svn_error,
)
from .fileids import (
get_local_changes,
)
from .mapping import (
SVN_PROP_BZR_PREFIX,
)
from .repository import (
SvnRepository,
SvnRepositoryFormat,
)
from .transport import (
url_join_unescaped_path,
)
# Max size of group in which revids are checked when looking for missing
# revisions
MAX_CHECK_PRESENT_INTERVAL = 1000
# Size of the text cache to keep
TEXT_CACHE_SIZE = 1024 * 1024 * 50
def has_id(tree, file_id):
try:
tree.id2path(file_id)
except NoSuchId:
return False
else:
return True
def tree_parent_id_basename_to_file_id(tree, parent_id, basename):
if parent_id is None and basename == "":
return tree.path2id('')
inv = tree.root_inventory
parent_id_basename_index = getattr(
inv, "parent_id_basename_to_file_id", None)
if parent_id_basename_index is None:
return inv[parent_id].children[basename].file_id
else:
ret = parent_id_basename_index.items(
[(parent_id or '', basename.encode("utf-8"))])
try:
return next(ret)[1]
except IndexError:
raise KeyError((parent_id, basename))
def tree_ancestors(tree, fileid, exceptions):
"""Find all ancestors of a particular file id in a tree.
:param tree: Tree
:param fileid: File id
:param exceptions: Sequence of paths to not report on
:return: Sequence of paths
"""
todo = set([fileid])
while todo:
fileid = todo.pop()
for ie in tree.root_inventory.get_entry(fileid).children.values():
p = tree.id2path(ie.file_id)
if p in exceptions:
continue
yield p
if ie.kind == "directory":
todo.add(ie.file_id)
def md5_strings(chunks):
"""Return the MD5sum of a list of chunks.
:param chunks: Chunks as strings
:return: String with MD5 hex digest
"""
s = osutils.md5()
map(s.update, chunks)
return s.hexdigest()
def md5_string(string):
"""Return the MD5sum of a string.
:param string: String to calculate the MD5sum of.
:return: MD5sums hex digest
"""
s = osutils.md5()
s.update(string)
return s.hexdigest()
def check_filename(path):
"""Check that a path does not contain invalid characters.
:param path: Path to check
:raises InvalidFileName:
"""
if not isinstance(path, text_type):
raise TypeError(path)
if u"\\" in path:
raise InvalidFileName(path)
def editor_strip_prefix(editor, path):
"""Wrap editor and strip base path from paths.
:param editor: Editor to wrap
:param path: Base path to strip
"""
if path == "":
return editor
return PathStrippingEditor(editor, path)
class PathStrippingDirectoryEditor(object):
"""Directory editor that strips a base from the paths."""
__slots__ = ('editor', 'path', 'actual')
def __init__(self, editor, path, actual=None):
self.editor = editor
self.path = path
self.actual = actual
def open_directory(self, path, base_revnum):
"""See ``DirectoryEditor``."""
if path.strip("/") == self.editor.prefix:
t = self.editor.actual.open_root(base_revnum)
elif self.actual is not None:
t = self.actual.open_directory(
self.editor.strip_prefix(path), base_revnum)
else:
t = None
return PathStrippingDirectoryEditor(self.editor, path, t)
def add_directory(self, path, copyfrom_path=None, copyfrom_rev=-1):
"""See ``DirectoryEditor``."""
if path.strip("/") == self.editor.prefix:
t = self.editor.actual.open_root(copyfrom_rev)
elif self.actual is not None:
t = self.actual.add_directory(
self.editor.strip_prefix(path),
self.editor.strip_copy_prefix(copyfrom_path), copyfrom_rev)
else:
t = None
return PathStrippingDirectoryEditor(self.editor, path, t)
def close(self):
"""See ``DirectoryEditor``."""
if self.actual is not None:
self.actual.close()
def change_prop(self, name, value):
"""See ``DirectoryEditor``."""
if self.actual is not None:
self.actual.change_prop(name, value)
def delete_entry(self, path, revnum):
"""See ``DirectoryEditor``."""
if self.actual is not None:
self.actual.delete_entry(self.editor.strip_prefix(path), revnum)
else:
raise AssertionError("delete_entry should not be called")
def add_file(self, path, copyfrom_path=None, copyfrom_rev=-1):
"""See ``DirectoryEditor``."""
if self.actual is not None:
return self.actual.add_file(
self.editor.strip_prefix(path),
self.editor.strip_copy_prefix(copyfrom_path), copyfrom_rev)
raise AssertionError("add_file should not be called")
def open_file(self, path, base_revnum):
"""See ``DirectoryEditor``."""
if self.actual is not None:
return self.actual.open_file(
self.editor.strip_prefix(path), base_revnum)
raise AssertionError("open_file should not be called")
class PathStrippingEditor(object):
"""Editor that strips a base from the paths."""
__slots__ = ('actual', 'prefix')
def __init__(self, actual, path):
self.actual = actual
self.prefix = path.strip("/")
def __getattr__(self, name):
try:
return getattr(super(PathStrippingEditor, self), name)
except AttributeError:
return getattr(self.actual, name)
def strip_prefix(self, path):
path = path.strip("/")
if not path.startswith(self.prefix):
raise AssertionError("Invalid path %r doesn't start with %r" % (
path, self.prefix))
return path[len(self.prefix):].strip("/")
def strip_copy_prefix(self, path):
if path is None:
return None
return self.strip_prefix(path)
def open_root(self, base_revnum=None):
return PathStrippingDirectoryEditor(self, "")
def close(self):
self.actual.close()
def abort(self):
self.actual.abort()
def set_target_revision(self, rev):
self.actual.set_target_revision(rev)
class DeltaBuildEditor(object):
"""Implementation of the Subversion commit editor interface that
converts Subversion to Bazaar semantics.
"""
__slots__ = ('revmeta', '_id_map', 'mapping')
def __init__(self, revmeta, mapping):
self.revmeta = revmeta
self._id_map = None
self.mapping = mapping
def set_target_revision(self, revnum):
if self.revmeta.metarev.revnum != revnum:
raise AssertionError("Expected %d, got %d" % (
self.revmeta.metarev.revnum, revnum))
def open_root(self, base_revnum=None):
return self._open_root(base_revnum)
def close(self):
pass
def abort(self):
pass
class DirectoryBuildEditor(object):
__slots__ = ('editor', 'path')
def __init__(self, editor, path):
self.editor = editor
self.path = path
def close(self):
if self.path == "":
# If it has changed, it has definitely been reported by now
if not self.editor.revmeta.knows_fileprops():
self.editor.revmeta._fileprops = \
self.editor.revmeta.get_previous_fileprops()
self._close()
def add_directory(self, path, copyfrom_path=None, copyfrom_revnum=-1):
if isinstance(path, bytes):
path = path.decode("utf-8")
check_filename(path)
return self._add_directory(path, copyfrom_path, copyfrom_revnum)
def open_directory(self, path, base_revnum):
if isinstance(path, bytes):
path = path.decode("utf-8")
return self._open_directory(path, base_revnum)
def absent_directory(self, path):
raise AbsentPath(path)
def absent_file(self, path):
raise AbsentPath(path)
def change_prop(self, name, value):
if self.path == "":
# Replay lazy_dict, since it may be more expensive
if not self.editor.revmeta.knows_fileprops():
self.editor.revmeta._fileprops = dict(
self.editor.revmeta.get_previous_fileprops())
if value is None:
if name in self.editor.revmeta._fileprops:
del self.editor.revmeta._fileprops[name]
else:
self.editor.revmeta._fileprops[name] = value
if name in (properties.PROP_ENTRY_COMMITTED_DATE,
properties.PROP_ENTRY_COMMITTED_REV,
properties.PROP_ENTRY_LAST_AUTHOR,
properties.PROP_ENTRY_LOCK_TOKEN,
properties.PROP_ENTRY_UUID,
properties.PROP_EXECUTABLE):
pass
elif (name.startswith(properties.PROP_WC_PREFIX)):
pass
elif name.startswith(properties.PROP_PREFIX):
trace.mutter('unsupported dir property %r', name)
def add_file(self, path, copyfrom_path=None, copyfrom_revnum=-1):
if isinstance(path, bytes):
path = path.decode("utf-8")
check_filename(path)
return self._add_file(path, copyfrom_path, copyfrom_revnum)
def open_file(self, path, base_revnum):
if isinstance(path, bytes):
path = path.decode("utf-8")
return self._open_file(path, base_revnum)
def delete_entry(self, path, revnum):
if isinstance(path, bytes):
path = path.decode("utf-8")
return self._delete_entry(path, revnum)
class FileBuildEditor(object):
__slots__ = ('path', 'editor', 'is_executable', 'is_special',
'last_file_rev')
def __init__(self, editor, path):
self.path = path
self.editor = editor
self.is_executable = None
self.is_special = None
def apply_textdelta(self, base_checksum=None):
return self._apply_textdelta(base_checksum)
def change_prop(self, name, value):
if name == properties.PROP_EXECUTABLE:
# You'd expect executable to match
# properties.PROP_EXECUTABLE_VALUE, but that's not
# how SVN behaves. It appears to consider the presence
# of the property sufficient to mark it executable.
self.is_executable = (value is not None)
elif name == properties.PROP_SPECIAL:
self.is_special = (value is not None)
elif name == properties.PROP_ENTRY_COMMITTED_REV:
self.last_file_rev = int(value)
elif name == properties.PROP_EXTERNALS:
trace.mutter('svn:externals property on file!')
elif name in (properties.PROP_ENTRY_COMMITTED_DATE,
properties.PROP_ENTRY_LAST_AUTHOR,
properties.PROP_ENTRY_LOCK_TOKEN,
properties.PROP_ENTRY_UUID,
properties.PROP_MIME_TYPE):
pass
elif name.startswith(properties.PROP_WC_PREFIX):
pass
elif (name.startswith(properties.PROP_PREFIX) or
name.startswith(SVN_PROP_BZR_PREFIX)):
trace.mutter('unsupported file property %r', name)
def close(self, checksum=None):
if not isinstance(self.path, text_type):
raise TypeError(self.path)
return self._close()
class DirectoryRevisionBuildEditor(DirectoryBuildEditor):
__slots__ = ('new_id', 'bzr_base_path',
'_renew_fileids', 'new_ie',
'svn_base_ie', 'bzr_base_ie')
def __repr__(self):
return "<%s for %s>" % (self.__class__.__name__, self.new_id)
def __init__(self, editor, bzr_base_path, path, new_id,
bzr_base_ie, svn_base_ie, parent_file_id, renew_fileids=None):
super(DirectoryRevisionBuildEditor, self).__init__(editor, path)
assert isinstance(new_id, bytes)
self.new_id = new_id
self.bzr_base_path = bzr_base_path
self._renew_fileids = renew_fileids
self.bzr_base_ie = bzr_base_ie
self.svn_base_ie = svn_base_ie
self.new_ie = InventoryDirectory(
self.new_id, urlutils.basename(self.path), parent_file_id)
if self.bzr_base_ie:
self.new_ie.revision = self.bzr_base_ie.revision
def _delete_entry(self, path, revnum):
self.editor._delete_entry(self.svn_base_ie.file_id, path, revnum)
def _close(self):
if (not has_id(self.editor.bzr_base_tree, self.new_id) or
self.new_ie != self.editor.bzr_base_tree.root_inventory.get_entry(self.new_id) or
self.bzr_base_path != self.path):
self.new_ie.revision = self.editor._get_directory_revision(self.new_id)
self.editor.texts.insert_record_stream([
ChunkedContentFactory(
(self.new_id, self.new_ie.revision),
self.editor._get_text_parents(self.new_id), None,
[])])
self.editor._inv_delta_append(
self.bzr_base_path, self.path, self.new_id, self.new_ie)
if self._renew_fileids:
# Make sure files get re-added that weren't mentioned explicitly
self.editor._renew_fileids(self._renew_fileids.file_id)
if self.path == u"":
self.editor._finish_commit()
def _add_directory(self, path, copyfrom_path=None, copyfrom_revnum=-1):
file_id = self.editor._get_new_file_id(path)
# This directory was moved here from somewhere else, but the
# other location hasn't been removed yet.
if copyfrom_path is not None:
svn_base_ie = self.editor.get_svn_base_ie_copyfrom(
copyfrom_path, copyfrom_revnum)
else:
svn_base_ie = None
try:
bzr_base_path = self.editor.bzr_base_tree.id2path(file_id)
except NoSuchId:
bzr_base_path = None
bzr_base_ie = None
else:
bzr_base_ie = self.editor.bzr_base_tree.root_inventory.get_entry(file_id)
return DirectoryRevisionBuildEditor(
self.editor, bzr_base_path, path,
file_id, bzr_base_ie, svn_base_ie, self.new_id,
[])
def _open_directory(self, path, base_revnum):
(svn_base_file_id, svn_base_ie) = self.editor.get_svn_base_ie_open(
self.svn_base_ie.file_id, path, base_revnum)
if self.bzr_base_ie:
file_id = self.editor._get_existing_file_id(
self.bzr_base_ie.file_id, self.new_id, path)
else:
file_id = self.editor._get_new_file_id(path)
try:
bzr_base_ie = self.editor.bzr_base_tree.root_inventory.get_entry(file_id)
except NoSuchId:
bzr_base_ie = None
if file_id == svn_base_file_id:
bzr_base_path = path
renew_fileids = None
else:
bzr_base_path = None
self._delete_entry(path, base_revnum)
# If a directory is replaced by a copy of itself, we need
# to make sure all children get readded with a new file id
renew_fileids = svn_base_ie
return DirectoryRevisionBuildEditor(self.editor, bzr_base_path, path,
file_id, bzr_base_ie, svn_base_ie, self.new_id,
renew_fileids=renew_fileids)
def _add_file(self, path, copyfrom_path=None, copyfrom_revnum=-1):
file_id = self.editor._get_new_file_id(path)
try:
bzr_base_path = self.editor.bzr_base_tree.id2path(file_id)
except NoSuchId:
bzr_base_path = None
if copyfrom_path is not None:
# Delta's will be against this text
svn_base_ie = self.editor.get_svn_base_ie_copyfrom(
copyfrom_path, copyfrom_revnum)
else:
svn_base_ie = None
return FileRevisionBuildEditor(
self.editor, bzr_base_path, path,
file_id, self.new_id, svn_base_ie)
def _open_file(self, path, base_revnum):
(svn_base_file_id, svn_base_ie) = self.editor.get_svn_base_ie_open(
self.svn_base_ie.file_id, path, base_revnum)
if self.bzr_base_ie:
file_id = self.editor._get_existing_file_id(
self.bzr_base_ie.file_id, self.new_id, path)
else:
file_id = self.editor._get_new_file_id(path)
if file_id == svn_base_file_id:
bzr_base_path = path
else:
# Replace with historical version
bzr_base_path = None
self._delete_entry(path, base_revnum)
return FileRevisionBuildEditor(
self.editor, bzr_base_path, path, file_id, self.new_id,
svn_base_ie)
def chunks_start_with_link(chunks):
# Shortcut for chunked:
if not chunks:
return False
if len(chunks[0]) >= 5:
return chunks[0].startswith("link ")
return "".join(chunks[:6]).startswith('link ')
class FileRevisionBuildEditor(FileBuildEditor):
__slots__ = ('bzr_base_path', 'file_id', 'is_symlink', 'svn_base_ie',
'base_chunks', 'chunks', 'parent_file_id')
def __init__(self, editor, bzr_base_path, path, file_id, parent_file_id,
svn_base_ie):
super(FileRevisionBuildEditor, self).__init__(editor, path)
self.bzr_base_path = bzr_base_path
self.file_id = file_id
self.svn_base_ie = svn_base_ie
if self.svn_base_ie is None:
self.base_chunks = []
self.is_symlink = False
else:
self.is_symlink = (svn_base_ie.kind == 'symlink')
self.base_chunks = self.editor._get_chunked(self.svn_base_ie)
self.chunks = None
self.parent_file_id = parent_file_id
def _apply_textdelta(self, base_checksum=None):
if base_checksum is not None:
actual_checksum = md5_strings(self.base_chunks)
if base_checksum != actual_checksum:
raise TextChecksumMismatch(
base_checksum, actual_checksum,
self.editor.revmeta.metarev.branch_path,
self.editor.revmeta.metarev.revnum)
self.chunks = []
return apply_txdelta_handler_chunks(self.base_chunks, self.chunks)
def _close(self, checksum=None):
if self.chunks is not None:
chunks = self.chunks
else:
# No delta was send, use the base chunks
chunks = self.base_chunks
chunks = map(bytes, chunks)
md5sum = osutils.md5()
shasum = osutils.sha()
text_size = 0
for chunk in chunks:
md5sum.update(chunk)
shasum.update(chunk)
text_size += len(chunk)
text_sha1 = shasum.hexdigest()
if checksum is not None:
actual_checksum = md5sum.hexdigest()
if checksum != actual_checksum:
raise TextChecksumMismatch(
checksum, actual_checksum,
self.editor.revmeta.metarev.branch_path,
self.editor.revmeta.metarev.revnum)
if self.is_special is not None:
self.is_symlink = (
self.is_special and chunks_start_with_link(chunks))
elif chunks_start_with_link(chunks):
# This file just might be a file that is svn:special but didn't
# contain a symlink but does now
if not self.is_symlink:
pass # FIXME: Query whether this file has svn:special set.
else:
self.is_symlink = False
assert self.is_symlink in (True, False)
if self.is_executable is None:
if self.svn_base_ie is not None:
self.is_executable = self.svn_base_ie.executable
else:
self.is_executable = False
parent_keys = self.editor._get_text_parents(self.file_id)
orig_chunks = chunks
if self.is_symlink:
ie = InventoryLink(
self.file_id, urlutils.basename(self.path),
self.parent_file_id)
ie.symlink_target = "".join(chunks)[len("link "):].decode("utf-8")
if "\n" in ie.symlink_target:
raise SymlinkTargetContainsNewline(self.path)
chunks = []
text_sha1 = osutils.sha_string("")
else:
ie = InventoryFile(
self.file_id, urlutils.basename(self.path),
self.parent_file_id)
ie.text_sha1 = text_sha1
ie.text_size = text_size
assert ie.text_size is not None
ie.executable = self.is_executable
text_revision = self.editor._get_file_revision(ie, self.path)
file_key = (self.file_id, text_revision)
cf = ChunkedContentFactory(file_key, parent_keys, text_sha1, chunks)
self.editor._text_cache[file_key] = orig_chunks
self.editor.texts.insert_record_stream([cf])
ie.revision = text_revision
self.editor._inv_delta_append(
self.bzr_base_path, self.path, self.file_id, ie)
def ensure_inventories_in_repo(repo, trees):
real_inv_vf = repo.inventories.without_fallbacks()
for t in trees:
revid = t.get_revision_id()
if revid == NULL_REVISION:
continue
if not real_inv_vf.get_parent_map([(revid, )]):
repo.add_inventory(revid, t.root_inventory, t.get_parent_ids())
class RevisionBuildEditor(DeltaBuildEditor):
"""Implementation of the Subversion commit editor interface that builds a
Bazaar revision.
"""
def __repr__(self):
return "<%s for %r in %r for %r>" % (
self.__class__.__name__, self.revid, self.target, self.source)
def __init__(self, source, target, revid, bzr_parent_trees, svn_base_tree,
revmeta, lhs_parent_revmeta, mapping, text_cache):
self.target = target
self.source = source
self.texts = target.texts
self.revid = revid
self._text_revids = None
self._text_cache = text_cache
self.bzr_base_tree = bzr_parent_trees[0]
self.bzr_parent_trees = bzr_parent_trees
self.svn_base_tree = svn_base_tree
self._inv_delta = []
self._new_file_paths = {}
self._deleted = set()
self._explicitly_deleted = set()
self.root_inventory = None
super(RevisionBuildEditor, self).__init__(revmeta, mapping)
self.lhs_parent_revmeta = lhs_parent_revmeta
self._text_revisions_overrides = revmeta.get_text_revisions(mapping)
self._text_parents_overrides = revmeta.get_text_parents(mapping)
def _inv_delta_append(self, old_path, new_path, file_id, ie):
self._new_file_paths[file_id] = new_path
self._inv_delta.append((old_path, new_path, file_id, ie))
def _delete_entry(self, old_parent_id, path, revnum):
self._explicitly_deleted.add(path)
def rec_del(fid):
p = self.bzr_base_tree.id2path(fid)
if p in self._deleted:
return
self._deleted.add(p)
if fid not in self.id_map.values():
self._inv_delta_append(p, None, fid, None)
if self.bzr_base_tree.kind(p) != 'directory':
return
for c in self.bzr_base_tree.iter_child_entries(p):
rec_del(c.file_id)
base_file_id = self._get_bzr_base_file_id(old_parent_id, path)
rec_del(base_file_id)
def get_svn_base_ie_open(self, parent_id, path, revnum):
"""Find the inventory entry against which svn is sending the
changes to generate the current one.
:param parent_id: File id of the parent
:param path: Path as it exists in the current revision
:param revnum: Revision number from which to open
:return: Tuple with file id and inventory entry
"""
if not isinstance(path, text_type):
raise TypeError(path)
assert (type(parent_id) is str or (parent_id is None and path == ""))
if path == u"":
if self.lhs_parent_revmeta is not None:
try:
(action, copyfrom_path, copyfrom_revnum, kind) = (
self.revmeta.metarev.paths.get(
self.revmeta.metarev.branch_path))
except TypeError:
copyfrom_path = None
if copyfrom_path is None:
svn_base_path = "."
else:
# Map copyfrom_path to the path that's related to the lhs
# parent branch path.
prev_locations = self.source.svn_transport.get_locations(
copyfrom_path, copyfrom_revnum,
[self.lhs_parent_revmeta.metarev.revnum])
copyfrom_path = prev_locations[self.lhs_parent_revmeta.metarev.revnum].strip("/")
svn_base_path = urlutils.determine_relative_path(
self.lhs_parent_revmeta.metarev.branch_path, copyfrom_path)
if svn_base_path == ".":
svn_base_path = ""
else:
svn_base_path = ""
file_id = self.svn_base_tree.path2id(svn_base_path)
else:
file_id = tree_parent_id_basename_to_file_id(
self.svn_base_tree, parent_id,
urlutils.basename(path))
return (file_id, self.svn_base_tree.root_inventory.get_entry(file_id))
def get_svn_base_ie_copyfrom(self, path, revnum):
"""Look up the base ie for the svn path, revnum.
:param path: Path to look up, relative to the current branch path
:param revnum: Revision number for which to lookup the path
"""
# Find the ancestor of self.revmeta with revnum revnum
last_revmeta = None
for revmeta, hidden, mapping in self.source._revmeta_provider._iter_reverse_revmeta_mapping_history(
self.revmeta.branch_path, self.revmeta.metarev.revnum, revnum, self.mapping):
if hidden:
continue
last_revmeta = revmeta
assert last_revmeta is not None and last_revmeta.metarev.revnum == revnum
revid = last_revmeta.get_revision_id(mapping)
# TODO: Use InterRepository._get_tree() for better performance,
# as it does (some) caching ?
inv = self.target.get_inventory(revid)
file_id = inv.path2id(path)
return inv[file_id]
def _get_chunked(self, ie):
if ie.kind == 'symlink':
return ("link ", ie.symlink_target.encode("utf-8"))
key = (ie.file_id, ie.revision)
file_data = self._text_cache.get(key)
if file_data is not None:
return file_data
return next(self.target.iter_files_bytes([key + (None,)]))[1]
def _add_merge_texts(self):
def get_new_file_path(file_id):
try:
return self._new_file_paths[file_id]
except KeyError:
base_ie = self.bzr_base_tree.root_inventory.get_entry(file_id)
if base_ie.parent_id is None:
parent_path = ""
else:
parent_path = get_new_file_path(base_ie.parent_id)
return urlutils.join(parent_path, base_ie.name)
# Add dummy merge text revisions
for file_id in self.bzr_base_tree.all_file_ids():
if file_id in self._new_file_paths:
continue
base_ie = self.bzr_base_tree.root_inventory.get_entry(file_id)
for tree in self.bzr_parent_trees[1:]:
try:
parent_ie = tree.root_inventory.get_entry(file_id)
except NoSuchId:
continue
if parent_ie.revision != base_ie.revision:
new_ie = base_ie.copy()
new_path = get_new_file_path(file_id)
new_ie.revision = self._text_revisions_overrides.get(
new_path, self.revid)
record = next(self.texts.get_record_stream([
(base_ie.file_id, base_ie.revision)], 'unordered',
True))
self.texts.insert_record_stream(
[FulltextContentFactory(
(new_ie.file_id, new_ie.revision),
self._get_text_parents(file_id),
record.sha1,
record.get_bytes_as('fulltext'))])
self._inv_delta_append(
self.bzr_base_tree.id2path(file_id), new_path,
file_id, new_ie)
break
def _finish_commit(self):
if len(self.bzr_parent_trees) > 1:
self._add_merge_texts()
rev = self.revmeta.get_revision(self.mapping, self.lhs_parent_revmeta)
assert rev.revision_id != NULL_REVISION
try:
assert rev.parent_ids[0] != NULL_REVISION
assert rev.parent_ids[0] == self.bzr_base_tree.get_revision_id(), \
"revision lhs parent %s does not match base tree revid %s" % \
(rev.parent_ids, self.bzr_base_tree.get_revision_id())
basis_id = rev.parent_ids[0]
basis_inv = self.bzr_base_tree.root_inventory
except IndexError:
basis_id = NULL_REVISION
basis_inv = None
present_parent_ids = self.target.has_revisions(rev.parent_ids)
rev.inventory_sha1, self.root_inventory = \
self.target.add_inventory_by_delta(
basis_id, self._inv_delta, rev.revision_id,
tuple([r for r in rev.parent_ids if r in present_parent_ids]),
basis_inv)
self.target.add_revision(self.revid, rev)
# Only fetch signature if it's cheap
if self.source.svn_transport.has_capability("log-revprops"):
signature = self.revmeta.get_signature()
if signature is not None:
self.target.add_signature_text(self.revid, signature)
def _open_root(self, base_revnum):
assert self.revid is not None
if self.svn_base_tree.path2id('') is None:
svn_base_ie = None
svn_base_file_id = None
else:
(svn_base_file_id, svn_base_ie) = self.get_svn_base_ie_open(
None, u"", base_revnum)
if self.bzr_base_tree.path2id('') is None:
# First time the root is set
bzr_base_ie = None
file_id = self._get_new_file_id(u"")
renew_fileids = None
bzr_base_path = None
else:
# Just inherit file id from previous
file_id = self._get_existing_file_id(None, None, u"")
try:
bzr_base_path = self.bzr_base_tree.id2path(file_id)
except NoSuchId:
bzr_base_path = None
bzr_base_ie = None
else:
bzr_base_ie = self.bzr_base_tree.root_inventory.get_entry(file_id)
if bzr_base_path != u"":
self._delete_entry(None, u"", base_revnum)
renew_fileids = None
elif file_id == svn_base_file_id:
renew_fileids = None
else:
self._delete_entry(None, u"", base_revnum)
renew_fileids = svn_base_ie
assert isinstance(file_id, bytes)
return DirectoryRevisionBuildEditor(
self, bzr_base_path, u"", file_id, bzr_base_ie, svn_base_ie, None,
renew_fileids)
def _renew_fileids(self, file_id):
# A bit expensive (O(d)), but this should be very rare
delta_new_paths = set(
[e[1] for e in self._inv_delta if e[1] is not None])
exceptions = delta_new_paths.union(self._explicitly_deleted)
for path in tree_ancestors(self.bzr_base_tree, file_id, exceptions):
if isinstance(path, bytes):
path = path.decode("utf-8")
self._renew_fileid(path)
def _renew_fileid(self, path):
"""'renew' the fileid of a path."""
if not isinstance(path, text_type):
raise TypeError(path)
old_file_id = self.bzr_base_tree.path2id(path)
old_ie = self.bzr_base_tree.root_inventory.get_entry(old_file_id)
new_ie = old_ie.copy()
new_ie.file_id = self._get_new_file_id(path)
new_ie.parent_id = self._get_new_file_id(urlutils.dirname(path))
new_ie.revision = self._text_revisions_overrides.get(path, self.revid)
# FIXME: Use self._text_cache
record = next(self.texts.get_record_stream(
[(old_ie.file_id, old_ie.revision)],
'unordered', True))
self.texts.insert_record_stream(
[ChunkedContentFactory(
(new_ie.file_id, new_ie.revision),
[], # New file id, so no parents
record.sha1,
record.get_bytes_as('chunked'))])
self._inv_delta_append(
self.bzr_base_tree.path2id(new_ie.file_id),
path, new_ie.file_id, new_ie)
@property
def id_map(self):
if self._id_map is not None:
return self._id_map
local_changes = get_local_changes(
self.revmeta.metarev.paths, self.revmeta.metarev.branch_path)
self._id_map = self.source.fileid_map.get_idmap_delta(
local_changes, self.revmeta, self.mapping)
return self._id_map
def _get_map_id(self, new_path):
return self.id_map.get(new_path)
def _get_bzr_base_file_id(self, parent_id, path):
if not isinstance(path, text_type):
raise TypeError(path)
assert (isinstance(parent_id, bytes) or
(parent_id is None and path == ""))
basename = urlutils.basename(path)
return tree_parent_id_basename_to_file_id(
self.bzr_base_tree, parent_id, basename)
def _get_existing_file_id(self, old_parent_id, new_parent_id, path):
if not isinstance(path, text_type):
raise TypeError(path)
assert isinstance(old_parent_id, bytes) or old_parent_id is None
assert isinstance(new_parent_id, bytes) or new_parent_id is None
ret = self._get_map_id(path)