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 get_root_id(self):
343
if self.tree is None:
345
return self.path2id("")
347
def has_or_had_id(self, file_id):
349
self.id2path(file_id)
350
except errors.NoSuchId:
354
def has_id(self, file_id):
356
path = self.id2path(file_id)
357
except errors.NoSuchId:
359
return self.has_filename(path)
361
def _lookup_path(self, path):
362
if self.tree is None:
363
raise errors.NoSuchFile(path)
365
(mode, hexsha) = tree_lookup_path(
366
self.store.__getitem__, self.tree, path.encode('utf-8'))
368
raise errors.NoSuchFile(self, path)
370
return (self.store, mode, hexsha)
372
def is_executable(self, path):
373
(store, mode, hexsha) = self._lookup_path(path)
375
# the tree root is a directory
377
return mode_is_executable(mode)
379
def kind(self, path):
380
(store, mode, hexsha) = self._lookup_path(path)
382
# the tree root is a directory
384
return mode_kind(mode)
386
def has_filename(self, path):
388
self._lookup_path(path)
389
except errors.NoSuchFile:
394
def list_files(self, include_root=False, from_dir=None, recursive=True):
395
if self.tree is None:
397
if from_dir is None or from_dir == '.':
399
(store, mode, hexsha) = self._lookup_path(from_dir)
400
if mode is None: # Root
401
root_ie = self._get_dir_ie(b"", None)
403
parent_path = posixpath.dirname(from_dir)
404
parent_id = self._fileid_map.lookup_file_id(parent_path)
405
if mode_kind(mode) == 'directory':
406
root_ie = self._get_dir_ie(from_dir.encode("utf-8"), parent_id)
408
root_ie = self._get_file_ie(
409
store, from_dir.encode("utf-8"),
410
posixpath.basename(from_dir), mode, hexsha)
412
yield (from_dir, "V", root_ie.kind, root_ie)
414
if root_ie.kind == 'directory':
415
todo.append((store, from_dir.encode("utf-8"),
416
b"", hexsha, root_ie.file_id))
418
(store, path, relpath, hexsha, parent_id) = todo.pop()
420
for name, mode, hexsha in tree.iteritems():
421
if self.mapping.is_special_file(name):
423
child_path = posixpath.join(path, name)
424
child_relpath = posixpath.join(relpath, name)
425
if stat.S_ISDIR(mode):
426
ie = self._get_dir_ie(child_path, parent_id)
429
(store, child_path, child_relpath, hexsha,
432
ie = self._get_file_ie(
433
store, child_path, name, mode, hexsha, parent_id)
434
yield (child_relpath.decode('utf-8'), "V", ie.kind, ie)
436
def _get_file_ie(self, store, path, name, mode, hexsha, parent_id):
437
if not isinstance(path, bytes):
438
raise TypeError(path)
439
if not isinstance(name, bytes):
440
raise TypeError(name)
441
kind = mode_kind(mode)
442
path = path.decode('utf-8')
443
name = name.decode("utf-8")
444
file_id = self._fileid_map.lookup_file_id(path)
445
ie = entry_factory[kind](file_id, name, parent_id)
446
if kind == 'symlink':
447
ie.symlink_target = store[hexsha].data.decode('utf-8')
448
elif kind == 'tree-reference':
449
ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(
452
data = store[hexsha].data
453
ie.text_sha1 = osutils.sha_string(data)
454
ie.text_size = len(data)
455
ie.executable = mode_is_executable(mode)
458
def _get_dir_ie(self, path, parent_id):
459
path = path.decode('utf-8')
460
file_id = self._fileid_map.lookup_file_id(path)
461
return GitTreeDirectory(file_id, posixpath.basename(path), parent_id)
463
def iter_child_entries(self, path):
464
(store, mode, tree_sha) = self._lookup_path(path)
466
if mode is not None and not stat.S_ISDIR(mode):
469
encoded_path = path.encode('utf-8')
470
file_id = self.path2id(path)
471
tree = store[tree_sha]
472
for name, mode, hexsha in tree.iteritems():
473
if self.mapping.is_special_file(name):
475
child_path = posixpath.join(encoded_path, name)
476
if stat.S_ISDIR(mode):
477
yield self._get_dir_ie(child_path, file_id)
479
yield self._get_file_ie(store, child_path, name, mode, hexsha,
482
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
483
if self.tree is None:
486
# TODO(jelmer): Support yield parents
487
raise NotImplementedError
488
if specific_files is not None:
489
if specific_files in ([""], []):
490
specific_files = None
492
specific_files = set([p.encode('utf-8')
493
for p in specific_files])
494
todo = deque([(self.store, b"", self.tree, self.get_root_id())])
495
if specific_files is None or u"" in specific_files:
496
yield u"", self._get_dir_ie(b"", None)
498
store, path, tree_sha, parent_id = todo.popleft()
499
tree = store[tree_sha]
501
for name, mode, hexsha in tree.iteritems():
502
if self.mapping.is_special_file(name):
504
child_path = posixpath.join(path, name)
505
child_path_decoded = child_path.decode('utf-8')
506
if stat.S_ISDIR(mode):
507
if (specific_files is None or
508
any([p for p in specific_files if p.startswith(
511
(store, child_path, hexsha,
512
self.path2id(child_path_decoded)))
513
if specific_files is None or child_path in specific_files:
514
if stat.S_ISDIR(mode):
515
yield (child_path_decoded,
516
self._get_dir_ie(child_path, parent_id))
518
yield (child_path_decoded,
519
self._get_file_ie(store, child_path, name, mode,
521
todo.extendleft(reversed(extradirs))
523
def iter_references(self):
524
if self.supports_tree_reference():
525
for path, entry in self.iter_entries_by_dir():
526
if entry.kind == 'tree-reference':
527
yield path, self.mapping.generate_file_id(b'')
529
def get_revision_id(self):
530
"""See RevisionTree.get_revision_id."""
531
return self._revision_id
533
def get_file_sha1(self, path, stat_value=None):
534
if self.tree is None:
535
raise errors.NoSuchFile(path)
536
return osutils.sha_string(self.get_file_text(path))
538
def get_file_verifier(self, path, stat_value=None):
539
(store, mode, hexsha) = self._lookup_path(path)
540
return ("GIT", hexsha)
542
def get_file_size(self, path):
543
(store, mode, hexsha) = self._lookup_path(path)
544
if stat.S_ISREG(mode):
545
return len(store[hexsha].data)
548
def get_file_text(self, path):
549
"""See RevisionTree.get_file_text."""
550
(store, mode, hexsha) = self._lookup_path(path)
551
if stat.S_ISREG(mode):
552
return store[hexsha].data
556
def get_symlink_target(self, path):
557
"""See RevisionTree.get_symlink_target."""
558
(store, mode, hexsha) = self._lookup_path(path)
559
if stat.S_ISLNK(mode):
560
return store[hexsha].data.decode('utf-8')
564
def get_reference_revision(self, path):
565
"""See RevisionTree.get_symlink_target."""
566
(store, mode, hexsha) = self._lookup_path(path)
567
if S_ISGITLINK(mode):
568
nested_repo = self._get_nested_repository(path)
569
return nested_repo.lookup_foreign_revision_id(hexsha)
573
def _comparison_data(self, entry, path):
575
return None, False, None
576
return entry.kind, entry.executable, None
578
def path_content_summary(self, path):
579
"""See Tree.path_content_summary."""
581
(store, mode, hexsha) = self._lookup_path(path)
582
except errors.NoSuchFile:
583
return ('missing', None, None, None)
584
kind = mode_kind(mode)
586
executable = mode_is_executable(mode)
587
contents = store[hexsha].data
588
return (kind, len(contents), executable,
589
osutils.sha_string(contents))
590
elif kind == 'symlink':
591
return (kind, None, None, store[hexsha].data.decode('utf-8'))
592
elif kind == 'tree-reference':
593
nested_repo = self._get_nested_repository(path)
594
return (kind, None, None,
595
nested_repo.lookup_foreign_revision_id(hexsha))
597
return (kind, None, None, None)
599
def find_related_paths_across_trees(self, paths, trees=[],
600
require_versioned=True):
603
if require_versioned:
604
trees = [self] + (trees if trees is not None else [])
608
if t.is_versioned(p):
613
raise errors.PathsNotVersionedError(unversioned)
614
return filter(self.is_versioned, paths)
616
def _iter_tree_contents(self, include_trees=False):
617
if self.tree is None:
619
return self.store.iter_tree_contents(
620
self.tree, include_trees=include_trees)
622
def annotate_iter(self, path, default_revision=CURRENT_REVISION):
623
"""Return an iterator of revision_id, line tuples.
625
For working trees (and mutable trees in general), the special
626
revision_id 'current:' will be used for lines that are new in this
627
tree, e.g. uncommitted changes.
628
:param default_revision: For lines that don't match a basis, mark them
629
with this revision id. Not all implementations will make use of
632
with self.lock_read():
633
# Now we have the parents of this content
634
from breezy.annotate import Annotator
635
from .annotate import AnnotateProvider
636
annotator = Annotator(AnnotateProvider(
637
self._repository._file_change_scanner))
638
this_key = (path, self.get_file_revision(path))
639
annotations = [(key[-1], line)
640
for key, line in annotator.annotate_flat(this_key)]
643
def _get_rules_searcher(self, default_searcher):
644
return default_searcher
646
def walkdirs(self, prefix=u""):
647
(store, mode, hexsha) = self._lookup_path(prefix)
649
[(store, prefix.encode('utf-8'), hexsha, self.path2id(prefix))])
651
store, path, tree_sha, parent_id = todo.popleft()
652
path_decoded = path.decode('utf-8')
653
tree = store[tree_sha]
655
for name, mode, hexsha in tree.iteritems():
656
if self.mapping.is_special_file(name):
658
child_path = posixpath.join(path, name)
659
file_id = self.path2id(child_path.decode('utf-8'))
660
if stat.S_ISDIR(mode):
661
todo.append((store, child_path, hexsha, file_id))
663
(child_path.decode('utf-8'), name.decode('utf-8'),
664
mode_kind(mode), None,
665
file_id, mode_kind(mode)))
666
yield (path_decoded, parent_id), children
669
def tree_delta_from_git_changes(changes, mapping,
670
fileid_maps, specific_files=None,
671
require_versioned=False, include_root=False,
673
"""Create a TreeDelta from two git trees.
675
source and target are iterators over tuples with:
676
(filename, sha, mode)
678
(old_fileid_map, new_fileid_map) = fileid_maps
679
if target_extras is None:
680
target_extras = set()
681
ret = delta.TreeDelta()
683
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
684
if newpath == b'' and not include_root:
687
oldpath_decoded = None
689
oldpath_decoded = oldpath.decode('utf-8')
691
newpath_decoded = None
693
newpath_decoded = newpath.decode('utf-8')
694
if not (specific_files is None or
695
(oldpath is not None and
696
osutils.is_inside_or_parent_of_any(
697
specific_files, oldpath_decoded)) or
698
(newpath is not None and
699
osutils.is_inside_or_parent_of_any(
700
specific_files, newpath_decoded))):
702
if mapping.is_special_file(oldpath):
704
if mapping.is_special_file(newpath):
706
if oldpath is None and newpath is None:
709
added.append((newpath, mode_kind(newmode)))
710
elif newpath is None or newmode == 0:
711
file_id = old_fileid_map.lookup_file_id(oldpath_decoded)
712
ret.removed.append((oldpath_decoded, file_id, mode_kind(oldmode)))
713
elif oldpath != newpath:
714
file_id = old_fileid_map.lookup_file_id(oldpath_decoded)
716
(oldpath_decoded, newpath.decode('utf-8'), file_id,
717
mode_kind(newmode), (oldsha != newsha),
718
(oldmode != newmode)))
719
elif mode_kind(oldmode) != mode_kind(newmode):
720
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
721
ret.kind_changed.append(
722
(newpath_decoded, file_id, mode_kind(oldmode),
724
elif oldsha != newsha or oldmode != newmode:
725
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
727
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
729
(newpath_decoded, file_id, mode_kind(newmode),
730
(oldsha != newsha), (oldmode != newmode)))
732
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
733
ret.unchanged.append(
734
(newpath_decoded, file_id, mode_kind(newmode)))
736
implicit_dirs = {b''}
737
for path, kind in added:
738
if kind == 'directory' or path in target_extras:
740
implicit_dirs.update(osutils.parent_directories(path))
742
for path, kind in added:
743
if kind == 'directory' and path not in implicit_dirs:
745
path_decoded = osutils.normalized_filename(path)[0]
746
if path in target_extras:
747
ret.unversioned.append((path_decoded, None, kind))
749
file_id = new_fileid_map.lookup_file_id(path_decoded)
750
ret.added.append((path_decoded, file_id, kind))
755
def changes_from_git_changes(changes, mapping, specific_files=None,
756
include_unchanged=False, target_extras=None):
757
"""Create a iter_changes-like generator from a git stream.
759
source and target are iterators over tuples with:
760
(filename, sha, mode)
762
if target_extras is None:
763
target_extras = set()
764
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
765
if oldpath is not None:
766
oldpath_decoded = oldpath.decode('utf-8')
768
oldpath_decoded = None
769
if newpath is not None:
770
newpath_decoded = newpath.decode('utf-8')
772
newpath_decoded = None
773
if not (specific_files is None or
774
(oldpath_decoded is not None and
775
osutils.is_inside_or_parent_of_any(
776
specific_files, oldpath_decoded)) or
777
(newpath_decoded is not None and
778
osutils.is_inside_or_parent_of_any(
779
specific_files, newpath_decoded))):
781
if oldpath is not None and mapping.is_special_file(oldpath):
783
if newpath is not None and mapping.is_special_file(newpath):
785
if oldpath_decoded is None:
786
fileid = mapping.generate_file_id(newpath_decoded)
795
oldexe = mode_is_executable(oldmode)
796
oldkind = mode_kind(oldmode)
800
if oldpath_decoded == u'':
804
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
805
oldparent = mapping.generate_file_id(oldparentpath)
806
fileid = mapping.generate_file_id(oldpath_decoded)
807
if newpath_decoded is None:
814
newversioned = (newpath_decoded not in target_extras)
816
newexe = mode_is_executable(newmode)
817
newkind = mode_kind(newmode)
821
if newpath_decoded == u'':
825
newparentpath, newname = osutils.split(newpath_decoded)
826
newparent = mapping.generate_file_id(newparentpath)
827
if (not include_unchanged and
828
oldkind == 'directory' and newkind == 'directory' and
829
oldpath_decoded == newpath_decoded):
831
yield _mod_tree.TreeChange(
832
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
833
(oldversioned, newversioned),
834
(oldparent, newparent), (oldname, newname),
835
(oldkind, newkind), (oldexe, newexe))
838
class InterGitTrees(_mod_tree.InterTree):
839
"""InterTree that works between two git trees."""
841
_matching_from_tree_format = None
842
_matching_to_tree_format = None
843
_test_mutable_trees_to_test_trees = None
846
def is_compatible(cls, source, target):
847
return (isinstance(source, GitRevisionTree) and
848
isinstance(target, GitRevisionTree))
850
def compare(self, want_unchanged=False, specific_files=None,
851
extra_trees=None, require_versioned=False, include_root=False,
852
want_unversioned=False):
853
with self.lock_read():
854
changes, target_extras = self._iter_git_changes(
855
want_unchanged=want_unchanged,
856
require_versioned=require_versioned,
857
specific_files=specific_files,
858
extra_trees=extra_trees,
859
want_unversioned=want_unversioned)
860
source_fileid_map = self.source._fileid_map
861
target_fileid_map = self.target._fileid_map
862
return tree_delta_from_git_changes(
863
changes, self.target.mapping,
864
(source_fileid_map, target_fileid_map),
865
specific_files=specific_files,
866
include_root=include_root, target_extras=target_extras)
868
def iter_changes(self, include_unchanged=False, specific_files=None,
869
pb=None, extra_trees=[], require_versioned=True,
870
want_unversioned=False):
871
with self.lock_read():
872
changes, target_extras = self._iter_git_changes(
873
want_unchanged=include_unchanged,
874
require_versioned=require_versioned,
875
specific_files=specific_files,
876
extra_trees=extra_trees,
877
want_unversioned=want_unversioned)
878
return changes_from_git_changes(
879
changes, self.target.mapping,
880
specific_files=specific_files,
881
include_unchanged=include_unchanged,
882
target_extras=target_extras)
884
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
885
require_versioned=False, extra_trees=None,
886
want_unversioned=False):
887
raise NotImplementedError(self._iter_git_changes)
890
class InterGitRevisionTrees(InterGitTrees):
891
"""InterTree that works between two git revision trees."""
893
_matching_from_tree_format = None
894
_matching_to_tree_format = None
895
_test_mutable_trees_to_test_trees = None
898
def is_compatible(cls, source, target):
899
return (isinstance(source, GitRevisionTree) and
900
isinstance(target, GitRevisionTree))
902
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
903
require_versioned=True, extra_trees=None,
904
want_unversioned=False):
905
trees = [self.source]
906
if extra_trees is not None:
907
trees.extend(extra_trees)
908
if specific_files is not None:
909
specific_files = self.target.find_related_paths_across_trees(
910
specific_files, trees,
911
require_versioned=require_versioned)
913
if (self.source._repository._git.object_store !=
914
self.target._repository._git.object_store):
915
store = OverlayObjectStore(
916
[self.source._repository._git.object_store,
917
self.target._repository._git.object_store])
919
store = self.source._repository._git.object_store
920
return store.tree_changes(
921
self.source.tree, self.target.tree, want_unchanged=want_unchanged,
922
include_trees=True, change_type_same=True), set()
925
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
928
class MutableGitIndexTree(mutabletree.MutableTree):
931
self._lock_mode = None
933
self._versioned_dirs = None
934
self._index_dirty = False
936
def is_versioned(self, path):
937
with self.lock_read():
938
path = path.rstrip('/').encode('utf-8')
939
(index, subpath) = self._lookup_index(path)
940
return (subpath in index or self._has_dir(path))
942
def _has_dir(self, path):
943
if not isinstance(path, bytes):
944
raise TypeError(path)
947
if self._versioned_dirs is None:
949
return path in self._versioned_dirs
951
def _load_dirs(self):
952
if self._lock_mode is None:
953
raise errors.ObjectNotLocked(self)
954
self._versioned_dirs = set()
955
# TODO(jelmer): Browse over all indexes
956
for p, i in self._recurse_index_entries():
957
self._ensure_versioned_dir(posixpath.dirname(p))
959
def _ensure_versioned_dir(self, dirname):
960
if not isinstance(dirname, bytes):
961
raise TypeError(dirname)
962
if dirname in self._versioned_dirs:
965
self._ensure_versioned_dir(posixpath.dirname(dirname))
966
self._versioned_dirs.add(dirname)
968
def path2id(self, path):
969
with self.lock_read():
970
path = path.rstrip('/')
971
if self.is_versioned(path.rstrip('/')):
972
return self._fileid_map.lookup_file_id(
973
osutils.safe_unicode(path))
976
def has_id(self, file_id):
978
self.id2path(file_id)
979
except errors.NoSuchId:
984
def id2path(self, file_id):
987
if type(file_id) is not bytes:
988
raise TypeError(file_id)
989
with self.lock_read():
991
path = self._fileid_map.lookup_path(file_id)
993
raise errors.NoSuchId(self, file_id)
994
if self.is_versioned(path):
996
raise errors.NoSuchId(self, file_id)
998
def _set_root_id(self, file_id):
999
raise errors.UnsupportedOperation(self._set_root_id, self)
1001
def get_root_id(self):
1002
return self.path2id(u"")
1004
def _add(self, files, ids, kinds):
1005
for (path, file_id, kind) in zip(files, ids, kinds):
1006
if file_id is not None:
1007
raise workingtree.SettingFileIdUnsupported()
1008
path, can_access = osutils.normalized_filename(path)
1010
raise errors.InvalidNormalization(path)
1011
self._index_add_entry(path, kind)
1013
def _read_submodule_head(self, path):
1014
raise NotImplementedError(self._read_submodule_head)
1016
def _lookup_index(self, encoded_path):
1017
if not isinstance(encoded_path, bytes):
1018
raise TypeError(encoded_path)
1019
# TODO(jelmer): Look in other indexes
1020
return self.index, encoded_path
1022
def _index_del_entry(self, index, path):
1024
# TODO(jelmer): Keep track of dirty per index
1025
self._index_dirty = True
1027
def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
1028
if kind == "directory":
1029
# Git indexes don't contain directories
1034
file, stat_val = self.get_file_with_stat(path)
1035
except (errors.NoSuchFile, IOError):
1036
# TODO: Rather than come up with something here, use the old
1039
stat_val = os.stat_result(
1040
(stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1042
blob.set_raw_string(file.read())
1043
# Add object to the repository if it didn't exist yet
1044
if blob.id not in self.store:
1045
self.store.add_object(blob)
1047
elif kind == "symlink":
1050
stat_val = self._lstat(path)
1051
except EnvironmentError:
1052
# TODO: Rather than come up with something here, use the
1054
stat_val = os.stat_result(
1055
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1056
blob.set_raw_string(
1057
self.get_symlink_target(path).encode("utf-8"))
1058
# Add object to the repository if it didn't exist yet
1059
if blob.id not in self.store:
1060
self.store.add_object(blob)
1062
elif kind == "tree-reference":
1063
if reference_revision is not None:
1064
hexsha = self.branch.lookup_bzr_revision_id(
1065
reference_revision)[0]
1067
hexsha = self._read_submodule_head(path)
1069
raise errors.NoCommits(path)
1071
stat_val = self._lstat(path)
1072
except EnvironmentError:
1073
stat_val = os.stat_result(
1074
(S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1075
stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
1077
raise AssertionError("unknown kind '%s'" % kind)
1078
# Add an entry to the index or update the existing entry
1079
ensure_normalized_path(path)
1080
encoded_path = path.encode("utf-8")
1081
if b'\r' in encoded_path or b'\n' in encoded_path:
1082
# TODO(jelmer): Why do we need to do this?
1083
trace.mutter('ignoring path with invalid newline in it: %r', path)
1085
(index, index_path) = self._lookup_index(encoded_path)
1086
index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
1087
self._index_dirty = True
1088
if self._versioned_dirs is not None:
1089
self._ensure_versioned_dir(index_path)
1091
def _recurse_index_entries(self, index=None, basepath=b""):
1092
# Iterate over all index entries
1093
with self.lock_read():
1096
for path, value in index.items():
1097
yield (posixpath.join(basepath, path), value)
1098
(ctime, mtime, dev, ino, mode, uid, gid, size, sha,
1100
if S_ISGITLINK(mode):
1101
pass # TODO(jelmer): dive into submodule
1103
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
1105
raise NotImplementedError(self.iter_entries_by_dir)
1106
with self.lock_read():
1107
if specific_files is not None:
1108
specific_files = set(specific_files)
1110
specific_files = None
1111
root_ie = self._get_dir_ie(u"", None)
1113
if specific_files is None or u"" in specific_files:
1114
ret[(u"", u"")] = root_ie
1115
dir_ids = {u"": root_ie.file_id}
1116
for path, value in self._recurse_index_entries():
1117
if self.mapping.is_special_file(path):
1119
path = path.decode("utf-8")
1120
if specific_files is not None and path not in specific_files:
1122
(parent, name) = posixpath.split(path)
1124
file_ie = self._get_file_ie(name, path, value, None)
1125
except errors.NoSuchFile:
1127
if yield_parents or specific_files is None:
1128
for (dir_path, dir_ie) in self._add_missing_parent_ids(
1130
ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
1131
file_ie.parent_id = self.path2id(parent)
1132
ret[(posixpath.dirname(path), path)] = file_ie
1133
return ((path, ie) for ((_, path), ie) in sorted(viewitems(ret)))
1135
def iter_references(self):
1136
# TODO(jelmer): Implement a more efficient version of this
1137
for path, entry in self.iter_entries_by_dir():
1138
if entry.kind == 'tree-reference':
1139
yield path, self.mapping.generate_file_id(b'')
1141
def _get_dir_ie(self, path, parent_id):
1142
file_id = self.path2id(path)
1143
return GitTreeDirectory(file_id,
1144
posixpath.basename(path).strip("/"), parent_id)
1146
def _get_file_ie(self, name, path, value, parent_id):
1147
if not isinstance(name, text_type):
1148
raise TypeError(name)
1149
if not isinstance(path, text_type):
1150
raise TypeError(path)
1151
if not isinstance(value, tuple) or len(value) != 10:
1152
raise TypeError(value)
1153
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1154
file_id = self.path2id(path)
1155
if not isinstance(file_id, bytes):
1156
raise TypeError(file_id)
1157
kind = mode_kind(mode)
1158
ie = entry_factory[kind](file_id, name, parent_id)
1159
if kind == 'symlink':
1160
ie.symlink_target = self.get_symlink_target(path)
1161
elif kind == 'tree-reference':
1162
ie.reference_revision = self.get_reference_revision(path)
1165
data = self.get_file_text(path)
1166
except errors.NoSuchFile:
1168
except IOError as e:
1169
if e.errno != errno.ENOENT:
1173
data = self.branch.repository._git.object_store[sha].data
1174
ie.text_sha1 = osutils.sha_string(data)
1175
ie.text_size = len(data)
1176
ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1179
def _add_missing_parent_ids(self, path, dir_ids):
1182
parent = posixpath.dirname(path).strip("/")
1183
ret = self._add_missing_parent_ids(parent, dir_ids)
1184
parent_id = dir_ids[parent]
1185
ie = self._get_dir_ie(path, parent_id)
1186
dir_ids[path] = ie.file_id
1187
ret.append((path, ie))
1190
def _comparison_data(self, entry, path):
1192
return None, False, None
1193
return entry.kind, entry.executable, None
1195
def _unversion_path(self, path):
1196
if self._lock_mode is None:
1197
raise errors.ObjectNotLocked(self)
1198
encoded_path = path.encode("utf-8")
1200
(index, subpath) = self._lookup_index(encoded_path)
1202
self._index_del_entry(index, encoded_path)
1204
# A directory, perhaps?
1205
# TODO(jelmer): Deletes that involve submodules?
1206
for p in list(index):
1207
if p.startswith(subpath + b"/"):
1209
self._index_del_entry(index, p)
1212
self._versioned_dirs = None
1215
def unversion(self, paths):
1216
with self.lock_tree_write():
1218
if self._unversion_path(path) == 0:
1219
raise errors.NoSuchFile(path)
1220
self._versioned_dirs = None
1226
def update_basis_by_delta(self, revid, delta):
1227
# TODO(jelmer): This shouldn't be called, it's inventory specific.
1228
for (old_path, new_path, file_id, ie) in delta:
1229
if old_path is not None:
1230
(index, old_subpath) = self._lookup_index(
1231
old_path.encode('utf-8'))
1232
if old_subpath in index:
1233
self._index_del_entry(index, old_subpath)
1234
self._versioned_dirs = None
1235
if new_path is not None and ie.kind != 'directory':
1236
self._index_add_entry(new_path, ie.kind)
1238
self._set_merges_from_parent_ids([])
1240
def move(self, from_paths, to_dir=None, after=None):
1242
with self.lock_tree_write():
1243
to_abs = self.abspath(to_dir)
1244
if not os.path.isdir(to_abs):
1245
raise errors.BzrMoveFailedError('', to_dir,
1246
errors.NotADirectory(to_abs))
1248
for from_rel in from_paths:
1249
from_tail = os.path.split(from_rel)[-1]
1250
to_rel = os.path.join(to_dir, from_tail)
1251
self.rename_one(from_rel, to_rel, after=after)
1252
rename_tuples.append((from_rel, to_rel))
1254
return rename_tuples
1256
def rename_one(self, from_rel, to_rel, after=None):
1257
from_path = from_rel.encode("utf-8")
1258
to_rel, can_access = osutils.normalized_filename(to_rel)
1260
raise errors.InvalidNormalization(to_rel)
1261
to_path = to_rel.encode("utf-8")
1262
with self.lock_tree_write():
1264
# Perhaps it's already moved?
1266
not self.has_filename(from_rel) and
1267
self.has_filename(to_rel) and
1268
not self.is_versioned(to_rel))
1270
if not self.has_filename(to_rel):
1271
raise errors.BzrMoveFailedError(
1272
from_rel, to_rel, errors.NoSuchFile(to_rel))
1273
if self.basis_tree().is_versioned(to_rel):
1274
raise errors.BzrMoveFailedError(
1275
from_rel, to_rel, errors.AlreadyVersionedError(to_rel))
1277
kind = self.kind(to_rel)
1280
to_kind = self.kind(to_rel)
1281
except errors.NoSuchFile:
1282
exc_type = errors.BzrRenameFailedError
1285
exc_type = errors.BzrMoveFailedError
1286
if self.is_versioned(to_rel):
1287
raise exc_type(from_rel, to_rel,
1288
errors.AlreadyVersionedError(to_rel))
1289
if not self.has_filename(from_rel):
1290
raise errors.BzrMoveFailedError(
1291
from_rel, to_rel, errors.NoSuchFile(from_rel))
1292
kind = self.kind(from_rel)
1293
if not self.is_versioned(from_rel) and kind != 'directory':
1294
raise exc_type(from_rel, to_rel,
1295
errors.NotVersionedError(from_rel))
1296
if self.has_filename(to_rel):
1297
raise errors.RenameFailedFilesExist(
1298
from_rel, to_rel, errors.FileExists(to_rel))
1300
kind = self.kind(from_rel)
1302
if not after and kind != 'directory':
1303
(index, from_subpath) = self._lookup_index(from_path)
1304
if from_subpath not in index:
1306
raise errors.BzrMoveFailedError(
1308
errors.NotVersionedError(path=from_rel))
1312
self._rename_one(from_rel, to_rel)
1313
except OSError as e:
1314
if e.errno == errno.ENOENT:
1315
raise errors.BzrMoveFailedError(
1316
from_rel, to_rel, errors.NoSuchFile(to_rel))
1318
if kind != 'directory':
1319
(index, from_index_path) = self._lookup_index(from_path)
1321
self._index_del_entry(index, from_path)
1324
self._index_add_entry(to_rel, kind)
1326
todo = [(p, i) for (p, i) in self._recurse_index_entries()
1327
if p.startswith(from_path + b'/')]
1328
for child_path, child_value in todo:
1329
(child_to_index, child_to_index_path) = self._lookup_index(
1330
posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
1331
child_to_index[child_to_index_path] = child_value
1332
# TODO(jelmer): Mark individual index as dirty
1333
self._index_dirty = True
1334
(child_from_index, child_from_index_path) = self._lookup_index(
1336
self._index_del_entry(
1337
child_from_index, child_from_index_path)
1339
self._versioned_dirs = None
1342
def find_related_paths_across_trees(self, paths, trees=[],
1343
require_versioned=True):
1347
if require_versioned:
1348
trees = [self] + (trees if trees is not None else [])
1352
if t.is_versioned(p):
1357
raise errors.PathsNotVersionedError(unversioned)
1359
return filter(self.is_versioned, paths)
1361
def path_content_summary(self, path):
1362
"""See Tree.path_content_summary."""
1364
stat_result = self._lstat(path)
1365
except OSError as e:
1366
if getattr(e, 'errno', None) == errno.ENOENT:
1368
return ('missing', None, None, None)
1369
# propagate other errors
1371
kind = mode_kind(stat_result.st_mode)
1373
return self._file_content_summary(path, stat_result)
1374
elif kind == 'directory':
1375
# perhaps it looks like a plain directory, but it's really a
1377
if self._directory_is_tree_reference(path):
1378
kind = 'tree-reference'
1379
return kind, None, None, None
1380
elif kind == 'symlink':
1381
target = osutils.readlink(self.abspath(path))
1382
return ('symlink', None, None, target)
1384
return (kind, None, None, None)
1386
def kind(self, relpath):
1387
kind = osutils.file_kind(self.abspath(relpath))
1388
if kind == 'directory':
1389
(index, index_path) = self._lookup_index(relpath.encode('utf-8'))
1393
mode = index[index_path].mode
1397
if S_ISGITLINK(mode):
1398
return 'tree-reference'
1403
def _live_entry(self, relpath):
1404
raise NotImplementedError(self._live_entry)
1407
class InterIndexGitTree(InterGitTrees):
1408
"""InterTree that works between a Git revision tree and an index."""
1410
def __init__(self, source, target):
1411
super(InterIndexGitTree, self).__init__(source, target)
1412
self._index = target.index
1415
def is_compatible(cls, source, target):
1416
return (isinstance(source, GitRevisionTree) and
1417
isinstance(target, MutableGitIndexTree))
1419
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1420
require_versioned=False, extra_trees=None,
1421
want_unversioned=False):
1422
trees = [self.source]
1423
if extra_trees is not None:
1424
trees.extend(extra_trees)
1425
if specific_files is not None:
1426
specific_files = self.target.find_related_paths_across_trees(
1427
specific_files, trees,
1428
require_versioned=require_versioned)
1429
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1430
with self.lock_read():
1431
return changes_between_git_tree_and_working_copy(
1432
self.source.store, self.source.tree,
1433
self.target, want_unchanged=want_unchanged,
1434
want_unversioned=want_unversioned)
1437
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
1440
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1441
want_unchanged=False,
1442
want_unversioned=False):
1443
"""Determine the changes between a git tree and a working tree with index.
1448
# Report dirified directories to commit_tree first, so that they can be
1449
# replaced with non-empty directories if they have contents.
1451
trust_executable = target._supports_executable()
1452
for path, index_entry in target._recurse_index_entries():
1454
live_entry = target._live_entry(path)
1455
except EnvironmentError as e:
1456
if e.errno == errno.ENOENT:
1457
# Entry was removed; keep it listed, but mark it as gone.
1458
blobs[path] = (ZERO_SHA, 0)
1459
elif e.errno == errno.EISDIR:
1460
# Backwards compatibility with Dulwich < 0.19.12;
1461
# newer versions of Dulwich return either an entry for the
1462
# submodule or None for directories.
1463
if S_ISGITLINK(index_entry.mode):
1464
blobs[path] = (index_entry.sha, index_entry.mode)
1466
# Entry was turned into a directory
1467
dirified.append((path, Tree().id, stat.S_IFDIR))
1468
store.add_object(Tree())
1472
if live_entry is None:
1473
# Entry was turned into a directory
1474
dirified.append((path, Tree().id, stat.S_IFDIR))
1475
store.add_object(Tree())
1477
mode = live_entry.mode
1478
if not trust_executable:
1479
if mode_is_executable(index_entry.mode):
1483
blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1484
if want_unversioned:
1485
for e in target.extras():
1486
st = target._lstat(e)
1488
np, accessible = osutils.normalized_filename(e)
1489
except UnicodeDecodeError:
1490
raise errors.BadFilenameEncoding(
1492
if stat.S_ISDIR(st.st_mode):
1495
blob = blob_from_path_and_stat(
1496
target.abspath(e).encode(osutils._fs_enc), st)
1497
store.add_object(blob)
1498
np = np.encode('utf-8')
1499
blobs[np] = (blob.id, cleanup_mode(st.st_mode))
1501
to_tree_sha = commit_tree(
1502
store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
1503
return store.tree_changes(
1504
from_tree_sha, to_tree_sha, include_trees=True,
1505
want_unchanged=want_unchanged, change_type_same=True), extras