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, yield_parents=False):
485
if self.tree is None:
488
# TODO(jelmer): Support yield parents
489
raise NotImplementedError
490
if specific_files is not None:
491
if specific_files in ([""], []):
492
specific_files = None
494
specific_files = set([p.encode('utf-8')
495
for p in specific_files])
496
todo = deque([(self.store, b"", self.tree, self.path2id(''))])
497
if specific_files is None or u"" in specific_files:
498
yield u"", self._get_dir_ie(b"", None)
500
store, path, tree_sha, parent_id = todo.popleft()
501
tree = store[tree_sha]
503
for name, mode, hexsha in tree.iteritems():
504
if self.mapping.is_special_file(name):
506
child_path = posixpath.join(path, name)
507
child_path_decoded = child_path.decode('utf-8')
508
if stat.S_ISDIR(mode):
509
if (specific_files is None or
510
any([p for p in specific_files if p.startswith(
513
(store, child_path, hexsha,
514
self.path2id(child_path_decoded)))
515
if specific_files is None or child_path in specific_files:
516
if stat.S_ISDIR(mode):
517
yield (child_path_decoded,
518
self._get_dir_ie(child_path, parent_id))
520
yield (child_path_decoded,
521
self._get_file_ie(store, child_path, name, mode,
523
todo.extendleft(reversed(extradirs))
525
def iter_references(self):
526
if self.supports_tree_reference():
527
for path, entry in self.iter_entries_by_dir():
528
if entry.kind == 'tree-reference':
531
def get_revision_id(self):
532
"""See RevisionTree.get_revision_id."""
533
return self._revision_id
535
def get_file_sha1(self, path, stat_value=None):
536
if self.tree is None:
537
raise errors.NoSuchFile(path)
538
return osutils.sha_string(self.get_file_text(path))
540
def get_file_verifier(self, path, stat_value=None):
541
(store, mode, hexsha) = self._lookup_path(path)
542
return ("GIT", hexsha)
544
def get_file_size(self, path):
545
(store, mode, hexsha) = self._lookup_path(path)
546
if stat.S_ISREG(mode):
547
return len(store[hexsha].data)
550
def get_file_text(self, path):
551
"""See RevisionTree.get_file_text."""
552
(store, mode, hexsha) = self._lookup_path(path)
553
if stat.S_ISREG(mode):
554
return store[hexsha].data
558
def get_symlink_target(self, path):
559
"""See RevisionTree.get_symlink_target."""
560
(store, mode, hexsha) = self._lookup_path(path)
561
if stat.S_ISLNK(mode):
562
return store[hexsha].data.decode('utf-8')
566
def get_reference_revision(self, path):
567
"""See RevisionTree.get_symlink_target."""
568
(store, mode, hexsha) = self._lookup_path(path)
569
if S_ISGITLINK(mode):
570
nested_repo = self._get_submodule_repository(path.encode('utf-8'))
571
return nested_repo.lookup_foreign_revision_id(hexsha)
575
def _comparison_data(self, entry, path):
577
return None, False, None
578
return entry.kind, entry.executable, None
580
def path_content_summary(self, path):
581
"""See Tree.path_content_summary."""
583
(store, mode, hexsha) = self._lookup_path(path)
584
except errors.NoSuchFile:
585
return ('missing', None, None, None)
586
kind = mode_kind(mode)
588
executable = mode_is_executable(mode)
589
contents = store[hexsha].data
590
return (kind, len(contents), executable,
591
osutils.sha_string(contents))
592
elif kind == 'symlink':
593
return (kind, None, None, store[hexsha].data.decode('utf-8'))
594
elif kind == 'tree-reference':
595
nested_repo = self._get_submodule_repository(path.encode('utf-8'))
596
return (kind, None, None,
597
nested_repo.lookup_foreign_revision_id(hexsha))
599
return (kind, None, None, None)
601
def find_related_paths_across_trees(self, paths, trees=[],
602
require_versioned=True):
605
if require_versioned:
606
trees = [self] + (trees if trees is not None else [])
610
if t.is_versioned(p):
615
raise errors.PathsNotVersionedError(unversioned)
616
return filter(self.is_versioned, paths)
618
def _iter_tree_contents(self, include_trees=False):
619
if self.tree is None:
621
return self.store.iter_tree_contents(
622
self.tree, include_trees=include_trees)
624
def annotate_iter(self, path, default_revision=CURRENT_REVISION):
625
"""Return an iterator of revision_id, line tuples.
627
For working trees (and mutable trees in general), the special
628
revision_id 'current:' will be used for lines that are new in this
629
tree, e.g. uncommitted changes.
630
:param default_revision: For lines that don't match a basis, mark them
631
with this revision id. Not all implementations will make use of
634
with self.lock_read():
635
# Now we have the parents of this content
636
from breezy.annotate import Annotator
637
from .annotate import AnnotateProvider
638
annotator = Annotator(AnnotateProvider(
639
self._repository._file_change_scanner))
640
this_key = (path, self.get_file_revision(path))
641
annotations = [(key[-1], line)
642
for key, line in annotator.annotate_flat(this_key)]
645
def _get_rules_searcher(self, default_searcher):
646
return default_searcher
648
def walkdirs(self, prefix=u""):
649
(store, mode, hexsha) = self._lookup_path(prefix)
651
[(store, prefix.encode('utf-8'), hexsha, self.path2id(prefix))])
653
store, path, tree_sha, parent_id = todo.popleft()
654
path_decoded = path.decode('utf-8')
655
tree = store[tree_sha]
657
for name, mode, hexsha in tree.iteritems():
658
if self.mapping.is_special_file(name):
660
child_path = posixpath.join(path, name)
661
file_id = self.path2id(child_path.decode('utf-8'))
662
if stat.S_ISDIR(mode):
663
todo.append((store, child_path, hexsha, file_id))
665
(child_path.decode('utf-8'), name.decode('utf-8'),
666
mode_kind(mode), None,
667
file_id, mode_kind(mode)))
668
yield (path_decoded, parent_id), children
671
def tree_delta_from_git_changes(changes, mappings,
673
require_versioned=False, include_root=False,
675
"""Create a TreeDelta from two git trees.
677
source and target are iterators over tuples with:
678
(filename, sha, mode)
680
(old_mapping, new_mapping) = mappings
681
if target_extras is None:
682
target_extras = set()
683
ret = delta.TreeDelta()
685
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
686
if newpath == b'' and not include_root:
688
if oldpath is not None:
689
oldpath_decoded = oldpath.decode('utf-8')
691
oldpath_decoded = None
692
if newpath is not None:
693
newpath_decoded = newpath.decode('utf-8')
695
newpath_decoded = None
696
if not (specific_files is None or
697
(oldpath is not None and
698
osutils.is_inside_or_parent_of_any(
699
specific_files, oldpath_decoded)) or
700
(newpath is not None and
701
osutils.is_inside_or_parent_of_any(
702
specific_files, newpath_decoded))):
705
if oldpath_decoded is None:
706
fileid = new_mapping.generate_file_id(newpath_decoded)
715
oldexe = mode_is_executable(oldmode)
716
oldkind = mode_kind(oldmode)
720
if oldpath_decoded == u'':
724
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
725
oldparent = old_mapping.generate_file_id(oldparentpath)
726
fileid = old_mapping.generate_file_id(oldpath_decoded)
727
if newpath_decoded is None:
734
newversioned = (newpath_decoded not in target_extras)
736
newexe = mode_is_executable(newmode)
737
newkind = mode_kind(newmode)
741
if newpath_decoded == u'':
745
newparentpath, newname = osutils.split(newpath_decoded)
746
newparent = new_mapping.generate_file_id(newparentpath)
747
if old_mapping.is_special_file(oldpath):
749
if new_mapping.is_special_file(newpath):
751
if oldpath is None and newpath is None:
753
change = _mod_tree.TreeChange(
754
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
755
(oldversioned, newversioned),
756
(oldparent, newparent), (oldname, newname),
757
(oldkind, newkind), (oldexe, newexe))
759
added.append((newpath, newkind))
760
elif newpath is None or newmode == 0:
761
ret.removed.append(change)
762
elif oldpath != newpath:
763
ret.renamed.append(change)
764
elif mode_kind(oldmode) != mode_kind(newmode):
765
ret.kind_changed.append(change)
766
elif oldsha != newsha or oldmode != newmode:
767
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
769
ret.modified.append(change)
771
ret.unchanged.append(change)
773
implicit_dirs = {b''}
774
for path, kind in added:
775
if kind == 'directory' or path in target_extras:
777
implicit_dirs.update(osutils.parent_directories(path))
779
for path, kind in added:
780
if kind == 'directory' and path not in implicit_dirs:
782
path_decoded = osutils.normalized_filename(path)[0]
783
parent_path, basename = osutils.split(path_decoded)
784
parent_id = new_mapping.generate_file_id(parent_path)
785
if path in target_extras:
786
ret.unversioned.append(_mod_tree.TreeChange(
787
None, (None, path_decoded),
788
True, (False, False), (None, parent_id),
789
(None, basename), (None, kind), (None, False)))
791
file_id = new_mapping.generate_file_id(path_decoded)
793
_mod_tree.TreeChange(
794
file_id, (None, path_decoded), True,
797
(None, basename), (None, kind), (None, False)))
802
def changes_from_git_changes(changes, mapping, specific_files=None,
803
include_unchanged=False, target_extras=None):
804
"""Create a iter_changes-like generator from a git stream.
806
source and target are iterators over tuples with:
807
(filename, sha, mode)
809
if target_extras is None:
810
target_extras = set()
811
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
812
if oldpath is not None:
813
oldpath_decoded = oldpath.decode('utf-8')
815
oldpath_decoded = None
816
if newpath is not None:
817
newpath_decoded = newpath.decode('utf-8')
819
newpath_decoded = None
820
if not (specific_files is None or
821
(oldpath_decoded is not None and
822
osutils.is_inside_or_parent_of_any(
823
specific_files, oldpath_decoded)) or
824
(newpath_decoded is not None and
825
osutils.is_inside_or_parent_of_any(
826
specific_files, newpath_decoded))):
828
if oldpath is not None and mapping.is_special_file(oldpath):
830
if newpath is not None and mapping.is_special_file(newpath):
832
if oldpath_decoded is None:
833
fileid = mapping.generate_file_id(newpath_decoded)
842
oldexe = mode_is_executable(oldmode)
843
oldkind = mode_kind(oldmode)
847
if oldpath_decoded == u'':
851
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
852
oldparent = mapping.generate_file_id(oldparentpath)
853
fileid = mapping.generate_file_id(oldpath_decoded)
854
if newpath_decoded is None:
861
newversioned = (newpath_decoded not in target_extras)
863
newexe = mode_is_executable(newmode)
864
newkind = mode_kind(newmode)
868
if newpath_decoded == u'':
872
newparentpath, newname = osutils.split(newpath_decoded)
873
newparent = mapping.generate_file_id(newparentpath)
874
if (not include_unchanged and
875
oldkind == 'directory' and newkind == 'directory' and
876
oldpath_decoded == newpath_decoded):
878
yield _mod_tree.TreeChange(
879
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
880
(oldversioned, newversioned),
881
(oldparent, newparent), (oldname, newname),
882
(oldkind, newkind), (oldexe, newexe))
885
class InterGitTrees(_mod_tree.InterTree):
886
"""InterTree that works between two git 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 compare(self, want_unchanged=False, specific_files=None,
898
extra_trees=None, require_versioned=False, include_root=False,
899
want_unversioned=False):
900
with self.lock_read():
901
changes, target_extras = self._iter_git_changes(
902
want_unchanged=want_unchanged,
903
require_versioned=require_versioned,
904
specific_files=specific_files,
905
extra_trees=extra_trees,
906
want_unversioned=want_unversioned)
907
return tree_delta_from_git_changes(
908
changes, (self.source.mapping, self.target.mapping),
909
specific_files=specific_files,
910
include_root=include_root, target_extras=target_extras)
912
def iter_changes(self, include_unchanged=False, specific_files=None,
913
pb=None, extra_trees=[], require_versioned=True,
914
want_unversioned=False):
915
with self.lock_read():
916
changes, target_extras = self._iter_git_changes(
917
want_unchanged=include_unchanged,
918
require_versioned=require_versioned,
919
specific_files=specific_files,
920
extra_trees=extra_trees,
921
want_unversioned=want_unversioned)
922
return changes_from_git_changes(
923
changes, self.target.mapping,
924
specific_files=specific_files,
925
include_unchanged=include_unchanged,
926
target_extras=target_extras)
928
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
929
require_versioned=False, extra_trees=None,
930
want_unversioned=False):
931
raise NotImplementedError(self._iter_git_changes)
934
class InterGitRevisionTrees(InterGitTrees):
935
"""InterTree that works between two git revision trees."""
937
_matching_from_tree_format = None
938
_matching_to_tree_format = None
939
_test_mutable_trees_to_test_trees = None
942
def is_compatible(cls, source, target):
943
return (isinstance(source, GitRevisionTree) and
944
isinstance(target, GitRevisionTree))
946
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
947
require_versioned=True, extra_trees=None,
948
want_unversioned=False):
949
trees = [self.source]
950
if extra_trees is not None:
951
trees.extend(extra_trees)
952
if specific_files is not None:
953
specific_files = self.target.find_related_paths_across_trees(
954
specific_files, trees,
955
require_versioned=require_versioned)
957
if (self.source._repository._git.object_store !=
958
self.target._repository._git.object_store):
959
store = OverlayObjectStore(
960
[self.source._repository._git.object_store,
961
self.target._repository._git.object_store])
963
store = self.source._repository._git.object_store
964
return store.tree_changes(
965
self.source.tree, self.target.tree, want_unchanged=want_unchanged,
966
include_trees=True, change_type_same=True), set()
969
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
972
class MutableGitIndexTree(mutabletree.MutableTree):
975
self._lock_mode = None
977
self._versioned_dirs = None
978
self._index_dirty = False
980
def is_versioned(self, path):
981
with self.lock_read():
982
path = path.rstrip('/').encode('utf-8')
983
(index, subpath) = self._lookup_index(path)
984
return (subpath in index or self._has_dir(path))
986
def _has_dir(self, path):
987
if not isinstance(path, bytes):
988
raise TypeError(path)
991
if self._versioned_dirs is None:
993
return path in self._versioned_dirs
995
def _load_dirs(self):
996
if self._lock_mode is None:
997
raise errors.ObjectNotLocked(self)
998
self._versioned_dirs = set()
999
# TODO(jelmer): Browse over all indexes
1000
for p, i in self._recurse_index_entries():
1001
self._ensure_versioned_dir(posixpath.dirname(p))
1003
def _ensure_versioned_dir(self, dirname):
1004
if not isinstance(dirname, bytes):
1005
raise TypeError(dirname)
1006
if dirname in self._versioned_dirs:
1009
self._ensure_versioned_dir(posixpath.dirname(dirname))
1010
self._versioned_dirs.add(dirname)
1012
def path2id(self, path):
1013
with self.lock_read():
1014
path = path.rstrip('/')
1015
if self.is_versioned(path.rstrip('/')):
1016
return self.mapping.generate_file_id(
1017
osutils.safe_unicode(path))
1020
def id2path(self, file_id):
1023
if type(file_id) is not bytes:
1024
raise TypeError(file_id)
1025
with self.lock_read():
1027
path = self.mapping.parse_file_id(file_id)
1029
raise errors.NoSuchId(self, file_id)
1030
if self.is_versioned(path):
1032
raise errors.NoSuchId(self, file_id)
1034
def _set_root_id(self, file_id):
1035
raise errors.UnsupportedOperation(self._set_root_id, self)
1037
def _add(self, files, ids, kinds):
1038
for (path, file_id, kind) in zip(files, ids, kinds):
1039
if file_id is not None:
1040
raise workingtree.SettingFileIdUnsupported()
1041
path, can_access = osutils.normalized_filename(path)
1043
raise errors.InvalidNormalization(path)
1044
self._index_add_entry(path, kind)
1046
def _read_submodule_head(self, path):
1047
raise NotImplementedError(self._read_submodule_head)
1049
def _lookup_index(self, encoded_path):
1050
if not isinstance(encoded_path, bytes):
1051
raise TypeError(encoded_path)
1052
# TODO(jelmer): Look in other indexes
1053
return self.index, encoded_path
1055
def _index_del_entry(self, index, path):
1057
# TODO(jelmer): Keep track of dirty per index
1058
self._index_dirty = True
1060
def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
1061
if kind == "directory":
1062
# Git indexes don't contain directories
1067
file, stat_val = self.get_file_with_stat(path)
1068
except (errors.NoSuchFile, IOError):
1069
# TODO: Rather than come up with something here, use the old
1072
stat_val = os.stat_result(
1073
(stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1075
blob.set_raw_string(file.read())
1076
# Add object to the repository if it didn't exist yet
1077
if blob.id not in self.store:
1078
self.store.add_object(blob)
1080
elif kind == "symlink":
1083
stat_val = self._lstat(path)
1084
except EnvironmentError:
1085
# TODO: Rather than come up with something here, use the
1087
stat_val = os.stat_result(
1088
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1089
blob.set_raw_string(
1090
self.get_symlink_target(path).encode("utf-8"))
1091
# Add object to the repository if it didn't exist yet
1092
if blob.id not in self.store:
1093
self.store.add_object(blob)
1095
elif kind == "tree-reference":
1096
if reference_revision is not None:
1097
hexsha = self.branch.lookup_bzr_revision_id(
1098
reference_revision)[0]
1100
hexsha = self._read_submodule_head(path)
1102
raise errors.NoCommits(path)
1104
stat_val = self._lstat(path)
1105
except EnvironmentError:
1106
stat_val = os.stat_result(
1107
(S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1108
stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
1110
raise AssertionError("unknown kind '%s'" % kind)
1111
# Add an entry to the index or update the existing entry
1112
ensure_normalized_path(path)
1113
encoded_path = path.encode("utf-8")
1114
if b'\r' in encoded_path or b'\n' in encoded_path:
1115
# TODO(jelmer): Why do we need to do this?
1116
trace.mutter('ignoring path with invalid newline in it: %r', path)
1118
(index, index_path) = self._lookup_index(encoded_path)
1119
index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
1120
self._index_dirty = True
1121
if self._versioned_dirs is not None:
1122
self._ensure_versioned_dir(index_path)
1124
def _recurse_index_entries(self, index=None, basepath=b""):
1125
# Iterate over all index entries
1126
with self.lock_read():
1129
for path, value in index.items():
1130
yield (posixpath.join(basepath, path), value)
1131
(ctime, mtime, dev, ino, mode, uid, gid, size, sha,
1133
if S_ISGITLINK(mode):
1134
pass # TODO(jelmer): dive into submodule
1136
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
1138
raise NotImplementedError(self.iter_entries_by_dir)
1139
with self.lock_read():
1140
if specific_files is not None:
1141
specific_files = set(specific_files)
1143
specific_files = None
1144
root_ie = self._get_dir_ie(u"", None)
1146
if specific_files is None or u"" in specific_files:
1147
ret[(u"", u"")] = root_ie
1148
dir_ids = {u"": root_ie.file_id}
1149
for path, value in self._recurse_index_entries():
1150
if self.mapping.is_special_file(path):
1152
path = path.decode("utf-8")
1153
if specific_files is not None and path not in specific_files:
1155
(parent, name) = posixpath.split(path)
1157
file_ie = self._get_file_ie(name, path, value, None)
1158
except errors.NoSuchFile:
1160
if yield_parents or specific_files is None:
1161
for (dir_path, dir_ie) in self._add_missing_parent_ids(
1163
ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
1164
file_ie.parent_id = self.path2id(parent)
1165
ret[(posixpath.dirname(path), path)] = file_ie
1166
return ((path, ie) for ((_, path), ie) in sorted(viewitems(ret)))
1168
def iter_references(self):
1169
# TODO(jelmer): Implement a more efficient version of this
1170
for path, entry in self.iter_entries_by_dir():
1171
if entry.kind == 'tree-reference':
1174
def _get_dir_ie(self, path, parent_id):
1175
file_id = self.path2id(path)
1176
return GitTreeDirectory(file_id,
1177
posixpath.basename(path).strip("/"), parent_id)
1179
def _get_file_ie(self, name, path, value, parent_id):
1180
if not isinstance(name, text_type):
1181
raise TypeError(name)
1182
if not isinstance(path, text_type):
1183
raise TypeError(path)
1184
if not isinstance(value, tuple) or len(value) != 10:
1185
raise TypeError(value)
1186
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1187
file_id = self.path2id(path)
1188
if not isinstance(file_id, bytes):
1189
raise TypeError(file_id)
1190
kind = mode_kind(mode)
1191
ie = entry_factory[kind](file_id, name, parent_id)
1192
if kind == 'symlink':
1193
ie.symlink_target = self.get_symlink_target(path)
1194
elif kind == 'tree-reference':
1195
ie.reference_revision = self.get_reference_revision(path)
1198
data = self.get_file_text(path)
1199
except errors.NoSuchFile:
1201
except IOError as e:
1202
if e.errno != errno.ENOENT:
1206
data = self.branch.repository._git.object_store[sha].data
1207
ie.text_sha1 = osutils.sha_string(data)
1208
ie.text_size = len(data)
1209
ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1212
def _add_missing_parent_ids(self, path, dir_ids):
1215
parent = posixpath.dirname(path).strip("/")
1216
ret = self._add_missing_parent_ids(parent, dir_ids)
1217
parent_id = dir_ids[parent]
1218
ie = self._get_dir_ie(path, parent_id)
1219
dir_ids[path] = ie.file_id
1220
ret.append((path, ie))
1223
def _comparison_data(self, entry, path):
1225
return None, False, None
1226
return entry.kind, entry.executable, None
1228
def _unversion_path(self, path):
1229
if self._lock_mode is None:
1230
raise errors.ObjectNotLocked(self)
1231
encoded_path = path.encode("utf-8")
1233
(index, subpath) = self._lookup_index(encoded_path)
1235
self._index_del_entry(index, encoded_path)
1237
# A directory, perhaps?
1238
# TODO(jelmer): Deletes that involve submodules?
1239
for p in list(index):
1240
if p.startswith(subpath + b"/"):
1242
self._index_del_entry(index, p)
1245
self._versioned_dirs = None
1248
def unversion(self, paths):
1249
with self.lock_tree_write():
1251
if self._unversion_path(path) == 0:
1252
raise errors.NoSuchFile(path)
1253
self._versioned_dirs = None
1259
def update_basis_by_delta(self, revid, delta):
1260
# TODO(jelmer): This shouldn't be called, it's inventory specific.
1261
for (old_path, new_path, file_id, ie) in delta:
1262
if old_path is not None:
1263
(index, old_subpath) = self._lookup_index(
1264
old_path.encode('utf-8'))
1265
if old_subpath in index:
1266
self._index_del_entry(index, old_subpath)
1267
self._versioned_dirs = None
1268
if new_path is not None and ie.kind != 'directory':
1269
self._index_add_entry(new_path, ie.kind)
1271
self._set_merges_from_parent_ids([])
1273
def move(self, from_paths, to_dir=None, after=None):
1275
with self.lock_tree_write():
1276
to_abs = self.abspath(to_dir)
1277
if not os.path.isdir(to_abs):
1278
raise errors.BzrMoveFailedError('', to_dir,
1279
errors.NotADirectory(to_abs))
1281
for from_rel in from_paths:
1282
from_tail = os.path.split(from_rel)[-1]
1283
to_rel = os.path.join(to_dir, from_tail)
1284
self.rename_one(from_rel, to_rel, after=after)
1285
rename_tuples.append((from_rel, to_rel))
1287
return rename_tuples
1289
def rename_one(self, from_rel, to_rel, after=None):
1290
from_path = from_rel.encode("utf-8")
1291
to_rel, can_access = osutils.normalized_filename(to_rel)
1293
raise errors.InvalidNormalization(to_rel)
1294
to_path = to_rel.encode("utf-8")
1295
with self.lock_tree_write():
1297
# Perhaps it's already moved?
1299
not self.has_filename(from_rel) and
1300
self.has_filename(to_rel) and
1301
not self.is_versioned(to_rel))
1303
if not self.has_filename(to_rel):
1304
raise errors.BzrMoveFailedError(
1305
from_rel, to_rel, errors.NoSuchFile(to_rel))
1306
if self.basis_tree().is_versioned(to_rel):
1307
raise errors.BzrMoveFailedError(
1308
from_rel, to_rel, errors.AlreadyVersionedError(to_rel))
1310
kind = self.kind(to_rel)
1313
to_kind = self.kind(to_rel)
1314
except errors.NoSuchFile:
1315
exc_type = errors.BzrRenameFailedError
1318
exc_type = errors.BzrMoveFailedError
1319
if self.is_versioned(to_rel):
1320
raise exc_type(from_rel, to_rel,
1321
errors.AlreadyVersionedError(to_rel))
1322
if not self.has_filename(from_rel):
1323
raise errors.BzrMoveFailedError(
1324
from_rel, to_rel, errors.NoSuchFile(from_rel))
1325
kind = self.kind(from_rel)
1326
if not self.is_versioned(from_rel) and kind != 'directory':
1327
raise exc_type(from_rel, to_rel,
1328
errors.NotVersionedError(from_rel))
1329
if self.has_filename(to_rel):
1330
raise errors.RenameFailedFilesExist(
1331
from_rel, to_rel, errors.FileExists(to_rel))
1333
kind = self.kind(from_rel)
1335
if not after and kind != 'directory':
1336
(index, from_subpath) = self._lookup_index(from_path)
1337
if from_subpath not in index:
1339
raise errors.BzrMoveFailedError(
1341
errors.NotVersionedError(path=from_rel))
1345
self._rename_one(from_rel, to_rel)
1346
except OSError as e:
1347
if e.errno == errno.ENOENT:
1348
raise errors.BzrMoveFailedError(
1349
from_rel, to_rel, errors.NoSuchFile(to_rel))
1351
if kind != 'directory':
1352
(index, from_index_path) = self._lookup_index(from_path)
1354
self._index_del_entry(index, from_path)
1357
self._index_add_entry(to_rel, kind)
1359
todo = [(p, i) for (p, i) in self._recurse_index_entries()
1360
if p.startswith(from_path + b'/')]
1361
for child_path, child_value in todo:
1362
(child_to_index, child_to_index_path) = self._lookup_index(
1363
posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
1364
child_to_index[child_to_index_path] = child_value
1365
# TODO(jelmer): Mark individual index as dirty
1366
self._index_dirty = True
1367
(child_from_index, child_from_index_path) = self._lookup_index(
1369
self._index_del_entry(
1370
child_from_index, child_from_index_path)
1372
self._versioned_dirs = None
1375
def find_related_paths_across_trees(self, paths, trees=[],
1376
require_versioned=True):
1380
if require_versioned:
1381
trees = [self] + (trees if trees is not None else [])
1385
if t.is_versioned(p):
1390
raise errors.PathsNotVersionedError(unversioned)
1392
return filter(self.is_versioned, paths)
1394
def path_content_summary(self, path):
1395
"""See Tree.path_content_summary."""
1397
stat_result = self._lstat(path)
1398
except OSError as e:
1399
if getattr(e, 'errno', None) == errno.ENOENT:
1401
return ('missing', None, None, None)
1402
# propagate other errors
1404
kind = mode_kind(stat_result.st_mode)
1406
return self._file_content_summary(path, stat_result)
1407
elif kind == 'directory':
1408
# perhaps it looks like a plain directory, but it's really a
1410
if self._directory_is_tree_reference(path):
1411
kind = 'tree-reference'
1412
return kind, None, None, None
1413
elif kind == 'symlink':
1414
target = osutils.readlink(self.abspath(path))
1415
return ('symlink', None, None, target)
1417
return (kind, None, None, None)
1419
def kind(self, relpath):
1420
kind = osutils.file_kind(self.abspath(relpath))
1421
if kind == 'directory':
1422
(index, index_path) = self._lookup_index(relpath.encode('utf-8'))
1426
mode = index[index_path].mode
1430
if S_ISGITLINK(mode):
1431
return 'tree-reference'
1436
def _live_entry(self, relpath):
1437
raise NotImplementedError(self._live_entry)
1439
def get_transform(self, pb=None):
1440
from ..transform import TreeTransform
1441
return TreeTransform(self, pb=pb)
1445
class InterIndexGitTree(InterGitTrees):
1446
"""InterTree that works between a Git revision tree and an index."""
1448
def __init__(self, source, target):
1449
super(InterIndexGitTree, self).__init__(source, target)
1450
self._index = target.index
1453
def is_compatible(cls, source, target):
1454
return (isinstance(source, GitRevisionTree) and
1455
isinstance(target, MutableGitIndexTree))
1457
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1458
require_versioned=False, extra_trees=None,
1459
want_unversioned=False):
1460
trees = [self.source]
1461
if extra_trees is not None:
1462
trees.extend(extra_trees)
1463
if specific_files is not None:
1464
specific_files = self.target.find_related_paths_across_trees(
1465
specific_files, trees,
1466
require_versioned=require_versioned)
1467
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1468
with self.lock_read():
1469
return changes_between_git_tree_and_working_copy(
1470
self.source.store, self.source.tree,
1471
self.target, want_unchanged=want_unchanged,
1472
want_unversioned=want_unversioned)
1475
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
1478
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1479
want_unchanged=False,
1480
want_unversioned=False):
1481
"""Determine the changes between a git tree and a working tree with index.
1486
# Report dirified directories to commit_tree first, so that they can be
1487
# replaced with non-empty directories if they have contents.
1489
trust_executable = target._supports_executable()
1490
for path, index_entry in target._recurse_index_entries():
1492
live_entry = target._live_entry(path)
1493
except EnvironmentError as e:
1494
if e.errno == errno.ENOENT:
1495
# Entry was removed; keep it listed, but mark it as gone.
1496
blobs[path] = (ZERO_SHA, 0)
1497
elif e.errno == errno.EISDIR:
1498
# Backwards compatibility with Dulwich < 0.19.12;
1499
# newer versions of Dulwich return either an entry for the
1500
# submodule or None for directories.
1501
if S_ISGITLINK(index_entry.mode):
1502
blobs[path] = (index_entry.sha, index_entry.mode)
1504
# Entry was turned into a directory
1505
dirified.append((path, Tree().id, stat.S_IFDIR))
1506
store.add_object(Tree())
1510
if live_entry is None:
1511
# Entry was turned into a directory
1512
dirified.append((path, Tree().id, stat.S_IFDIR))
1513
store.add_object(Tree())
1515
mode = live_entry.mode
1516
if not trust_executable:
1517
if mode_is_executable(index_entry.mode):
1521
blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1522
if want_unversioned:
1523
for e in target.extras():
1524
st = target._lstat(e)
1526
np, accessible = osutils.normalized_filename(e)
1527
except UnicodeDecodeError:
1528
raise errors.BadFilenameEncoding(
1530
if stat.S_ISDIR(st.st_mode):
1533
blob = blob_from_path_and_stat(
1534
target.abspath(e).encode(osutils._fs_enc), st)
1535
store.add_object(blob)
1536
np = np.encode('utf-8')
1537
blobs[np] = (blob.id, cleanup_mode(st.st_mode))
1539
to_tree_sha = commit_tree(
1540
store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
1541
return store.tree_changes(
1542
from_tree_sha, to_tree_sha, include_trees=True,
1543
want_unchanged=want_unchanged, change_type_same=True), extras