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 (
74
class GitTreeDirectory(_mod_tree.TreeDirectory):
76
__slots__ = ['file_id', 'name', 'parent_id', 'children']
78
def __init__(self, file_id, name, parent_id):
79
self.file_id = file_id
81
self.parent_id = parent_id
94
return self.__class__(
95
self.file_id, self.name, self.parent_id)
98
return "%s(file_id=%r, name=%r, parent_id=%r)" % (
99
self.__class__.__name__, self.file_id, self.name,
102
def __eq__(self, other):
103
return (self.kind == other.kind and
104
self.file_id == other.file_id and
105
self.name == other.name and
106
self.parent_id == other.parent_id)
109
class GitTreeFile(_mod_tree.TreeFile):
111
__slots__ = ['file_id', 'name', 'parent_id', 'text_size', 'text_sha1',
114
def __init__(self, file_id, name, parent_id, text_size=None,
115
text_sha1=None, executable=None):
116
self.file_id = file_id
118
self.parent_id = parent_id
119
self.text_size = text_size
120
self.text_sha1 = text_sha1
121
self.executable = executable
127
def __eq__(self, other):
128
return (self.kind == other.kind and
129
self.file_id == other.file_id and
130
self.name == other.name and
131
self.parent_id == other.parent_id and
132
self.text_sha1 == other.text_sha1 and
133
self.text_size == other.text_size and
134
self.executable == other.executable)
137
return ("%s(file_id=%r, name=%r, parent_id=%r, text_size=%r, "
138
"text_sha1=%r, executable=%r)") % (
139
type(self).__name__, self.file_id, self.name, self.parent_id,
140
self.text_size, self.text_sha1, self.executable)
143
ret = self.__class__(
144
self.file_id, self.name, self.parent_id)
145
ret.text_sha1 = self.text_sha1
146
ret.text_size = self.text_size
147
ret.executable = self.executable
151
class GitTreeSymlink(_mod_tree.TreeLink):
153
__slots__ = ['file_id', 'name', 'parent_id', 'symlink_target']
155
def __init__(self, file_id, name, parent_id,
156
symlink_target=None):
157
self.file_id = file_id
159
self.parent_id = parent_id
160
self.symlink_target = symlink_target
167
def executable(self):
175
return "%s(file_id=%r, name=%r, parent_id=%r, symlink_target=%r)" % (
176
type(self).__name__, self.file_id, self.name, self.parent_id,
179
def __eq__(self, other):
180
return (self.kind == other.kind and
181
self.file_id == other.file_id and
182
self.name == other.name and
183
self.parent_id == other.parent_id and
184
self.symlink_target == other.symlink_target)
187
return self.__class__(
188
self.file_id, self.name, self.parent_id,
192
class GitTreeSubmodule(_mod_tree.TreeLink):
194
__slots__ = ['file_id', 'name', 'parent_id', 'reference_revision']
196
def __init__(self, file_id, name, parent_id, reference_revision=None):
197
self.file_id = file_id
199
self.parent_id = parent_id
200
self.reference_revision = reference_revision
204
return 'tree-reference'
207
return ("%s(file_id=%r, name=%r, parent_id=%r, "
208
"reference_revision=%r)") % (
209
type(self).__name__, self.file_id, self.name, self.parent_id,
210
self.reference_revision)
212
def __eq__(self, other):
213
return (self.kind == other.kind and
214
self.file_id == other.file_id and
215
self.name == other.name and
216
self.parent_id == other.parent_id and
217
self.reference_revision == other.reference_revision)
220
return self.__class__(
221
self.file_id, self.name, self.parent_id,
222
self.reference_revision)
226
'directory': GitTreeDirectory,
228
'symlink': GitTreeSymlink,
229
'tree-reference': GitTreeSubmodule,
233
def ensure_normalized_path(path):
234
"""Check whether path is normalized.
236
:raises InvalidNormalization: When path is not normalized, and cannot be
237
accessed on this platform by the normalized path.
238
:return: The NFC normalised version of path.
240
norm_path, can_access = osutils.normalized_filename(path)
241
if norm_path != path:
245
raise errors.InvalidNormalization(path)
249
class GitRevisionTree(revisiontree.RevisionTree):
250
"""Revision tree implementation based on Git objects."""
252
def __init__(self, repository, revision_id):
253
self._revision_id = revision_id
254
self._repository = repository
255
self._submodules = None
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
266
commit = self.store[self.commit_id]
268
raise errors.NoSuchRevision(repository, revision_id)
269
self.tree = commit.tree
271
def _submodule_info(self):
272
if self._submodules is None:
274
with self.get_file('.gitmodules') as f:
275
config = GitConfigFile.from_file(f)
278
for path, url, section in parse_submodules(config)}
279
except errors.NoSuchFile:
280
self._submodules = {}
281
return self._submodules
283
def _get_submodule_repository(self, relpath):
284
if not isinstance(relpath, bytes):
285
raise TypeError(relpath)
287
info = self._submodule_info()[relpath]
289
nested_repo_transport = self._repository.user_transport.clone(relpath.decode('utf-8'))
291
nested_repo_transport = self._repository.control_transport.clone(
292
posixpath.join('modules', info[0]))
293
nested_controldir = _mod_controldir.ControlDir.open_from_transport(
294
nested_repo_transport)
295
return nested_controldir.find_repository()
297
def get_nested_tree(self, path):
298
encoded_path = path.encode('utf-8')
299
nested_repo = self._get_submodule_repository(encoded_path)
300
ref_rev = self.get_reference_revision(path)
301
return nested_repo.revision_tree(ref_rev)
303
def supports_rename_tracking(self):
306
def get_file_revision(self, path):
307
change_scanner = self._repository._file_change_scanner
308
if self.commit_id == ZERO_SHA:
310
(unused_path, commit_id) = change_scanner.find_last_change_revision(
311
path.encode('utf-8'), self.commit_id)
312
return self._repository.lookup_foreign_revision_id(
313
commit_id, self.mapping)
315
def get_file_mtime(self, path):
317
revid = self.get_file_revision(path)
319
raise errors.NoSuchFile(path)
321
rev = self._repository.get_revision(revid)
322
except errors.NoSuchRevision:
323
raise _mod_tree.FileTimestampUnavailable(path)
326
def id2path(self, file_id):
328
path = self.mapping.parse_file_id(file_id)
330
raise errors.NoSuchId(self, file_id)
331
if self.is_versioned(path):
333
raise errors.NoSuchId(self, file_id)
335
def is_versioned(self, path):
336
return self.has_filename(path)
338
def path2id(self, path):
339
if self.mapping.is_special_file(path):
341
if not self.is_versioned(path):
343
return self.mapping.generate_file_id(osutils.safe_unicode(path))
345
def all_file_ids(self):
346
raise errors.UnsupportedOperation(self.all_file_ids, self)
348
def all_versioned_paths(self):
350
todo = [(self.store, b'', self.tree)]
352
(store, path, tree_id) = todo.pop()
355
tree = store[tree_id]
356
for name, mode, hexsha in tree.items():
357
subpath = posixpath.join(path, name)
358
ret.add(subpath.decode('utf-8'))
359
if stat.S_ISDIR(mode):
360
todo.append((store, subpath, hexsha))
363
def _lookup_path(self, path):
364
if self.tree is None:
365
raise errors.NoSuchFile(path)
367
(mode, hexsha) = tree_lookup_path(
368
self.store.__getitem__, self.tree, path.encode('utf-8'))
370
raise errors.NoSuchFile(self, path)
372
return (self.store, mode, hexsha)
374
def is_executable(self, path):
375
(store, mode, hexsha) = self._lookup_path(path)
377
# the tree root is a directory
379
return mode_is_executable(mode)
381
def kind(self, path):
382
(store, mode, hexsha) = self._lookup_path(path)
384
# the tree root is a directory
386
return mode_kind(mode)
388
def has_filename(self, path):
390
self._lookup_path(path)
391
except errors.NoSuchFile:
396
def list_files(self, include_root=False, from_dir=None, recursive=True):
397
if self.tree is None:
399
if from_dir is None or from_dir == '.':
401
(store, mode, hexsha) = self._lookup_path(from_dir)
402
if mode is None: # Root
403
root_ie = self._get_dir_ie(b"", None)
405
parent_path = posixpath.dirname(from_dir)
406
parent_id = self.mapping.generate_file_id(parent_path)
407
if mode_kind(mode) == 'directory':
408
root_ie = self._get_dir_ie(from_dir.encode("utf-8"), parent_id)
410
root_ie = self._get_file_ie(
411
store, from_dir.encode("utf-8"),
412
posixpath.basename(from_dir), mode, hexsha)
414
yield (from_dir, "V", root_ie.kind, root_ie)
416
if root_ie.kind == 'directory':
417
todo.append((store, from_dir.encode("utf-8"),
418
b"", hexsha, root_ie.file_id))
420
(store, path, relpath, hexsha, parent_id) = todo.pop()
422
for name, mode, hexsha in tree.iteritems():
423
if self.mapping.is_special_file(name):
425
child_path = posixpath.join(path, name)
426
child_relpath = posixpath.join(relpath, name)
427
if stat.S_ISDIR(mode):
428
ie = self._get_dir_ie(child_path, parent_id)
431
(store, child_path, child_relpath, hexsha,
434
ie = self._get_file_ie(
435
store, child_path, name, mode, hexsha, parent_id)
436
yield (child_relpath.decode('utf-8'), "V", ie.kind, ie)
438
def _get_file_ie(self, store, path, name, mode, hexsha, parent_id):
439
if not isinstance(path, bytes):
440
raise TypeError(path)
441
if not isinstance(name, bytes):
442
raise TypeError(name)
443
kind = mode_kind(mode)
444
path = path.decode('utf-8')
445
name = name.decode("utf-8")
446
file_id = self.mapping.generate_file_id(path)
447
ie = entry_factory[kind](file_id, name, parent_id)
448
if kind == 'symlink':
449
ie.symlink_target = store[hexsha].data.decode('utf-8')
450
elif kind == 'tree-reference':
451
ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(
454
data = store[hexsha].data
455
ie.text_sha1 = osutils.sha_string(data)
456
ie.text_size = len(data)
457
ie.executable = mode_is_executable(mode)
460
def _get_dir_ie(self, path, parent_id):
461
path = path.decode('utf-8')
462
file_id = self.mapping.generate_file_id(path)
463
return GitTreeDirectory(file_id, posixpath.basename(path), parent_id)
465
def iter_child_entries(self, path):
466
(store, mode, tree_sha) = self._lookup_path(path)
468
if mode is not None and not stat.S_ISDIR(mode):
471
encoded_path = path.encode('utf-8')
472
file_id = self.path2id(path)
473
tree = store[tree_sha]
474
for name, mode, hexsha in tree.iteritems():
475
if self.mapping.is_special_file(name):
477
child_path = posixpath.join(encoded_path, name)
478
if stat.S_ISDIR(mode):
479
yield self._get_dir_ie(child_path, file_id)
481
yield self._get_file_ie(store, child_path, name, mode, hexsha,
484
def iter_entries_by_dir(self, specific_files=None):
485
if self.tree is None:
487
if specific_files is not None:
488
if specific_files in ([""], []):
489
specific_files = None
491
specific_files = set([p.encode('utf-8')
492
for p in specific_files])
493
todo = deque([(self.store, b"", self.tree, self.path2id(''))])
494
if specific_files is None or u"" in specific_files:
495
yield u"", self._get_dir_ie(b"", None)
497
store, path, tree_sha, parent_id = todo.popleft()
498
tree = store[tree_sha]
500
for name, mode, hexsha in tree.iteritems():
501
if self.mapping.is_special_file(name):
503
child_path = posixpath.join(path, name)
504
child_path_decoded = child_path.decode('utf-8')
505
if stat.S_ISDIR(mode):
506
if (specific_files is None or
507
any([p for p in specific_files if p.startswith(
510
(store, child_path, hexsha,
511
self.path2id(child_path_decoded)))
512
if specific_files is None or child_path in specific_files:
513
if stat.S_ISDIR(mode):
514
yield (child_path_decoded,
515
self._get_dir_ie(child_path, parent_id))
517
yield (child_path_decoded,
518
self._get_file_ie(store, child_path, name, mode,
520
todo.extendleft(reversed(extradirs))
522
def iter_references(self):
523
if self.supports_tree_reference():
524
for path, entry in self.iter_entries_by_dir():
525
if entry.kind == 'tree-reference':
528
def get_revision_id(self):
529
"""See RevisionTree.get_revision_id."""
530
return self._revision_id
532
def get_file_sha1(self, path, stat_value=None):
533
if self.tree is None:
534
raise errors.NoSuchFile(path)
535
return osutils.sha_string(self.get_file_text(path))
537
def get_file_verifier(self, path, stat_value=None):
538
(store, mode, hexsha) = self._lookup_path(path)
539
return ("GIT", hexsha)
541
def get_file_size(self, path):
542
(store, mode, hexsha) = self._lookup_path(path)
543
if stat.S_ISREG(mode):
544
return len(store[hexsha].data)
547
def get_file_text(self, path):
548
"""See RevisionTree.get_file_text."""
549
(store, mode, hexsha) = self._lookup_path(path)
550
if stat.S_ISREG(mode):
551
return store[hexsha].data
555
def get_symlink_target(self, path):
556
"""See RevisionTree.get_symlink_target."""
557
(store, mode, hexsha) = self._lookup_path(path)
558
if stat.S_ISLNK(mode):
559
return store[hexsha].data.decode('utf-8')
563
def get_reference_revision(self, path):
564
"""See RevisionTree.get_symlink_target."""
565
(store, mode, hexsha) = self._lookup_path(path)
566
if S_ISGITLINK(mode):
567
nested_repo = self._get_submodule_repository(path.encode('utf-8'))
568
return nested_repo.lookup_foreign_revision_id(hexsha)
572
def _comparison_data(self, entry, path):
574
return None, False, None
575
return entry.kind, entry.executable, None
577
def path_content_summary(self, path):
578
"""See Tree.path_content_summary."""
580
(store, mode, hexsha) = self._lookup_path(path)
581
except errors.NoSuchFile:
582
return ('missing', None, None, None)
583
kind = mode_kind(mode)
585
executable = mode_is_executable(mode)
586
contents = store[hexsha].data
587
return (kind, len(contents), executable,
588
osutils.sha_string(contents))
589
elif kind == 'symlink':
590
return (kind, None, None, store[hexsha].data.decode('utf-8'))
591
elif kind == 'tree-reference':
592
nested_repo = self._get_submodule_repository(path.encode('utf-8'))
593
return (kind, None, None,
594
nested_repo.lookup_foreign_revision_id(hexsha))
596
return (kind, None, None, None)
598
def find_related_paths_across_trees(self, paths, trees=[],
599
require_versioned=True):
602
if require_versioned:
603
trees = [self] + (trees if trees is not None else [])
607
if t.is_versioned(p):
612
raise errors.PathsNotVersionedError(unversioned)
613
return filter(self.is_versioned, paths)
615
def _iter_tree_contents(self, include_trees=False):
616
if self.tree is None:
618
return self.store.iter_tree_contents(
619
self.tree, include_trees=include_trees)
621
def annotate_iter(self, path, default_revision=CURRENT_REVISION):
622
"""Return an iterator of revision_id, line tuples.
624
For working trees (and mutable trees in general), the special
625
revision_id 'current:' will be used for lines that are new in this
626
tree, e.g. uncommitted changes.
627
:param default_revision: For lines that don't match a basis, mark them
628
with this revision id. Not all implementations will make use of
631
with self.lock_read():
632
# Now we have the parents of this content
633
from breezy.annotate import Annotator
634
from .annotate import AnnotateProvider
635
annotator = Annotator(AnnotateProvider(
636
self._repository._file_change_scanner))
637
this_key = (path, self.get_file_revision(path))
638
annotations = [(key[-1], line)
639
for key, line in annotator.annotate_flat(this_key)]
642
def _get_rules_searcher(self, default_searcher):
643
return default_searcher
645
def walkdirs(self, prefix=u""):
646
(store, mode, hexsha) = self._lookup_path(prefix)
648
[(store, prefix.encode('utf-8'), hexsha, self.path2id(prefix))])
650
store, path, tree_sha, parent_id = todo.popleft()
651
path_decoded = path.decode('utf-8')
652
tree = store[tree_sha]
654
for name, mode, hexsha in tree.iteritems():
655
if self.mapping.is_special_file(name):
657
child_path = posixpath.join(path, name)
658
file_id = self.path2id(child_path.decode('utf-8'))
659
if stat.S_ISDIR(mode):
660
todo.append((store, child_path, hexsha, file_id))
662
(child_path.decode('utf-8'), name.decode('utf-8'),
663
mode_kind(mode), None,
664
file_id, mode_kind(mode)))
665
yield (path_decoded, parent_id), children
668
def tree_delta_from_git_changes(changes, mappings,
670
require_versioned=False, include_root=False,
672
"""Create a TreeDelta from two git trees.
674
source and target are iterators over tuples with:
675
(filename, sha, mode)
677
(old_mapping, new_mapping) = mappings
678
if target_extras is None:
679
target_extras = set()
680
ret = delta.TreeDelta()
682
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
683
if newpath == b'' and not include_root:
685
if oldpath is not None:
686
oldpath_decoded = oldpath.decode('utf-8')
688
oldpath_decoded = None
689
if newpath is not None:
690
newpath_decoded = newpath.decode('utf-8')
692
newpath_decoded = None
693
if not (specific_files is None or
694
(oldpath is not None and
695
osutils.is_inside_or_parent_of_any(
696
specific_files, oldpath_decoded)) or
697
(newpath is not None and
698
osutils.is_inside_or_parent_of_any(
699
specific_files, newpath_decoded))):
702
if oldpath_decoded is None:
703
fileid = new_mapping.generate_file_id(newpath_decoded)
712
oldexe = mode_is_executable(oldmode)
713
oldkind = mode_kind(oldmode)
717
if oldpath_decoded == u'':
721
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
722
oldparent = old_mapping.generate_file_id(oldparentpath)
723
fileid = old_mapping.generate_file_id(oldpath_decoded)
724
if newpath_decoded is None:
731
newversioned = (newpath_decoded not in target_extras)
733
newexe = mode_is_executable(newmode)
734
newkind = mode_kind(newmode)
738
if newpath_decoded == u'':
742
newparentpath, newname = osutils.split(newpath_decoded)
743
newparent = new_mapping.generate_file_id(newparentpath)
744
if old_mapping.is_special_file(oldpath):
746
if new_mapping.is_special_file(newpath):
748
if oldpath is None and newpath is None:
750
change = _mod_tree.TreeChange(
751
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
752
(oldversioned, newversioned),
753
(oldparent, newparent), (oldname, newname),
754
(oldkind, newkind), (oldexe, newexe))
756
added.append((newpath, newkind))
757
elif newpath is None or newmode == 0:
758
ret.removed.append(change)
759
elif oldpath != newpath:
760
ret.renamed.append(change)
761
elif mode_kind(oldmode) != mode_kind(newmode):
762
ret.kind_changed.append(change)
763
elif oldsha != newsha or oldmode != newmode:
764
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
766
ret.modified.append(change)
768
ret.unchanged.append(change)
770
implicit_dirs = {b''}
771
for path, kind in added:
772
if kind == 'directory' or path in target_extras:
774
implicit_dirs.update(osutils.parent_directories(path))
776
for path, kind in added:
777
if kind == 'directory' and path not in implicit_dirs:
779
path_decoded = osutils.normalized_filename(path)[0]
780
parent_path, basename = osutils.split(path_decoded)
781
parent_id = new_mapping.generate_file_id(parent_path)
782
if path in target_extras:
783
ret.unversioned.append(_mod_tree.TreeChange(
784
None, (None, path_decoded),
785
True, (False, False), (None, parent_id),
786
(None, basename), (None, kind), (None, False)))
788
file_id = new_mapping.generate_file_id(path_decoded)
790
_mod_tree.TreeChange(
791
file_id, (None, path_decoded), True,
794
(None, basename), (None, kind), (None, False)))
799
def changes_from_git_changes(changes, mapping, specific_files=None,
800
include_unchanged=False, target_extras=None):
801
"""Create a iter_changes-like generator from a git stream.
803
source and target are iterators over tuples with:
804
(filename, sha, mode)
806
if target_extras is None:
807
target_extras = set()
808
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
809
if oldpath is not None:
810
oldpath_decoded = oldpath.decode('utf-8')
812
oldpath_decoded = None
813
if newpath is not None:
814
newpath_decoded = newpath.decode('utf-8')
816
newpath_decoded = None
817
if not (specific_files is None or
818
(oldpath_decoded is not None and
819
osutils.is_inside_or_parent_of_any(
820
specific_files, oldpath_decoded)) or
821
(newpath_decoded is not None and
822
osutils.is_inside_or_parent_of_any(
823
specific_files, newpath_decoded))):
825
if oldpath is not None and mapping.is_special_file(oldpath):
827
if newpath is not None and mapping.is_special_file(newpath):
829
if oldpath_decoded is None:
830
fileid = mapping.generate_file_id(newpath_decoded)
839
oldexe = mode_is_executable(oldmode)
840
oldkind = mode_kind(oldmode)
844
if oldpath_decoded == u'':
848
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
849
oldparent = mapping.generate_file_id(oldparentpath)
850
fileid = mapping.generate_file_id(oldpath_decoded)
851
if newpath_decoded is None:
858
newversioned = (newpath_decoded not in target_extras)
860
newexe = mode_is_executable(newmode)
861
newkind = mode_kind(newmode)
865
if newpath_decoded == u'':
869
newparentpath, newname = osutils.split(newpath_decoded)
870
newparent = mapping.generate_file_id(newparentpath)
871
if (not include_unchanged and
872
oldkind == 'directory' and newkind == 'directory' and
873
oldpath_decoded == newpath_decoded):
875
yield _mod_tree.TreeChange(
876
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
877
(oldversioned, newversioned),
878
(oldparent, newparent), (oldname, newname),
879
(oldkind, newkind), (oldexe, newexe))
882
class InterGitTrees(_mod_tree.InterTree):
883
"""InterTree that works between two git trees."""
885
_matching_from_tree_format = None
886
_matching_to_tree_format = None
887
_test_mutable_trees_to_test_trees = None
890
def is_compatible(cls, source, target):
891
return (isinstance(source, GitRevisionTree) and
892
isinstance(target, GitRevisionTree))
894
def compare(self, want_unchanged=False, specific_files=None,
895
extra_trees=None, require_versioned=False, include_root=False,
896
want_unversioned=False):
897
with self.lock_read():
898
changes, target_extras = self._iter_git_changes(
899
want_unchanged=want_unchanged,
900
require_versioned=require_versioned,
901
specific_files=specific_files,
902
extra_trees=extra_trees,
903
want_unversioned=want_unversioned)
904
return tree_delta_from_git_changes(
905
changes, (self.source.mapping, self.target.mapping),
906
specific_files=specific_files,
907
include_root=include_root, target_extras=target_extras)
909
def iter_changes(self, include_unchanged=False, specific_files=None,
910
pb=None, extra_trees=[], require_versioned=True,
911
want_unversioned=False):
912
with self.lock_read():
913
changes, target_extras = self._iter_git_changes(
914
want_unchanged=include_unchanged,
915
require_versioned=require_versioned,
916
specific_files=specific_files,
917
extra_trees=extra_trees,
918
want_unversioned=want_unversioned)
919
return changes_from_git_changes(
920
changes, self.target.mapping,
921
specific_files=specific_files,
922
include_unchanged=include_unchanged,
923
target_extras=target_extras)
925
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
926
require_versioned=False, extra_trees=None,
927
want_unversioned=False):
928
raise NotImplementedError(self._iter_git_changes)
931
class InterGitRevisionTrees(InterGitTrees):
932
"""InterTree that works between two git revision trees."""
934
_matching_from_tree_format = None
935
_matching_to_tree_format = None
936
_test_mutable_trees_to_test_trees = None
939
def is_compatible(cls, source, target):
940
return (isinstance(source, GitRevisionTree) and
941
isinstance(target, GitRevisionTree))
943
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
944
require_versioned=True, extra_trees=None,
945
want_unversioned=False):
946
trees = [self.source]
947
if extra_trees is not None:
948
trees.extend(extra_trees)
949
if specific_files is not None:
950
specific_files = self.target.find_related_paths_across_trees(
951
specific_files, trees,
952
require_versioned=require_versioned)
954
if (self.source._repository._git.object_store !=
955
self.target._repository._git.object_store):
956
store = OverlayObjectStore(
957
[self.source._repository._git.object_store,
958
self.target._repository._git.object_store])
960
store = self.source._repository._git.object_store
961
return store.tree_changes(
962
self.source.tree, self.target.tree, want_unchanged=want_unchanged,
963
include_trees=True, change_type_same=True), set()
966
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
969
class MutableGitIndexTree(mutabletree.MutableTree):
972
self._lock_mode = None
974
self._versioned_dirs = None
975
self._index_dirty = False
977
def is_versioned(self, path):
978
with self.lock_read():
979
path = path.rstrip('/').encode('utf-8')
980
(index, subpath) = self._lookup_index(path)
981
return (subpath in index or self._has_dir(path))
983
def _has_dir(self, path):
984
if not isinstance(path, bytes):
985
raise TypeError(path)
988
if self._versioned_dirs is None:
990
return path in self._versioned_dirs
992
def _load_dirs(self):
993
if self._lock_mode is None:
994
raise errors.ObjectNotLocked(self)
995
self._versioned_dirs = set()
996
# TODO(jelmer): Browse over all indexes
997
for p, i in self._recurse_index_entries():
998
self._ensure_versioned_dir(posixpath.dirname(p))
1000
def _ensure_versioned_dir(self, dirname):
1001
if not isinstance(dirname, bytes):
1002
raise TypeError(dirname)
1003
if dirname in self._versioned_dirs:
1006
self._ensure_versioned_dir(posixpath.dirname(dirname))
1007
self._versioned_dirs.add(dirname)
1009
def path2id(self, path):
1010
with self.lock_read():
1011
path = path.rstrip('/')
1012
if self.is_versioned(path.rstrip('/')):
1013
return self.mapping.generate_file_id(
1014
osutils.safe_unicode(path))
1017
def id2path(self, file_id):
1020
if type(file_id) is not bytes:
1021
raise TypeError(file_id)
1022
with self.lock_read():
1024
path = self.mapping.parse_file_id(file_id)
1026
raise errors.NoSuchId(self, file_id)
1027
if self.is_versioned(path):
1029
raise errors.NoSuchId(self, file_id)
1031
def _set_root_id(self, file_id):
1032
raise errors.UnsupportedOperation(self._set_root_id, self)
1034
def _add(self, files, ids, kinds):
1035
for (path, file_id, kind) in zip(files, ids, kinds):
1036
if file_id is not None:
1037
raise workingtree.SettingFileIdUnsupported()
1038
path, can_access = osutils.normalized_filename(path)
1040
raise errors.InvalidNormalization(path)
1041
self._index_add_entry(path, kind)
1043
def _read_submodule_head(self, path):
1044
raise NotImplementedError(self._read_submodule_head)
1046
def _lookup_index(self, encoded_path):
1047
if not isinstance(encoded_path, bytes):
1048
raise TypeError(encoded_path)
1049
# TODO(jelmer): Look in other indexes
1050
return self.index, encoded_path
1052
def _index_del_entry(self, index, path):
1054
# TODO(jelmer): Keep track of dirty per index
1055
self._index_dirty = True
1057
def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
1058
if kind == "directory":
1059
# Git indexes don't contain directories
1064
file, stat_val = self.get_file_with_stat(path)
1065
except (errors.NoSuchFile, IOError):
1066
# TODO: Rather than come up with something here, use the old
1069
stat_val = os.stat_result(
1070
(stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1072
blob.set_raw_string(file.read())
1073
# Add object to the repository if it didn't exist yet
1074
if blob.id not in self.store:
1075
self.store.add_object(blob)
1077
elif kind == "symlink":
1080
stat_val = self._lstat(path)
1081
except EnvironmentError:
1082
# TODO: Rather than come up with something here, use the
1084
stat_val = os.stat_result(
1085
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1086
blob.set_raw_string(
1087
self.get_symlink_target(path).encode("utf-8"))
1088
# Add object to the repository if it didn't exist yet
1089
if blob.id not in self.store:
1090
self.store.add_object(blob)
1092
elif kind == "tree-reference":
1093
if reference_revision is not None:
1094
hexsha = self.branch.lookup_bzr_revision_id(
1095
reference_revision)[0]
1097
hexsha = self._read_submodule_head(path)
1099
raise errors.NoCommits(path)
1101
stat_val = self._lstat(path)
1102
except EnvironmentError:
1103
stat_val = os.stat_result(
1104
(S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1105
stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
1107
raise AssertionError("unknown kind '%s'" % kind)
1108
# Add an entry to the index or update the existing entry
1109
ensure_normalized_path(path)
1110
encoded_path = path.encode("utf-8")
1111
if b'\r' in encoded_path or b'\n' in encoded_path:
1112
# TODO(jelmer): Why do we need to do this?
1113
trace.mutter('ignoring path with invalid newline in it: %r', path)
1115
(index, index_path) = self._lookup_index(encoded_path)
1116
index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
1117
self._index_dirty = True
1118
if self._versioned_dirs is not None:
1119
self._ensure_versioned_dir(index_path)
1121
def _recurse_index_entries(self, index=None, basepath=b""):
1122
# Iterate over all index entries
1123
with self.lock_read():
1126
for path, value in index.items():
1127
yield (posixpath.join(basepath, path), value)
1128
(ctime, mtime, dev, ino, mode, uid, gid, size, sha,
1130
if S_ISGITLINK(mode):
1131
pass # TODO(jelmer): dive into submodule
1133
def iter_entries_by_dir(self, specific_files=None):
1134
with self.lock_read():
1135
if specific_files is not None:
1136
specific_files = set(specific_files)
1138
specific_files = None
1139
root_ie = self._get_dir_ie(u"", None)
1141
if specific_files is None or u"" in specific_files:
1142
ret[(u"", u"")] = root_ie
1143
dir_ids = {u"": root_ie.file_id}
1144
for path, value in self._recurse_index_entries():
1145
if self.mapping.is_special_file(path):
1147
path = path.decode("utf-8")
1148
if specific_files is not None and path not in specific_files:
1150
(parent, name) = posixpath.split(path)
1152
file_ie = self._get_file_ie(name, path, value, None)
1153
except errors.NoSuchFile:
1155
if specific_files is None:
1156
for (dir_path, dir_ie) in self._add_missing_parent_ids(
1158
ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
1159
file_ie.parent_id = self.path2id(parent)
1160
ret[(posixpath.dirname(path), path)] = file_ie
1161
# Special casing for directories
1163
for path in specific_files:
1164
key = (posixpath.dirname(path), path)
1165
if key not in ret and self.is_versioned(path):
1166
ret[key] = self._get_dir_ie(path, self.path2id(key[0]))
1167
return ((path, ie) for ((_, path), ie) in sorted(viewitems(ret)))
1169
def iter_references(self):
1170
# TODO(jelmer): Implement a more efficient version of this
1171
for path, entry in self.iter_entries_by_dir():
1172
if entry.kind == 'tree-reference':
1175
def _get_dir_ie(self, path, parent_id):
1176
file_id = self.path2id(path)
1177
return GitTreeDirectory(file_id,
1178
posixpath.basename(path).strip("/"), parent_id)
1180
def _get_file_ie(self, name, path, value, parent_id):
1181
if not isinstance(name, text_type):
1182
raise TypeError(name)
1183
if not isinstance(path, text_type):
1184
raise TypeError(path)
1185
if not isinstance(value, tuple) or len(value) != 10:
1186
raise TypeError(value)
1187
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1188
file_id = self.path2id(path)
1189
if not isinstance(file_id, bytes):
1190
raise TypeError(file_id)
1191
kind = mode_kind(mode)
1192
ie = entry_factory[kind](file_id, name, parent_id)
1193
if kind == 'symlink':
1194
ie.symlink_target = self.get_symlink_target(path)
1195
elif kind == 'tree-reference':
1196
ie.reference_revision = self.get_reference_revision(path)
1199
data = self.get_file_text(path)
1200
except errors.NoSuchFile:
1202
except IOError as e:
1203
if e.errno != errno.ENOENT:
1207
data = self.branch.repository._git.object_store[sha].data
1208
ie.text_sha1 = osutils.sha_string(data)
1209
ie.text_size = len(data)
1210
ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1213
def _add_missing_parent_ids(self, path, dir_ids):
1216
parent = posixpath.dirname(path).strip("/")
1217
ret = self._add_missing_parent_ids(parent, dir_ids)
1218
parent_id = dir_ids[parent]
1219
ie = self._get_dir_ie(path, parent_id)
1220
dir_ids[path] = ie.file_id
1221
ret.append((path, ie))
1224
def _comparison_data(self, entry, path):
1226
return None, False, None
1227
return entry.kind, entry.executable, None
1229
def _unversion_path(self, path):
1230
if self._lock_mode is None:
1231
raise errors.ObjectNotLocked(self)
1232
encoded_path = path.encode("utf-8")
1234
(index, subpath) = self._lookup_index(encoded_path)
1236
self._index_del_entry(index, encoded_path)
1238
# A directory, perhaps?
1239
# TODO(jelmer): Deletes that involve submodules?
1240
for p in list(index):
1241
if p.startswith(subpath + b"/"):
1243
self._index_del_entry(index, p)
1246
self._versioned_dirs = None
1249
def unversion(self, paths):
1250
with self.lock_tree_write():
1252
if self._unversion_path(path) == 0:
1253
raise errors.NoSuchFile(path)
1254
self._versioned_dirs = None
1260
def update_basis_by_delta(self, revid, delta):
1261
# TODO(jelmer): This shouldn't be called, it's inventory specific.
1262
for (old_path, new_path, file_id, ie) in delta:
1263
if old_path is not None:
1264
(index, old_subpath) = self._lookup_index(
1265
old_path.encode('utf-8'))
1266
if old_subpath in index:
1267
self._index_del_entry(index, old_subpath)
1268
self._versioned_dirs = None
1269
if new_path is not None and ie.kind != 'directory':
1270
self._index_add_entry(new_path, ie.kind)
1272
self._set_merges_from_parent_ids([])
1274
def move(self, from_paths, to_dir=None, after=None):
1276
with self.lock_tree_write():
1277
to_abs = self.abspath(to_dir)
1278
if not os.path.isdir(to_abs):
1279
raise errors.BzrMoveFailedError('', to_dir,
1280
errors.NotADirectory(to_abs))
1282
for from_rel in from_paths:
1283
from_tail = os.path.split(from_rel)[-1]
1284
to_rel = os.path.join(to_dir, from_tail)
1285
self.rename_one(from_rel, to_rel, after=after)
1286
rename_tuples.append((from_rel, to_rel))
1288
return rename_tuples
1290
def rename_one(self, from_rel, to_rel, after=None):
1291
from_path = from_rel.encode("utf-8")
1292
to_rel, can_access = osutils.normalized_filename(to_rel)
1294
raise errors.InvalidNormalization(to_rel)
1295
to_path = to_rel.encode("utf-8")
1296
with self.lock_tree_write():
1298
# Perhaps it's already moved?
1300
not self.has_filename(from_rel) and
1301
self.has_filename(to_rel) and
1302
not self.is_versioned(to_rel))
1304
if not self.has_filename(to_rel):
1305
raise errors.BzrMoveFailedError(
1306
from_rel, to_rel, errors.NoSuchFile(to_rel))
1307
if self.basis_tree().is_versioned(to_rel):
1308
raise errors.BzrMoveFailedError(
1309
from_rel, to_rel, errors.AlreadyVersionedError(to_rel))
1311
kind = self.kind(to_rel)
1314
to_kind = self.kind(to_rel)
1315
except errors.NoSuchFile:
1316
exc_type = errors.BzrRenameFailedError
1319
exc_type = errors.BzrMoveFailedError
1320
if self.is_versioned(to_rel):
1321
raise exc_type(from_rel, to_rel,
1322
errors.AlreadyVersionedError(to_rel))
1323
if not self.has_filename(from_rel):
1324
raise errors.BzrMoveFailedError(
1325
from_rel, to_rel, errors.NoSuchFile(from_rel))
1326
kind = self.kind(from_rel)
1327
if not self.is_versioned(from_rel) and kind != 'directory':
1328
raise exc_type(from_rel, to_rel,
1329
errors.NotVersionedError(from_rel))
1330
if self.has_filename(to_rel):
1331
raise errors.RenameFailedFilesExist(
1332
from_rel, to_rel, errors.FileExists(to_rel))
1334
kind = self.kind(from_rel)
1336
if not after and kind != 'directory':
1337
(index, from_subpath) = self._lookup_index(from_path)
1338
if from_subpath not in index:
1340
raise errors.BzrMoveFailedError(
1342
errors.NotVersionedError(path=from_rel))
1346
self._rename_one(from_rel, to_rel)
1347
except OSError as e:
1348
if e.errno == errno.ENOENT:
1349
raise errors.BzrMoveFailedError(
1350
from_rel, to_rel, errors.NoSuchFile(to_rel))
1352
if kind != 'directory':
1353
(index, from_index_path) = self._lookup_index(from_path)
1355
self._index_del_entry(index, from_path)
1358
self._index_add_entry(to_rel, kind)
1360
todo = [(p, i) for (p, i) in self._recurse_index_entries()
1361
if p.startswith(from_path + b'/')]
1362
for child_path, child_value in todo:
1363
(child_to_index, child_to_index_path) = self._lookup_index(
1364
posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
1365
child_to_index[child_to_index_path] = child_value
1366
# TODO(jelmer): Mark individual index as dirty
1367
self._index_dirty = True
1368
(child_from_index, child_from_index_path) = self._lookup_index(
1370
self._index_del_entry(
1371
child_from_index, child_from_index_path)
1373
self._versioned_dirs = None
1376
def find_related_paths_across_trees(self, paths, trees=[],
1377
require_versioned=True):
1381
if require_versioned:
1382
trees = [self] + (trees if trees is not None else [])
1386
if t.is_versioned(p):
1391
raise errors.PathsNotVersionedError(unversioned)
1393
return filter(self.is_versioned, paths)
1395
def path_content_summary(self, path):
1396
"""See Tree.path_content_summary."""
1398
stat_result = self._lstat(path)
1399
except OSError as e:
1400
if getattr(e, 'errno', None) == errno.ENOENT:
1402
return ('missing', None, None, None)
1403
# propagate other errors
1405
kind = mode_kind(stat_result.st_mode)
1407
return self._file_content_summary(path, stat_result)
1408
elif kind == 'directory':
1409
# perhaps it looks like a plain directory, but it's really a
1411
if self._directory_is_tree_reference(path):
1412
kind = 'tree-reference'
1413
return kind, None, None, None
1414
elif kind == 'symlink':
1415
target = osutils.readlink(self.abspath(path))
1416
return ('symlink', None, None, target)
1418
return (kind, None, None, None)
1420
def kind(self, relpath):
1421
kind = osutils.file_kind(self.abspath(relpath))
1422
if kind == 'directory':
1423
(index, index_path) = self._lookup_index(relpath.encode('utf-8'))
1427
mode = index[index_path].mode
1431
if S_ISGITLINK(mode):
1432
return 'tree-reference'
1437
def _live_entry(self, relpath):
1438
raise NotImplementedError(self._live_entry)
1440
def get_transform(self, pb=None):
1441
from ..transform import TreeTransform
1442
return TreeTransform(self, pb=pb)
1446
class InterIndexGitTree(InterGitTrees):
1447
"""InterTree that works between a Git revision tree and an index."""
1449
def __init__(self, source, target):
1450
super(InterIndexGitTree, self).__init__(source, target)
1451
self._index = target.index
1454
def is_compatible(cls, source, target):
1455
return (isinstance(source, GitRevisionTree) and
1456
isinstance(target, MutableGitIndexTree))
1458
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1459
require_versioned=False, extra_trees=None,
1460
want_unversioned=False):
1461
trees = [self.source]
1462
if extra_trees is not None:
1463
trees.extend(extra_trees)
1464
if specific_files is not None:
1465
specific_files = self.target.find_related_paths_across_trees(
1466
specific_files, trees,
1467
require_versioned=require_versioned)
1468
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1469
with self.lock_read():
1470
return changes_between_git_tree_and_working_copy(
1471
self.source.store, self.source.tree,
1472
self.target, want_unchanged=want_unchanged,
1473
want_unversioned=want_unversioned)
1476
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
1479
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1480
want_unchanged=False,
1481
want_unversioned=False):
1482
"""Determine the changes between a git tree and a working tree with index.
1487
# Report dirified directories to commit_tree first, so that they can be
1488
# replaced with non-empty directories if they have contents.
1490
trust_executable = target._supports_executable()
1491
for path, index_entry in target._recurse_index_entries():
1493
live_entry = target._live_entry(path)
1494
except EnvironmentError as e:
1495
if e.errno == errno.ENOENT:
1496
# Entry was removed; keep it listed, but mark it as gone.
1497
blobs[path] = (ZERO_SHA, 0)
1498
elif e.errno == errno.EISDIR:
1499
# Backwards compatibility with Dulwich < 0.19.12;
1500
# newer versions of Dulwich return either an entry for the
1501
# submodule or None for directories.
1502
if S_ISGITLINK(index_entry.mode):
1503
blobs[path] = (index_entry.sha, index_entry.mode)
1505
# Entry was turned into a directory
1506
dirified.append((path, Tree().id, stat.S_IFDIR))
1507
store.add_object(Tree())
1511
if live_entry is None:
1512
# Entry was turned into a directory
1513
dirified.append((path, Tree().id, stat.S_IFDIR))
1514
store.add_object(Tree())
1516
mode = live_entry.mode
1517
if not trust_executable:
1518
if mode_is_executable(index_entry.mode):
1522
blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1523
if want_unversioned:
1524
for e in target.extras():
1525
st = target._lstat(e)
1527
np, accessible = osutils.normalized_filename(e)
1528
except UnicodeDecodeError:
1529
raise errors.BadFilenameEncoding(
1531
if stat.S_ISDIR(st.st_mode):
1534
blob = blob_from_path_and_stat(
1535
target.abspath(e).encode(osutils._fs_enc), st)
1536
store.add_object(blob)
1537
np = np.encode('utf-8')
1538
blobs[np] = (blob.id, cleanup_mode(st.st_mode))
1540
to_tree_sha = commit_tree(
1541
store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
1542
return store.tree_changes(
1543
from_tree_sha, to_tree_sha, include_trees=True,
1544
want_unchanged=want_unchanged, change_type_same=True), extras