1
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
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
20
from __future__ import absolute_import
22
from collections import deque
24
from io import BytesIO
27
from dulwich.index import (
28
blob_from_path_and_stat,
31
index_entry_from_stat,
33
from dulwich.object_store import (
37
from dulwich.objects import (
48
controldir as _mod_controldir,
58
from ..revision import (
62
from ..sixish import (
67
from .mapping import (
75
class GitTreeDirectory(_mod_tree.TreeDirectory):
77
__slots__ = ['file_id', 'name', 'parent_id', 'children']
79
def __init__(self, file_id, name, parent_id):
80
self.file_id = file_id
82
self.parent_id = parent_id
95
return self.__class__(
96
self.file_id, self.name, self.parent_id)
99
return "%s(file_id=%r, name=%r, parent_id=%r)" % (
100
self.__class__.__name__, self.file_id, self.name,
103
def __eq__(self, other):
104
return (self.kind == other.kind and
105
self.file_id == other.file_id and
106
self.name == other.name and
107
self.parent_id == other.parent_id)
110
class GitTreeFile(_mod_tree.TreeFile):
112
__slots__ = ['file_id', 'name', 'parent_id', 'text_size', 'text_sha1',
115
def __init__(self, file_id, name, parent_id, text_size=None,
116
text_sha1=None, executable=None):
117
self.file_id = file_id
119
self.parent_id = parent_id
120
self.text_size = text_size
121
self.text_sha1 = text_sha1
122
self.executable = executable
128
def __eq__(self, other):
129
return (self.kind == other.kind and
130
self.file_id == other.file_id and
131
self.name == other.name and
132
self.parent_id == other.parent_id and
133
self.text_sha1 == other.text_sha1 and
134
self.text_size == other.text_size and
135
self.executable == other.executable)
138
return ("%s(file_id=%r, name=%r, parent_id=%r, text_size=%r, "
139
"text_sha1=%r, executable=%r)") % (
140
type(self).__name__, self.file_id, self.name, self.parent_id,
141
self.text_size, self.text_sha1, self.executable)
144
ret = self.__class__(
145
self.file_id, self.name, self.parent_id)
146
ret.text_sha1 = self.text_sha1
147
ret.text_size = self.text_size
148
ret.executable = self.executable
152
class GitTreeSymlink(_mod_tree.TreeLink):
154
__slots__ = ['file_id', 'name', 'parent_id', 'symlink_target']
156
def __init__(self, file_id, name, parent_id,
157
symlink_target=None):
158
self.file_id = file_id
160
self.parent_id = parent_id
161
self.symlink_target = symlink_target
168
def executable(self):
176
return "%s(file_id=%r, name=%r, parent_id=%r, symlink_target=%r)" % (
177
type(self).__name__, self.file_id, self.name, self.parent_id,
180
def __eq__(self, other):
181
return (self.kind == other.kind and
182
self.file_id == other.file_id and
183
self.name == other.name and
184
self.parent_id == other.parent_id and
185
self.symlink_target == other.symlink_target)
188
return self.__class__(
189
self.file_id, self.name, self.parent_id,
193
class GitTreeSubmodule(_mod_tree.TreeLink):
195
__slots__ = ['file_id', 'name', 'parent_id', 'reference_revision']
197
def __init__(self, file_id, name, parent_id, reference_revision=None):
198
self.file_id = file_id
200
self.parent_id = parent_id
201
self.reference_revision = reference_revision
205
return 'tree-reference'
208
return ("%s(file_id=%r, name=%r, parent_id=%r, "
209
"reference_revision=%r)") % (
210
type(self).__name__, self.file_id, self.name, self.parent_id,
211
self.reference_revision)
213
def __eq__(self, other):
214
return (self.kind == other.kind and
215
self.file_id == other.file_id and
216
self.name == other.name and
217
self.parent_id == other.parent_id and
218
self.reference_revision == other.reference_revision)
221
return self.__class__(
222
self.file_id, self.name, self.parent_id,
223
self.reference_revision)
227
'directory': GitTreeDirectory,
229
'symlink': GitTreeSymlink,
230
'tree-reference': GitTreeSubmodule,
234
def ensure_normalized_path(path):
235
"""Check whether path is normalized.
237
:raises InvalidNormalization: When path is not normalized, and cannot be
238
accessed on this platform by the normalized path.
239
:return: The NFC normalised version of path.
241
norm_path, can_access = osutils.normalized_filename(path)
242
if norm_path != path:
246
raise errors.InvalidNormalization(path)
250
class GitRevisionTree(revisiontree.RevisionTree):
251
"""Revision tree implementation based on Git objects."""
253
def __init__(self, repository, revision_id):
254
self._revision_id = revision_id
255
self._repository = repository
256
self.store = repository._git.object_store
257
if not isinstance(revision_id, bytes):
258
raise TypeError(revision_id)
259
self.commit_id, self.mapping = repository.lookup_bzr_revision_id(
261
if revision_id == NULL_REVISION:
263
self.mapping = default_mapping
264
self._fileid_map = GitFileIdMap(
269
commit = self.store[self.commit_id]
271
raise errors.NoSuchRevision(repository, revision_id)
272
self.tree = commit.tree
273
self._fileid_map = self.mapping.get_fileid_map(
274
self.store.__getitem__, self.tree)
276
def _get_nested_repository(self, path):
277
nested_repo_transport = self._repository.user_transport.clone(path)
278
nested_controldir = _mod_controldir.ControlDir.open_from_transport(
279
nested_repo_transport)
280
return nested_controldir.find_repository()
282
def supports_rename_tracking(self):
285
def get_file_revision(self, path):
286
change_scanner = self._repository._file_change_scanner
287
if self.commit_id == ZERO_SHA:
289
(unused_path, commit_id) = change_scanner.find_last_change_revision(
290
path.encode('utf-8'), self.commit_id)
291
return self._repository.lookup_foreign_revision_id(
292
commit_id, self.mapping)
294
def get_file_mtime(self, path):
296
revid = self.get_file_revision(path)
298
raise errors.NoSuchFile(path)
300
rev = self._repository.get_revision(revid)
301
except errors.NoSuchRevision:
302
raise _mod_tree.FileTimestampUnavailable(path)
305
def id2path(self, file_id):
307
path = self._fileid_map.lookup_path(file_id)
309
raise errors.NoSuchId(self, file_id)
310
if self.is_versioned(path):
312
raise errors.NoSuchId(self, file_id)
314
def is_versioned(self, path):
315
return self.has_filename(path)
317
def path2id(self, path):
318
if self.mapping.is_special_file(path):
320
if not self.is_versioned(path):
322
return self._fileid_map.lookup_file_id(osutils.safe_unicode(path))
324
def all_file_ids(self):
325
raise errors.UnsupportedOperation(self.all_file_ids, self)
327
def all_versioned_paths(self):
329
todo = [(self.store, b'', self.tree)]
331
(store, path, tree_id) = todo.pop()
334
tree = store[tree_id]
335
for name, mode, hexsha in tree.items():
336
subpath = posixpath.join(path, name)
337
ret.add(subpath.decode('utf-8'))
338
if stat.S_ISDIR(mode):
339
todo.append((store, subpath, hexsha))
342
def has_or_had_id(self, file_id):
344
self.id2path(file_id)
345
except errors.NoSuchId:
349
def has_id(self, file_id):
351
path = self.id2path(file_id)
352
except errors.NoSuchId:
354
return self.has_filename(path)
356
def _lookup_path(self, path):
357
if self.tree is None:
358
raise errors.NoSuchFile(path)
360
(mode, hexsha) = tree_lookup_path(
361
self.store.__getitem__, self.tree, path.encode('utf-8'))
363
raise errors.NoSuchFile(self, path)
365
return (self.store, mode, hexsha)
367
def is_executable(self, path):
368
(store, mode, hexsha) = self._lookup_path(path)
370
# the tree root is a directory
372
return mode_is_executable(mode)
374
def kind(self, path):
375
(store, mode, hexsha) = self._lookup_path(path)
377
# the tree root is a directory
379
return mode_kind(mode)
381
def has_filename(self, path):
383
self._lookup_path(path)
384
except errors.NoSuchFile:
389
def list_files(self, include_root=False, from_dir=None, recursive=True):
390
if self.tree is None:
392
if from_dir is None or from_dir == '.':
394
(store, mode, hexsha) = self._lookup_path(from_dir)
395
if mode is None: # Root
396
root_ie = self._get_dir_ie(b"", None)
398
parent_path = posixpath.dirname(from_dir)
399
parent_id = self._fileid_map.lookup_file_id(parent_path)
400
if mode_kind(mode) == 'directory':
401
root_ie = self._get_dir_ie(from_dir.encode("utf-8"), parent_id)
403
root_ie = self._get_file_ie(
404
store, from_dir.encode("utf-8"),
405
posixpath.basename(from_dir), mode, hexsha)
407
yield (from_dir, "V", root_ie.kind, root_ie)
409
if root_ie.kind == 'directory':
410
todo.append((store, from_dir.encode("utf-8"),
411
b"", hexsha, root_ie.file_id))
413
(store, path, relpath, hexsha, parent_id) = todo.pop()
415
for name, mode, hexsha in tree.iteritems():
416
if self.mapping.is_special_file(name):
418
child_path = posixpath.join(path, name)
419
child_relpath = posixpath.join(relpath, name)
420
if stat.S_ISDIR(mode):
421
ie = self._get_dir_ie(child_path, parent_id)
424
(store, child_path, child_relpath, hexsha,
427
ie = self._get_file_ie(
428
store, child_path, name, mode, hexsha, parent_id)
429
yield (child_relpath.decode('utf-8'), "V", ie.kind, ie)
431
def _get_file_ie(self, store, path, name, mode, hexsha, parent_id):
432
if not isinstance(path, bytes):
433
raise TypeError(path)
434
if not isinstance(name, bytes):
435
raise TypeError(name)
436
kind = mode_kind(mode)
437
path = path.decode('utf-8')
438
name = name.decode("utf-8")
439
file_id = self._fileid_map.lookup_file_id(path)
440
ie = entry_factory[kind](file_id, name, parent_id)
441
if kind == 'symlink':
442
ie.symlink_target = store[hexsha].data.decode('utf-8')
443
elif kind == 'tree-reference':
444
ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(
447
data = store[hexsha].data
448
ie.text_sha1 = osutils.sha_string(data)
449
ie.text_size = len(data)
450
ie.executable = mode_is_executable(mode)
453
def _get_dir_ie(self, path, parent_id):
454
path = path.decode('utf-8')
455
file_id = self._fileid_map.lookup_file_id(path)
456
return GitTreeDirectory(file_id, posixpath.basename(path), parent_id)
458
def iter_child_entries(self, path):
459
(store, mode, tree_sha) = self._lookup_path(path)
461
if mode is not None and not stat.S_ISDIR(mode):
464
encoded_path = path.encode('utf-8')
465
file_id = self.path2id(path)
466
tree = store[tree_sha]
467
for name, mode, hexsha in tree.iteritems():
468
if self.mapping.is_special_file(name):
470
child_path = posixpath.join(encoded_path, name)
471
if stat.S_ISDIR(mode):
472
yield self._get_dir_ie(child_path, file_id)
474
yield self._get_file_ie(store, child_path, name, mode, hexsha,
477
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
478
if self.tree is None:
481
# TODO(jelmer): Support yield parents
482
raise NotImplementedError
483
if specific_files is not None:
484
if specific_files in ([""], []):
485
specific_files = None
487
specific_files = set([p.encode('utf-8')
488
for p in specific_files])
489
todo = deque([(self.store, b"", self.tree, self.path2id(''))])
490
if specific_files is None or u"" in specific_files:
491
yield u"", self._get_dir_ie(b"", None)
493
store, path, tree_sha, parent_id = todo.popleft()
494
tree = store[tree_sha]
496
for name, mode, hexsha in tree.iteritems():
497
if self.mapping.is_special_file(name):
499
child_path = posixpath.join(path, name)
500
child_path_decoded = child_path.decode('utf-8')
501
if stat.S_ISDIR(mode):
502
if (specific_files is None or
503
any([p for p in specific_files if p.startswith(
506
(store, child_path, hexsha,
507
self.path2id(child_path_decoded)))
508
if specific_files is None or child_path in specific_files:
509
if stat.S_ISDIR(mode):
510
yield (child_path_decoded,
511
self._get_dir_ie(child_path, parent_id))
513
yield (child_path_decoded,
514
self._get_file_ie(store, child_path, name, mode,
516
todo.extendleft(reversed(extradirs))
518
def iter_references(self):
519
if self.supports_tree_reference():
520
for path, entry in self.iter_entries_by_dir():
521
if entry.kind == 'tree-reference':
524
def get_revision_id(self):
525
"""See RevisionTree.get_revision_id."""
526
return self._revision_id
528
def get_file_sha1(self, path, stat_value=None):
529
if self.tree is None:
530
raise errors.NoSuchFile(path)
531
return osutils.sha_string(self.get_file_text(path))
533
def get_file_verifier(self, path, stat_value=None):
534
(store, mode, hexsha) = self._lookup_path(path)
535
return ("GIT", hexsha)
537
def get_file_size(self, path):
538
(store, mode, hexsha) = self._lookup_path(path)
539
if stat.S_ISREG(mode):
540
return len(store[hexsha].data)
543
def get_file_text(self, path):
544
"""See RevisionTree.get_file_text."""
545
(store, mode, hexsha) = self._lookup_path(path)
546
if stat.S_ISREG(mode):
547
return store[hexsha].data
551
def get_symlink_target(self, path):
552
"""See RevisionTree.get_symlink_target."""
553
(store, mode, hexsha) = self._lookup_path(path)
554
if stat.S_ISLNK(mode):
555
return store[hexsha].data.decode('utf-8')
559
def get_reference_revision(self, path):
560
"""See RevisionTree.get_symlink_target."""
561
(store, mode, hexsha) = self._lookup_path(path)
562
if S_ISGITLINK(mode):
563
nested_repo = self._get_nested_repository(path)
564
return nested_repo.lookup_foreign_revision_id(hexsha)
568
def _comparison_data(self, entry, path):
570
return None, False, None
571
return entry.kind, entry.executable, None
573
def path_content_summary(self, path):
574
"""See Tree.path_content_summary."""
576
(store, mode, hexsha) = self._lookup_path(path)
577
except errors.NoSuchFile:
578
return ('missing', None, None, None)
579
kind = mode_kind(mode)
581
executable = mode_is_executable(mode)
582
contents = store[hexsha].data
583
return (kind, len(contents), executable,
584
osutils.sha_string(contents))
585
elif kind == 'symlink':
586
return (kind, None, None, store[hexsha].data.decode('utf-8'))
587
elif kind == 'tree-reference':
588
nested_repo = self._get_nested_repository(path)
589
return (kind, None, None,
590
nested_repo.lookup_foreign_revision_id(hexsha))
592
return (kind, None, None, None)
594
def find_related_paths_across_trees(self, paths, trees=[],
595
require_versioned=True):
598
if require_versioned:
599
trees = [self] + (trees if trees is not None else [])
603
if t.is_versioned(p):
608
raise errors.PathsNotVersionedError(unversioned)
609
return filter(self.is_versioned, paths)
611
def _iter_tree_contents(self, include_trees=False):
612
if self.tree is None:
614
return self.store.iter_tree_contents(
615
self.tree, include_trees=include_trees)
617
def annotate_iter(self, path, default_revision=CURRENT_REVISION):
618
"""Return an iterator of revision_id, line tuples.
620
For working trees (and mutable trees in general), the special
621
revision_id 'current:' will be used for lines that are new in this
622
tree, e.g. uncommitted changes.
623
:param default_revision: For lines that don't match a basis, mark them
624
with this revision id. Not all implementations will make use of
627
with self.lock_read():
628
# Now we have the parents of this content
629
from breezy.annotate import Annotator
630
from .annotate import AnnotateProvider
631
annotator = Annotator(AnnotateProvider(
632
self._repository._file_change_scanner))
633
this_key = (path, self.get_file_revision(path))
634
annotations = [(key[-1], line)
635
for key, line in annotator.annotate_flat(this_key)]
638
def _get_rules_searcher(self, default_searcher):
639
return default_searcher
641
def walkdirs(self, prefix=u""):
642
(store, mode, hexsha) = self._lookup_path(prefix)
644
[(store, prefix.encode('utf-8'), hexsha, self.path2id(prefix))])
646
store, path, tree_sha, parent_id = todo.popleft()
647
path_decoded = path.decode('utf-8')
648
tree = store[tree_sha]
650
for name, mode, hexsha in tree.iteritems():
651
if self.mapping.is_special_file(name):
653
child_path = posixpath.join(path, name)
654
file_id = self.path2id(child_path.decode('utf-8'))
655
if stat.S_ISDIR(mode):
656
todo.append((store, child_path, hexsha, file_id))
658
(child_path.decode('utf-8'), name.decode('utf-8'),
659
mode_kind(mode), None,
660
file_id, mode_kind(mode)))
661
yield (path_decoded, parent_id), children
664
def tree_delta_from_git_changes(changes, mapping,
665
fileid_maps, specific_files=None,
666
require_versioned=False, include_root=False,
668
"""Create a TreeDelta from two git trees.
670
source and target are iterators over tuples with:
671
(filename, sha, mode)
673
(old_fileid_map, new_fileid_map) = fileid_maps
674
if target_extras is None:
675
target_extras = set()
676
ret = delta.TreeDelta()
678
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
679
if newpath == b'' and not include_root:
682
oldpath_decoded = None
684
oldpath_decoded = oldpath.decode('utf-8')
686
newpath_decoded = None
688
newpath_decoded = newpath.decode('utf-8')
689
if not (specific_files is None or
690
(oldpath is not None and
691
osutils.is_inside_or_parent_of_any(
692
specific_files, oldpath_decoded)) or
693
(newpath is not None and
694
osutils.is_inside_or_parent_of_any(
695
specific_files, newpath_decoded))):
697
if mapping.is_special_file(oldpath):
699
if mapping.is_special_file(newpath):
701
if oldpath is None and newpath is None:
704
added.append((newpath, mode_kind(newmode)))
705
elif newpath is None or newmode == 0:
706
file_id = old_fileid_map.lookup_file_id(oldpath_decoded)
707
ret.removed.append((oldpath_decoded, file_id, mode_kind(oldmode)))
708
elif oldpath != newpath:
709
file_id = old_fileid_map.lookup_file_id(oldpath_decoded)
711
(oldpath_decoded, newpath.decode('utf-8'), file_id,
712
mode_kind(newmode), (oldsha != newsha),
713
(oldmode != newmode)))
714
elif mode_kind(oldmode) != mode_kind(newmode):
715
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
716
ret.kind_changed.append(
717
(newpath_decoded, file_id, mode_kind(oldmode),
719
elif oldsha != newsha or oldmode != newmode:
720
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
722
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
724
(newpath_decoded, file_id, mode_kind(newmode),
725
(oldsha != newsha), (oldmode != newmode)))
727
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
728
ret.unchanged.append(
729
(newpath_decoded, file_id, mode_kind(newmode)))
731
implicit_dirs = {b''}
732
for path, kind in added:
733
if kind == 'directory' or path in target_extras:
735
implicit_dirs.update(osutils.parent_directories(path))
737
for path, kind in added:
738
if kind == 'directory' and path not in implicit_dirs:
740
path_decoded = osutils.normalized_filename(path)[0]
741
if path in target_extras:
742
ret.unversioned.append((path_decoded, None, kind))
744
file_id = new_fileid_map.lookup_file_id(path_decoded)
745
ret.added.append((path_decoded, file_id, kind))
750
def changes_from_git_changes(changes, mapping, specific_files=None,
751
include_unchanged=False, target_extras=None):
752
"""Create a iter_changes-like generator from a git stream.
754
source and target are iterators over tuples with:
755
(filename, sha, mode)
757
if target_extras is None:
758
target_extras = set()
759
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
760
if oldpath is not None:
761
oldpath_decoded = oldpath.decode('utf-8')
763
oldpath_decoded = None
764
if newpath is not None:
765
newpath_decoded = newpath.decode('utf-8')
767
newpath_decoded = None
768
if not (specific_files is None or
769
(oldpath_decoded is not None and
770
osutils.is_inside_or_parent_of_any(
771
specific_files, oldpath_decoded)) or
772
(newpath_decoded is not None and
773
osutils.is_inside_or_parent_of_any(
774
specific_files, newpath_decoded))):
776
if oldpath is not None and mapping.is_special_file(oldpath):
778
if newpath is not None and mapping.is_special_file(newpath):
780
if oldpath_decoded is None:
781
fileid = mapping.generate_file_id(newpath_decoded)
790
oldexe = mode_is_executable(oldmode)
791
oldkind = mode_kind(oldmode)
795
if oldpath_decoded == u'':
799
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
800
oldparent = mapping.generate_file_id(oldparentpath)
801
fileid = mapping.generate_file_id(oldpath_decoded)
802
if newpath_decoded is None:
809
newversioned = (newpath_decoded not in target_extras)
811
newexe = mode_is_executable(newmode)
812
newkind = mode_kind(newmode)
816
if newpath_decoded == u'':
820
newparentpath, newname = osutils.split(newpath_decoded)
821
newparent = mapping.generate_file_id(newparentpath)
822
if (not include_unchanged and
823
oldkind == 'directory' and newkind == 'directory' and
824
oldpath_decoded == newpath_decoded):
826
yield _mod_tree.TreeChange(
827
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
828
(oldversioned, newversioned),
829
(oldparent, newparent), (oldname, newname),
830
(oldkind, newkind), (oldexe, newexe))
833
class InterGitTrees(_mod_tree.InterTree):
834
"""InterTree that works between two git trees."""
836
_matching_from_tree_format = None
837
_matching_to_tree_format = None
838
_test_mutable_trees_to_test_trees = None
841
def is_compatible(cls, source, target):
842
return (isinstance(source, GitRevisionTree) and
843
isinstance(target, GitRevisionTree))
845
def compare(self, want_unchanged=False, specific_files=None,
846
extra_trees=None, require_versioned=False, include_root=False,
847
want_unversioned=False):
848
with self.lock_read():
849
changes, target_extras = self._iter_git_changes(
850
want_unchanged=want_unchanged,
851
require_versioned=require_versioned,
852
specific_files=specific_files,
853
extra_trees=extra_trees,
854
want_unversioned=want_unversioned)
855
source_fileid_map = self.source._fileid_map
856
target_fileid_map = self.target._fileid_map
857
return tree_delta_from_git_changes(
858
changes, self.target.mapping,
859
(source_fileid_map, target_fileid_map),
860
specific_files=specific_files,
861
include_root=include_root, target_extras=target_extras)
863
def iter_changes(self, include_unchanged=False, specific_files=None,
864
pb=None, extra_trees=[], require_versioned=True,
865
want_unversioned=False):
866
with self.lock_read():
867
changes, target_extras = self._iter_git_changes(
868
want_unchanged=include_unchanged,
869
require_versioned=require_versioned,
870
specific_files=specific_files,
871
extra_trees=extra_trees,
872
want_unversioned=want_unversioned)
873
return changes_from_git_changes(
874
changes, self.target.mapping,
875
specific_files=specific_files,
876
include_unchanged=include_unchanged,
877
target_extras=target_extras)
879
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
880
require_versioned=False, extra_trees=None,
881
want_unversioned=False):
882
raise NotImplementedError(self._iter_git_changes)
885
class InterGitRevisionTrees(InterGitTrees):
886
"""InterTree that works between two git revision trees."""
888
_matching_from_tree_format = None
889
_matching_to_tree_format = None
890
_test_mutable_trees_to_test_trees = None
893
def is_compatible(cls, source, target):
894
return (isinstance(source, GitRevisionTree) and
895
isinstance(target, GitRevisionTree))
897
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
898
require_versioned=True, extra_trees=None,
899
want_unversioned=False):
900
trees = [self.source]
901
if extra_trees is not None:
902
trees.extend(extra_trees)
903
if specific_files is not None:
904
specific_files = self.target.find_related_paths_across_trees(
905
specific_files, trees,
906
require_versioned=require_versioned)
908
if (self.source._repository._git.object_store !=
909
self.target._repository._git.object_store):
910
store = OverlayObjectStore(
911
[self.source._repository._git.object_store,
912
self.target._repository._git.object_store])
914
store = self.source._repository._git.object_store
915
return store.tree_changes(
916
self.source.tree, self.target.tree, want_unchanged=want_unchanged,
917
include_trees=True, change_type_same=True), set()
920
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
923
class MutableGitIndexTree(mutabletree.MutableTree):
926
self._lock_mode = None
928
self._versioned_dirs = None
929
self._index_dirty = False
931
def is_versioned(self, path):
932
with self.lock_read():
933
path = path.rstrip('/').encode('utf-8')
934
(index, subpath) = self._lookup_index(path)
935
return (subpath in index or self._has_dir(path))
937
def _has_dir(self, path):
938
if not isinstance(path, bytes):
939
raise TypeError(path)
942
if self._versioned_dirs is None:
944
return path in self._versioned_dirs
946
def _load_dirs(self):
947
if self._lock_mode is None:
948
raise errors.ObjectNotLocked(self)
949
self._versioned_dirs = set()
950
# TODO(jelmer): Browse over all indexes
951
for p, i in self._recurse_index_entries():
952
self._ensure_versioned_dir(posixpath.dirname(p))
954
def _ensure_versioned_dir(self, dirname):
955
if not isinstance(dirname, bytes):
956
raise TypeError(dirname)
957
if dirname in self._versioned_dirs:
960
self._ensure_versioned_dir(posixpath.dirname(dirname))
961
self._versioned_dirs.add(dirname)
963
def path2id(self, path):
964
with self.lock_read():
965
path = path.rstrip('/')
966
if self.is_versioned(path.rstrip('/')):
967
return self._fileid_map.lookup_file_id(
968
osutils.safe_unicode(path))
971
def has_id(self, file_id):
973
self.id2path(file_id)
974
except errors.NoSuchId:
979
def id2path(self, file_id):
982
if type(file_id) is not bytes:
983
raise TypeError(file_id)
984
with self.lock_read():
986
path = self._fileid_map.lookup_path(file_id)
988
raise errors.NoSuchId(self, file_id)
989
if self.is_versioned(path):
991
raise errors.NoSuchId(self, file_id)
993
def _set_root_id(self, file_id):
994
raise errors.UnsupportedOperation(self._set_root_id, self)
996
def _add(self, files, ids, kinds):
997
for (path, file_id, kind) in zip(files, ids, kinds):
998
if file_id is not None:
999
raise workingtree.SettingFileIdUnsupported()
1000
path, can_access = osutils.normalized_filename(path)
1002
raise errors.InvalidNormalization(path)
1003
self._index_add_entry(path, kind)
1005
def _read_submodule_head(self, path):
1006
raise NotImplementedError(self._read_submodule_head)
1008
def _lookup_index(self, encoded_path):
1009
if not isinstance(encoded_path, bytes):
1010
raise TypeError(encoded_path)
1011
# TODO(jelmer): Look in other indexes
1012
return self.index, encoded_path
1014
def _index_del_entry(self, index, path):
1016
# TODO(jelmer): Keep track of dirty per index
1017
self._index_dirty = True
1019
def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
1020
if kind == "directory":
1021
# Git indexes don't contain directories
1026
file, stat_val = self.get_file_with_stat(path)
1027
except (errors.NoSuchFile, IOError):
1028
# TODO: Rather than come up with something here, use the old
1031
stat_val = os.stat_result(
1032
(stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1034
blob.set_raw_string(file.read())
1035
# Add object to the repository if it didn't exist yet
1036
if blob.id not in self.store:
1037
self.store.add_object(blob)
1039
elif kind == "symlink":
1042
stat_val = self._lstat(path)
1043
except EnvironmentError:
1044
# TODO: Rather than come up with something here, use the
1046
stat_val = os.stat_result(
1047
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1048
blob.set_raw_string(
1049
self.get_symlink_target(path).encode("utf-8"))
1050
# Add object to the repository if it didn't exist yet
1051
if blob.id not in self.store:
1052
self.store.add_object(blob)
1054
elif kind == "tree-reference":
1055
if reference_revision is not None:
1056
hexsha = self.branch.lookup_bzr_revision_id(
1057
reference_revision)[0]
1059
hexsha = self._read_submodule_head(path)
1061
raise errors.NoCommits(path)
1063
stat_val = self._lstat(path)
1064
except EnvironmentError:
1065
stat_val = os.stat_result(
1066
(S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1067
stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
1069
raise AssertionError("unknown kind '%s'" % kind)
1070
# Add an entry to the index or update the existing entry
1071
ensure_normalized_path(path)
1072
encoded_path = path.encode("utf-8")
1073
if b'\r' in encoded_path or b'\n' in encoded_path:
1074
# TODO(jelmer): Why do we need to do this?
1075
trace.mutter('ignoring path with invalid newline in it: %r', path)
1077
(index, index_path) = self._lookup_index(encoded_path)
1078
index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
1079
self._index_dirty = True
1080
if self._versioned_dirs is not None:
1081
self._ensure_versioned_dir(index_path)
1083
def _recurse_index_entries(self, index=None, basepath=b""):
1084
# Iterate over all index entries
1085
with self.lock_read():
1088
for path, value in index.items():
1089
yield (posixpath.join(basepath, path), value)
1090
(ctime, mtime, dev, ino, mode, uid, gid, size, sha,
1092
if S_ISGITLINK(mode):
1093
pass # TODO(jelmer): dive into submodule
1095
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
1097
raise NotImplementedError(self.iter_entries_by_dir)
1098
with self.lock_read():
1099
if specific_files is not None:
1100
specific_files = set(specific_files)
1102
specific_files = None
1103
root_ie = self._get_dir_ie(u"", None)
1105
if specific_files is None or u"" in specific_files:
1106
ret[(u"", u"")] = root_ie
1107
dir_ids = {u"": root_ie.file_id}
1108
for path, value in self._recurse_index_entries():
1109
if self.mapping.is_special_file(path):
1111
path = path.decode("utf-8")
1112
if specific_files is not None and path not in specific_files:
1114
(parent, name) = posixpath.split(path)
1116
file_ie = self._get_file_ie(name, path, value, None)
1117
except errors.NoSuchFile:
1119
if yield_parents or specific_files is None:
1120
for (dir_path, dir_ie) in self._add_missing_parent_ids(
1122
ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
1123
file_ie.parent_id = self.path2id(parent)
1124
ret[(posixpath.dirname(path), path)] = file_ie
1125
return ((path, ie) for ((_, path), ie) in sorted(viewitems(ret)))
1127
def iter_references(self):
1128
# TODO(jelmer): Implement a more efficient version of this
1129
for path, entry in self.iter_entries_by_dir():
1130
if entry.kind == 'tree-reference':
1133
def _get_dir_ie(self, path, parent_id):
1134
file_id = self.path2id(path)
1135
return GitTreeDirectory(file_id,
1136
posixpath.basename(path).strip("/"), parent_id)
1138
def _get_file_ie(self, name, path, value, parent_id):
1139
if not isinstance(name, text_type):
1140
raise TypeError(name)
1141
if not isinstance(path, text_type):
1142
raise TypeError(path)
1143
if not isinstance(value, tuple) or len(value) != 10:
1144
raise TypeError(value)
1145
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1146
file_id = self.path2id(path)
1147
if not isinstance(file_id, bytes):
1148
raise TypeError(file_id)
1149
kind = mode_kind(mode)
1150
ie = entry_factory[kind](file_id, name, parent_id)
1151
if kind == 'symlink':
1152
ie.symlink_target = self.get_symlink_target(path)
1153
elif kind == 'tree-reference':
1154
ie.reference_revision = self.get_reference_revision(path)
1157
data = self.get_file_text(path)
1158
except errors.NoSuchFile:
1160
except IOError as e:
1161
if e.errno != errno.ENOENT:
1165
data = self.branch.repository._git.object_store[sha].data
1166
ie.text_sha1 = osutils.sha_string(data)
1167
ie.text_size = len(data)
1168
ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1171
def _add_missing_parent_ids(self, path, dir_ids):
1174
parent = posixpath.dirname(path).strip("/")
1175
ret = self._add_missing_parent_ids(parent, dir_ids)
1176
parent_id = dir_ids[parent]
1177
ie = self._get_dir_ie(path, parent_id)
1178
dir_ids[path] = ie.file_id
1179
ret.append((path, ie))
1182
def _comparison_data(self, entry, path):
1184
return None, False, None
1185
return entry.kind, entry.executable, None
1187
def _unversion_path(self, path):
1188
if self._lock_mode is None:
1189
raise errors.ObjectNotLocked(self)
1190
encoded_path = path.encode("utf-8")
1192
(index, subpath) = self._lookup_index(encoded_path)
1194
self._index_del_entry(index, encoded_path)
1196
# A directory, perhaps?
1197
# TODO(jelmer): Deletes that involve submodules?
1198
for p in list(index):
1199
if p.startswith(subpath + b"/"):
1201
self._index_del_entry(index, p)
1204
self._versioned_dirs = None
1207
def unversion(self, paths):
1208
with self.lock_tree_write():
1210
if self._unversion_path(path) == 0:
1211
raise errors.NoSuchFile(path)
1212
self._versioned_dirs = None
1218
def update_basis_by_delta(self, revid, delta):
1219
# TODO(jelmer): This shouldn't be called, it's inventory specific.
1220
for (old_path, new_path, file_id, ie) in delta:
1221
if old_path is not None:
1222
(index, old_subpath) = self._lookup_index(
1223
old_path.encode('utf-8'))
1224
if old_subpath in index:
1225
self._index_del_entry(index, old_subpath)
1226
self._versioned_dirs = None
1227
if new_path is not None and ie.kind != 'directory':
1228
self._index_add_entry(new_path, ie.kind)
1230
self._set_merges_from_parent_ids([])
1232
def move(self, from_paths, to_dir=None, after=None):
1234
with self.lock_tree_write():
1235
to_abs = self.abspath(to_dir)
1236
if not os.path.isdir(to_abs):
1237
raise errors.BzrMoveFailedError('', to_dir,
1238
errors.NotADirectory(to_abs))
1240
for from_rel in from_paths:
1241
from_tail = os.path.split(from_rel)[-1]
1242
to_rel = os.path.join(to_dir, from_tail)
1243
self.rename_one(from_rel, to_rel, after=after)
1244
rename_tuples.append((from_rel, to_rel))
1246
return rename_tuples
1248
def rename_one(self, from_rel, to_rel, after=None):
1249
from_path = from_rel.encode("utf-8")
1250
to_rel, can_access = osutils.normalized_filename(to_rel)
1252
raise errors.InvalidNormalization(to_rel)
1253
to_path = to_rel.encode("utf-8")
1254
with self.lock_tree_write():
1256
# Perhaps it's already moved?
1258
not self.has_filename(from_rel) and
1259
self.has_filename(to_rel) and
1260
not self.is_versioned(to_rel))
1262
if not self.has_filename(to_rel):
1263
raise errors.BzrMoveFailedError(
1264
from_rel, to_rel, errors.NoSuchFile(to_rel))
1265
if self.basis_tree().is_versioned(to_rel):
1266
raise errors.BzrMoveFailedError(
1267
from_rel, to_rel, errors.AlreadyVersionedError(to_rel))
1269
kind = self.kind(to_rel)
1272
to_kind = self.kind(to_rel)
1273
except errors.NoSuchFile:
1274
exc_type = errors.BzrRenameFailedError
1277
exc_type = errors.BzrMoveFailedError
1278
if self.is_versioned(to_rel):
1279
raise exc_type(from_rel, to_rel,
1280
errors.AlreadyVersionedError(to_rel))
1281
if not self.has_filename(from_rel):
1282
raise errors.BzrMoveFailedError(
1283
from_rel, to_rel, errors.NoSuchFile(from_rel))
1284
kind = self.kind(from_rel)
1285
if not self.is_versioned(from_rel) and kind != 'directory':
1286
raise exc_type(from_rel, to_rel,
1287
errors.NotVersionedError(from_rel))
1288
if self.has_filename(to_rel):
1289
raise errors.RenameFailedFilesExist(
1290
from_rel, to_rel, errors.FileExists(to_rel))
1292
kind = self.kind(from_rel)
1294
if not after and kind != 'directory':
1295
(index, from_subpath) = self._lookup_index(from_path)
1296
if from_subpath not in index:
1298
raise errors.BzrMoveFailedError(
1300
errors.NotVersionedError(path=from_rel))
1304
self._rename_one(from_rel, to_rel)
1305
except OSError as e:
1306
if e.errno == errno.ENOENT:
1307
raise errors.BzrMoveFailedError(
1308
from_rel, to_rel, errors.NoSuchFile(to_rel))
1310
if kind != 'directory':
1311
(index, from_index_path) = self._lookup_index(from_path)
1313
self._index_del_entry(index, from_path)
1316
self._index_add_entry(to_rel, kind)
1318
todo = [(p, i) for (p, i) in self._recurse_index_entries()
1319
if p.startswith(from_path + b'/')]
1320
for child_path, child_value in todo:
1321
(child_to_index, child_to_index_path) = self._lookup_index(
1322
posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
1323
child_to_index[child_to_index_path] = child_value
1324
# TODO(jelmer): Mark individual index as dirty
1325
self._index_dirty = True
1326
(child_from_index, child_from_index_path) = self._lookup_index(
1328
self._index_del_entry(
1329
child_from_index, child_from_index_path)
1331
self._versioned_dirs = None
1334
def find_related_paths_across_trees(self, paths, trees=[],
1335
require_versioned=True):
1339
if require_versioned:
1340
trees = [self] + (trees if trees is not None else [])
1344
if t.is_versioned(p):
1349
raise errors.PathsNotVersionedError(unversioned)
1351
return filter(self.is_versioned, paths)
1353
def path_content_summary(self, path):
1354
"""See Tree.path_content_summary."""
1356
stat_result = self._lstat(path)
1357
except OSError as e:
1358
if getattr(e, 'errno', None) == errno.ENOENT:
1360
return ('missing', None, None, None)
1361
# propagate other errors
1363
kind = mode_kind(stat_result.st_mode)
1365
return self._file_content_summary(path, stat_result)
1366
elif kind == 'directory':
1367
# perhaps it looks like a plain directory, but it's really a
1369
if self._directory_is_tree_reference(path):
1370
kind = 'tree-reference'
1371
return kind, None, None, None
1372
elif kind == 'symlink':
1373
target = osutils.readlink(self.abspath(path))
1374
return ('symlink', None, None, target)
1376
return (kind, None, None, None)
1378
def kind(self, relpath):
1379
kind = osutils.file_kind(self.abspath(relpath))
1380
if kind == 'directory':
1381
(index, index_path) = self._lookup_index(relpath.encode('utf-8'))
1385
mode = index[index_path].mode
1389
if S_ISGITLINK(mode):
1390
return 'tree-reference'
1395
def _live_entry(self, relpath):
1396
raise NotImplementedError(self._live_entry)
1398
def get_transform(self, pb=None):
1399
from ..transform import TreeTransform
1400
return TreeTransform(self, pb=pb)
1404
class InterIndexGitTree(InterGitTrees):
1405
"""InterTree that works between a Git revision tree and an index."""
1407
def __init__(self, source, target):
1408
super(InterIndexGitTree, self).__init__(source, target)
1409
self._index = target.index
1412
def is_compatible(cls, source, target):
1413
return (isinstance(source, GitRevisionTree) and
1414
isinstance(target, MutableGitIndexTree))
1416
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1417
require_versioned=False, extra_trees=None,
1418
want_unversioned=False):
1419
trees = [self.source]
1420
if extra_trees is not None:
1421
trees.extend(extra_trees)
1422
if specific_files is not None:
1423
specific_files = self.target.find_related_paths_across_trees(
1424
specific_files, trees,
1425
require_versioned=require_versioned)
1426
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1427
with self.lock_read():
1428
return changes_between_git_tree_and_working_copy(
1429
self.source.store, self.source.tree,
1430
self.target, want_unchanged=want_unchanged,
1431
want_unversioned=want_unversioned)
1434
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
1437
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1438
want_unchanged=False,
1439
want_unversioned=False):
1440
"""Determine the changes between a git tree and a working tree with index.
1445
# Report dirified directories to commit_tree first, so that they can be
1446
# replaced with non-empty directories if they have contents.
1448
trust_executable = target._supports_executable()
1449
for path, index_entry in target._recurse_index_entries():
1451
live_entry = target._live_entry(path)
1452
except EnvironmentError as e:
1453
if e.errno == errno.ENOENT:
1454
# Entry was removed; keep it listed, but mark it as gone.
1455
blobs[path] = (ZERO_SHA, 0)
1456
elif e.errno == errno.EISDIR:
1457
# Backwards compatibility with Dulwich < 0.19.12;
1458
# newer versions of Dulwich return either an entry for the
1459
# submodule or None for directories.
1460
if S_ISGITLINK(index_entry.mode):
1461
blobs[path] = (index_entry.sha, index_entry.mode)
1463
# Entry was turned into a directory
1464
dirified.append((path, Tree().id, stat.S_IFDIR))
1465
store.add_object(Tree())
1469
if live_entry is None:
1470
# Entry was turned into a directory
1471
dirified.append((path, Tree().id, stat.S_IFDIR))
1472
store.add_object(Tree())
1474
mode = live_entry.mode
1475
if not trust_executable:
1476
if mode_is_executable(index_entry.mode):
1480
blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1481
if want_unversioned:
1482
for e in target.extras():
1483
st = target._lstat(e)
1485
np, accessible = osutils.normalized_filename(e)
1486
except UnicodeDecodeError:
1487
raise errors.BadFilenameEncoding(
1489
if stat.S_ISDIR(st.st_mode):
1492
blob = blob_from_path_and_stat(
1493
target.abspath(e).encode(osutils._fs_enc), st)
1494
store.add_object(blob)
1495
np = np.encode('utf-8')
1496
blobs[np] = (blob.id, cleanup_mode(st.st_mode))
1498
to_tree_sha = commit_tree(
1499
store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
1500
return store.tree_changes(
1501
from_tree_sha, to_tree_sha, include_trees=True,
1502
want_unchanged=want_unchanged, change_type_same=True), extras