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 has_id(self, file_id):
364
raise errors.UnsupportedOperation(self.has_id, self)
366
def _lookup_path(self, path):
367
if self.tree is None:
368
raise errors.NoSuchFile(path)
370
(mode, hexsha) = tree_lookup_path(
371
self.store.__getitem__, self.tree, path.encode('utf-8'))
373
raise errors.NoSuchFile(self, path)
375
return (self.store, mode, hexsha)
377
def is_executable(self, path):
378
(store, mode, hexsha) = self._lookup_path(path)
380
# the tree root is a directory
382
return mode_is_executable(mode)
384
def kind(self, path):
385
(store, mode, hexsha) = self._lookup_path(path)
387
# the tree root is a directory
389
return mode_kind(mode)
391
def has_filename(self, path):
393
self._lookup_path(path)
394
except errors.NoSuchFile:
399
def list_files(self, include_root=False, from_dir=None, recursive=True):
400
if self.tree is None:
402
if from_dir is None or from_dir == '.':
404
(store, mode, hexsha) = self._lookup_path(from_dir)
405
if mode is None: # Root
406
root_ie = self._get_dir_ie(b"", None)
408
parent_path = posixpath.dirname(from_dir)
409
parent_id = self.mapping.generate_file_id(parent_path)
410
if mode_kind(mode) == 'directory':
411
root_ie = self._get_dir_ie(from_dir.encode("utf-8"), parent_id)
413
root_ie = self._get_file_ie(
414
store, from_dir.encode("utf-8"),
415
posixpath.basename(from_dir), mode, hexsha)
417
yield (from_dir, "V", root_ie.kind, root_ie)
419
if root_ie.kind == 'directory':
420
todo.append((store, from_dir.encode("utf-8"),
421
b"", hexsha, root_ie.file_id))
423
(store, path, relpath, hexsha, parent_id) = todo.pop()
425
for name, mode, hexsha in tree.iteritems():
426
if self.mapping.is_special_file(name):
428
child_path = posixpath.join(path, name)
429
child_relpath = posixpath.join(relpath, name)
430
if stat.S_ISDIR(mode):
431
ie = self._get_dir_ie(child_path, parent_id)
434
(store, child_path, child_relpath, hexsha,
437
ie = self._get_file_ie(
438
store, child_path, name, mode, hexsha, parent_id)
439
yield (child_relpath.decode('utf-8'), "V", ie.kind, ie)
441
def _get_file_ie(self, store, path, name, mode, hexsha, parent_id):
442
if not isinstance(path, bytes):
443
raise TypeError(path)
444
if not isinstance(name, bytes):
445
raise TypeError(name)
446
kind = mode_kind(mode)
447
path = path.decode('utf-8')
448
name = name.decode("utf-8")
449
file_id = self.mapping.generate_file_id(path)
450
ie = entry_factory[kind](file_id, name, parent_id)
451
if kind == 'symlink':
452
ie.symlink_target = store[hexsha].data.decode('utf-8')
453
elif kind == 'tree-reference':
454
ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(
457
data = store[hexsha].data
458
ie.text_sha1 = osutils.sha_string(data)
459
ie.text_size = len(data)
460
ie.executable = mode_is_executable(mode)
463
def _get_dir_ie(self, path, parent_id):
464
path = path.decode('utf-8')
465
file_id = self.mapping.generate_file_id(path)
466
return GitTreeDirectory(file_id, posixpath.basename(path), parent_id)
468
def iter_child_entries(self, path):
469
(store, mode, tree_sha) = self._lookup_path(path)
471
if mode is not None and not stat.S_ISDIR(mode):
474
encoded_path = path.encode('utf-8')
475
file_id = self.path2id(path)
476
tree = store[tree_sha]
477
for name, mode, hexsha in tree.iteritems():
478
if self.mapping.is_special_file(name):
480
child_path = posixpath.join(encoded_path, name)
481
if stat.S_ISDIR(mode):
482
yield self._get_dir_ie(child_path, file_id)
484
yield self._get_file_ie(store, child_path, name, mode, hexsha,
487
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
488
if self.tree is None:
491
# TODO(jelmer): Support yield parents
492
raise NotImplementedError
493
if specific_files is not None:
494
if specific_files in ([""], []):
495
specific_files = None
497
specific_files = set([p.encode('utf-8')
498
for p in specific_files])
499
todo = deque([(self.store, b"", self.tree, self.path2id(''))])
500
if specific_files is None or u"" in specific_files:
501
yield u"", self._get_dir_ie(b"", None)
503
store, path, tree_sha, parent_id = todo.popleft()
504
tree = store[tree_sha]
506
for name, mode, hexsha in tree.iteritems():
507
if self.mapping.is_special_file(name):
509
child_path = posixpath.join(path, name)
510
child_path_decoded = child_path.decode('utf-8')
511
if stat.S_ISDIR(mode):
512
if (specific_files is None or
513
any([p for p in specific_files if p.startswith(
516
(store, child_path, hexsha,
517
self.path2id(child_path_decoded)))
518
if specific_files is None or child_path in specific_files:
519
if stat.S_ISDIR(mode):
520
yield (child_path_decoded,
521
self._get_dir_ie(child_path, parent_id))
523
yield (child_path_decoded,
524
self._get_file_ie(store, child_path, name, mode,
526
todo.extendleft(reversed(extradirs))
528
def iter_references(self):
529
if self.supports_tree_reference():
530
for path, entry in self.iter_entries_by_dir():
531
if entry.kind == 'tree-reference':
534
def get_revision_id(self):
535
"""See RevisionTree.get_revision_id."""
536
return self._revision_id
538
def get_file_sha1(self, path, stat_value=None):
539
if self.tree is None:
540
raise errors.NoSuchFile(path)
541
return osutils.sha_string(self.get_file_text(path))
543
def get_file_verifier(self, path, stat_value=None):
544
(store, mode, hexsha) = self._lookup_path(path)
545
return ("GIT", hexsha)
547
def get_file_size(self, path):
548
(store, mode, hexsha) = self._lookup_path(path)
549
if stat.S_ISREG(mode):
550
return len(store[hexsha].data)
553
def get_file_text(self, path):
554
"""See RevisionTree.get_file_text."""
555
(store, mode, hexsha) = self._lookup_path(path)
556
if stat.S_ISREG(mode):
557
return store[hexsha].data
561
def get_symlink_target(self, path):
562
"""See RevisionTree.get_symlink_target."""
563
(store, mode, hexsha) = self._lookup_path(path)
564
if stat.S_ISLNK(mode):
565
return store[hexsha].data.decode('utf-8')
569
def get_reference_revision(self, path):
570
"""See RevisionTree.get_symlink_target."""
571
(store, mode, hexsha) = self._lookup_path(path)
572
if S_ISGITLINK(mode):
573
nested_repo = self._get_submodule_repository(path.encode('utf-8'))
574
return nested_repo.lookup_foreign_revision_id(hexsha)
578
def _comparison_data(self, entry, path):
580
return None, False, None
581
return entry.kind, entry.executable, None
583
def path_content_summary(self, path):
584
"""See Tree.path_content_summary."""
586
(store, mode, hexsha) = self._lookup_path(path)
587
except errors.NoSuchFile:
588
return ('missing', None, None, None)
589
kind = mode_kind(mode)
591
executable = mode_is_executable(mode)
592
contents = store[hexsha].data
593
return (kind, len(contents), executable,
594
osutils.sha_string(contents))
595
elif kind == 'symlink':
596
return (kind, None, None, store[hexsha].data.decode('utf-8'))
597
elif kind == 'tree-reference':
598
nested_repo = self._get_submodule_repository(path.encode('utf-8'))
599
return (kind, None, None,
600
nested_repo.lookup_foreign_revision_id(hexsha))
602
return (kind, None, None, None)
604
def find_related_paths_across_trees(self, paths, trees=[],
605
require_versioned=True):
608
if require_versioned:
609
trees = [self] + (trees if trees is not None else [])
613
if t.is_versioned(p):
618
raise errors.PathsNotVersionedError(unversioned)
619
return filter(self.is_versioned, paths)
621
def _iter_tree_contents(self, include_trees=False):
622
if self.tree is None:
624
return self.store.iter_tree_contents(
625
self.tree, include_trees=include_trees)
627
def annotate_iter(self, path, default_revision=CURRENT_REVISION):
628
"""Return an iterator of revision_id, line tuples.
630
For working trees (and mutable trees in general), the special
631
revision_id 'current:' will be used for lines that are new in this
632
tree, e.g. uncommitted changes.
633
:param default_revision: For lines that don't match a basis, mark them
634
with this revision id. Not all implementations will make use of
637
with self.lock_read():
638
# Now we have the parents of this content
639
from breezy.annotate import Annotator
640
from .annotate import AnnotateProvider
641
annotator = Annotator(AnnotateProvider(
642
self._repository._file_change_scanner))
643
this_key = (path, self.get_file_revision(path))
644
annotations = [(key[-1], line)
645
for key, line in annotator.annotate_flat(this_key)]
648
def _get_rules_searcher(self, default_searcher):
649
return default_searcher
651
def walkdirs(self, prefix=u""):
652
(store, mode, hexsha) = self._lookup_path(prefix)
654
[(store, prefix.encode('utf-8'), hexsha, self.path2id(prefix))])
656
store, path, tree_sha, parent_id = todo.popleft()
657
path_decoded = path.decode('utf-8')
658
tree = store[tree_sha]
660
for name, mode, hexsha in tree.iteritems():
661
if self.mapping.is_special_file(name):
663
child_path = posixpath.join(path, name)
664
file_id = self.path2id(child_path.decode('utf-8'))
665
if stat.S_ISDIR(mode):
666
todo.append((store, child_path, hexsha, file_id))
668
(child_path.decode('utf-8'), name.decode('utf-8'),
669
mode_kind(mode), None,
670
file_id, mode_kind(mode)))
671
yield (path_decoded, parent_id), children
674
def tree_delta_from_git_changes(changes, mappings,
676
require_versioned=False, include_root=False,
678
"""Create a TreeDelta from two git trees.
680
source and target are iterators over tuples with:
681
(filename, sha, mode)
683
(old_mapping, new_mapping) = mappings
684
if target_extras is None:
685
target_extras = set()
686
ret = delta.TreeDelta()
688
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
689
if newpath == b'' and not include_root:
691
if oldpath is not None:
692
oldpath_decoded = oldpath.decode('utf-8')
694
oldpath_decoded = None
695
if newpath is not None:
696
newpath_decoded = newpath.decode('utf-8')
698
newpath_decoded = None
699
if not (specific_files is None or
700
(oldpath is not None and
701
osutils.is_inside_or_parent_of_any(
702
specific_files, oldpath_decoded)) or
703
(newpath is not None and
704
osutils.is_inside_or_parent_of_any(
705
specific_files, newpath_decoded))):
708
if oldpath_decoded is None:
709
fileid = new_mapping.generate_file_id(newpath_decoded)
718
oldexe = mode_is_executable(oldmode)
719
oldkind = mode_kind(oldmode)
723
if oldpath_decoded == u'':
727
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
728
oldparent = old_mapping.generate_file_id(oldparentpath)
729
fileid = old_mapping.generate_file_id(oldpath_decoded)
730
if newpath_decoded is None:
737
newversioned = (newpath_decoded not in target_extras)
739
newexe = mode_is_executable(newmode)
740
newkind = mode_kind(newmode)
744
if newpath_decoded == u'':
748
newparentpath, newname = osutils.split(newpath_decoded)
749
newparent = new_mapping.generate_file_id(newparentpath)
750
if old_mapping.is_special_file(oldpath):
752
if new_mapping.is_special_file(newpath):
754
if oldpath is None and newpath is None:
756
change = _mod_tree.TreeChange(
757
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
758
(oldversioned, newversioned),
759
(oldparent, newparent), (oldname, newname),
760
(oldkind, newkind), (oldexe, newexe))
762
added.append((newpath, newkind))
763
elif newpath is None or newmode == 0:
764
ret.removed.append(change)
765
elif oldpath != newpath:
766
ret.renamed.append(change)
767
elif mode_kind(oldmode) != mode_kind(newmode):
768
ret.kind_changed.append(change)
769
elif oldsha != newsha or oldmode != newmode:
770
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
772
ret.modified.append(change)
774
ret.unchanged.append(change)
776
implicit_dirs = {b''}
777
for path, kind in added:
778
if kind == 'directory' or path in target_extras:
780
implicit_dirs.update(osutils.parent_directories(path))
782
for path, kind in added:
783
if kind == 'directory' and path not in implicit_dirs:
785
path_decoded = osutils.normalized_filename(path)[0]
786
parent_path, basename = osutils.split(path_decoded)
787
parent_id = new_mapping.generate_file_id(parent_path)
788
if path in target_extras:
789
ret.unversioned.append(_mod_tree.TreeChange(
790
None, (None, path_decoded),
791
True, (False, False), (None, parent_id),
792
(None, basename), (None, kind), (None, False)))
794
file_id = new_mapping.generate_file_id(path_decoded)
796
_mod_tree.TreeChange(
797
file_id, (None, path_decoded), True,
800
(None, basename), (None, kind), (None, False)))
805
def changes_from_git_changes(changes, mapping, specific_files=None,
806
include_unchanged=False, target_extras=None):
807
"""Create a iter_changes-like generator from a git stream.
809
source and target are iterators over tuples with:
810
(filename, sha, mode)
812
if target_extras is None:
813
target_extras = set()
814
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
815
if oldpath is not None:
816
oldpath_decoded = oldpath.decode('utf-8')
818
oldpath_decoded = None
819
if newpath is not None:
820
newpath_decoded = newpath.decode('utf-8')
822
newpath_decoded = None
823
if not (specific_files is None or
824
(oldpath_decoded is not None and
825
osutils.is_inside_or_parent_of_any(
826
specific_files, oldpath_decoded)) or
827
(newpath_decoded is not None and
828
osutils.is_inside_or_parent_of_any(
829
specific_files, newpath_decoded))):
831
if oldpath is not None and mapping.is_special_file(oldpath):
833
if newpath is not None and mapping.is_special_file(newpath):
835
if oldpath_decoded is None:
836
fileid = mapping.generate_file_id(newpath_decoded)
845
oldexe = mode_is_executable(oldmode)
846
oldkind = mode_kind(oldmode)
850
if oldpath_decoded == u'':
854
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
855
oldparent = mapping.generate_file_id(oldparentpath)
856
fileid = mapping.generate_file_id(oldpath_decoded)
857
if newpath_decoded is None:
864
newversioned = (newpath_decoded not in target_extras)
866
newexe = mode_is_executable(newmode)
867
newkind = mode_kind(newmode)
871
if newpath_decoded == u'':
875
newparentpath, newname = osutils.split(newpath_decoded)
876
newparent = mapping.generate_file_id(newparentpath)
877
if (not include_unchanged and
878
oldkind == 'directory' and newkind == 'directory' and
879
oldpath_decoded == newpath_decoded):
881
yield _mod_tree.TreeChange(
882
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
883
(oldversioned, newversioned),
884
(oldparent, newparent), (oldname, newname),
885
(oldkind, newkind), (oldexe, newexe))
888
class InterGitTrees(_mod_tree.InterTree):
889
"""InterTree that works between two git trees."""
891
_matching_from_tree_format = None
892
_matching_to_tree_format = None
893
_test_mutable_trees_to_test_trees = None
896
def is_compatible(cls, source, target):
897
return (isinstance(source, GitRevisionTree) and
898
isinstance(target, GitRevisionTree))
900
def compare(self, want_unchanged=False, specific_files=None,
901
extra_trees=None, require_versioned=False, include_root=False,
902
want_unversioned=False):
903
with self.lock_read():
904
changes, target_extras = self._iter_git_changes(
905
want_unchanged=want_unchanged,
906
require_versioned=require_versioned,
907
specific_files=specific_files,
908
extra_trees=extra_trees,
909
want_unversioned=want_unversioned)
910
return tree_delta_from_git_changes(
911
changes, (self.source.mapping, self.target.mapping),
912
specific_files=specific_files,
913
include_root=include_root, target_extras=target_extras)
915
def iter_changes(self, include_unchanged=False, specific_files=None,
916
pb=None, extra_trees=[], require_versioned=True,
917
want_unversioned=False):
918
with self.lock_read():
919
changes, target_extras = self._iter_git_changes(
920
want_unchanged=include_unchanged,
921
require_versioned=require_versioned,
922
specific_files=specific_files,
923
extra_trees=extra_trees,
924
want_unversioned=want_unversioned)
925
return changes_from_git_changes(
926
changes, self.target.mapping,
927
specific_files=specific_files,
928
include_unchanged=include_unchanged,
929
target_extras=target_extras)
931
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
932
require_versioned=False, extra_trees=None,
933
want_unversioned=False):
934
raise NotImplementedError(self._iter_git_changes)
937
class InterGitRevisionTrees(InterGitTrees):
938
"""InterTree that works between two git revision trees."""
940
_matching_from_tree_format = None
941
_matching_to_tree_format = None
942
_test_mutable_trees_to_test_trees = None
945
def is_compatible(cls, source, target):
946
return (isinstance(source, GitRevisionTree) and
947
isinstance(target, GitRevisionTree))
949
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
950
require_versioned=True, extra_trees=None,
951
want_unversioned=False):
952
trees = [self.source]
953
if extra_trees is not None:
954
trees.extend(extra_trees)
955
if specific_files is not None:
956
specific_files = self.target.find_related_paths_across_trees(
957
specific_files, trees,
958
require_versioned=require_versioned)
960
if (self.source._repository._git.object_store !=
961
self.target._repository._git.object_store):
962
store = OverlayObjectStore(
963
[self.source._repository._git.object_store,
964
self.target._repository._git.object_store])
966
store = self.source._repository._git.object_store
967
return store.tree_changes(
968
self.source.tree, self.target.tree, want_unchanged=want_unchanged,
969
include_trees=True, change_type_same=True), set()
972
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
975
class MutableGitIndexTree(mutabletree.MutableTree):
978
self._lock_mode = None
980
self._versioned_dirs = None
981
self._index_dirty = False
983
def is_versioned(self, path):
984
with self.lock_read():
985
path = path.rstrip('/').encode('utf-8')
986
(index, subpath) = self._lookup_index(path)
987
return (subpath in index or self._has_dir(path))
989
def _has_dir(self, path):
990
if not isinstance(path, bytes):
991
raise TypeError(path)
994
if self._versioned_dirs is None:
996
return path in self._versioned_dirs
998
def _load_dirs(self):
999
if self._lock_mode is None:
1000
raise errors.ObjectNotLocked(self)
1001
self._versioned_dirs = set()
1002
# TODO(jelmer): Browse over all indexes
1003
for p, i in self._recurse_index_entries():
1004
self._ensure_versioned_dir(posixpath.dirname(p))
1006
def _ensure_versioned_dir(self, dirname):
1007
if not isinstance(dirname, bytes):
1008
raise TypeError(dirname)
1009
if dirname in self._versioned_dirs:
1012
self._ensure_versioned_dir(posixpath.dirname(dirname))
1013
self._versioned_dirs.add(dirname)
1015
def path2id(self, path):
1016
with self.lock_read():
1017
path = path.rstrip('/')
1018
if self.is_versioned(path.rstrip('/')):
1019
return self.mapping.generate_file_id(
1020
osutils.safe_unicode(path))
1023
def has_id(self, file_id):
1024
raise errors.UnsupportedOperation(self.has_id, self)
1026
def id2path(self, file_id):
1029
if type(file_id) is not bytes:
1030
raise TypeError(file_id)
1031
with self.lock_read():
1033
path = self.mapping.parse_file_id(file_id)
1035
raise errors.NoSuchId(self, file_id)
1036
if self.is_versioned(path):
1038
raise errors.NoSuchId(self, file_id)
1040
def _set_root_id(self, file_id):
1041
raise errors.UnsupportedOperation(self._set_root_id, self)
1043
def _add(self, files, ids, kinds):
1044
for (path, file_id, kind) in zip(files, ids, kinds):
1045
if file_id is not None:
1046
raise workingtree.SettingFileIdUnsupported()
1047
path, can_access = osutils.normalized_filename(path)
1049
raise errors.InvalidNormalization(path)
1050
self._index_add_entry(path, kind)
1052
def _read_submodule_head(self, path):
1053
raise NotImplementedError(self._read_submodule_head)
1055
def _lookup_index(self, encoded_path):
1056
if not isinstance(encoded_path, bytes):
1057
raise TypeError(encoded_path)
1058
# TODO(jelmer): Look in other indexes
1059
return self.index, encoded_path
1061
def _index_del_entry(self, index, path):
1063
# TODO(jelmer): Keep track of dirty per index
1064
self._index_dirty = True
1066
def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
1067
if kind == "directory":
1068
# Git indexes don't contain directories
1073
file, stat_val = self.get_file_with_stat(path)
1074
except (errors.NoSuchFile, IOError):
1075
# TODO: Rather than come up with something here, use the old
1078
stat_val = os.stat_result(
1079
(stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1081
blob.set_raw_string(file.read())
1082
# Add object to the repository if it didn't exist yet
1083
if blob.id not in self.store:
1084
self.store.add_object(blob)
1086
elif kind == "symlink":
1089
stat_val = self._lstat(path)
1090
except EnvironmentError:
1091
# TODO: Rather than come up with something here, use the
1093
stat_val = os.stat_result(
1094
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1095
blob.set_raw_string(
1096
self.get_symlink_target(path).encode("utf-8"))
1097
# Add object to the repository if it didn't exist yet
1098
if blob.id not in self.store:
1099
self.store.add_object(blob)
1101
elif kind == "tree-reference":
1102
if reference_revision is not None:
1103
hexsha = self.branch.lookup_bzr_revision_id(
1104
reference_revision)[0]
1106
hexsha = self._read_submodule_head(path)
1108
raise errors.NoCommits(path)
1110
stat_val = self._lstat(path)
1111
except EnvironmentError:
1112
stat_val = os.stat_result(
1113
(S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1114
stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
1116
raise AssertionError("unknown kind '%s'" % kind)
1117
# Add an entry to the index or update the existing entry
1118
ensure_normalized_path(path)
1119
encoded_path = path.encode("utf-8")
1120
if b'\r' in encoded_path or b'\n' in encoded_path:
1121
# TODO(jelmer): Why do we need to do this?
1122
trace.mutter('ignoring path with invalid newline in it: %r', path)
1124
(index, index_path) = self._lookup_index(encoded_path)
1125
index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
1126
self._index_dirty = True
1127
if self._versioned_dirs is not None:
1128
self._ensure_versioned_dir(index_path)
1130
def _recurse_index_entries(self, index=None, basepath=b""):
1131
# Iterate over all index entries
1132
with self.lock_read():
1135
for path, value in index.items():
1136
yield (posixpath.join(basepath, path), value)
1137
(ctime, mtime, dev, ino, mode, uid, gid, size, sha,
1139
if S_ISGITLINK(mode):
1140
pass # TODO(jelmer): dive into submodule
1142
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
1144
raise NotImplementedError(self.iter_entries_by_dir)
1145
with self.lock_read():
1146
if specific_files is not None:
1147
specific_files = set(specific_files)
1149
specific_files = None
1150
root_ie = self._get_dir_ie(u"", None)
1152
if specific_files is None or u"" in specific_files:
1153
ret[(u"", u"")] = root_ie
1154
dir_ids = {u"": root_ie.file_id}
1155
for path, value in self._recurse_index_entries():
1156
if self.mapping.is_special_file(path):
1158
path = path.decode("utf-8")
1159
if specific_files is not None and path not in specific_files:
1161
(parent, name) = posixpath.split(path)
1163
file_ie = self._get_file_ie(name, path, value, None)
1164
except errors.NoSuchFile:
1166
if yield_parents or specific_files is None:
1167
for (dir_path, dir_ie) in self._add_missing_parent_ids(
1169
ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
1170
file_ie.parent_id = self.path2id(parent)
1171
ret[(posixpath.dirname(path), path)] = file_ie
1172
return ((path, ie) for ((_, path), ie) in sorted(viewitems(ret)))
1174
def iter_references(self):
1175
# TODO(jelmer): Implement a more efficient version of this
1176
for path, entry in self.iter_entries_by_dir():
1177
if entry.kind == 'tree-reference':
1180
def _get_dir_ie(self, path, parent_id):
1181
file_id = self.path2id(path)
1182
return GitTreeDirectory(file_id,
1183
posixpath.basename(path).strip("/"), parent_id)
1185
def _get_file_ie(self, name, path, value, parent_id):
1186
if not isinstance(name, text_type):
1187
raise TypeError(name)
1188
if not isinstance(path, text_type):
1189
raise TypeError(path)
1190
if not isinstance(value, tuple) or len(value) != 10:
1191
raise TypeError(value)
1192
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1193
file_id = self.path2id(path)
1194
if not isinstance(file_id, bytes):
1195
raise TypeError(file_id)
1196
kind = mode_kind(mode)
1197
ie = entry_factory[kind](file_id, name, parent_id)
1198
if kind == 'symlink':
1199
ie.symlink_target = self.get_symlink_target(path)
1200
elif kind == 'tree-reference':
1201
ie.reference_revision = self.get_reference_revision(path)
1204
data = self.get_file_text(path)
1205
except errors.NoSuchFile:
1207
except IOError as e:
1208
if e.errno != errno.ENOENT:
1212
data = self.branch.repository._git.object_store[sha].data
1213
ie.text_sha1 = osutils.sha_string(data)
1214
ie.text_size = len(data)
1215
ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1218
def _add_missing_parent_ids(self, path, dir_ids):
1221
parent = posixpath.dirname(path).strip("/")
1222
ret = self._add_missing_parent_ids(parent, dir_ids)
1223
parent_id = dir_ids[parent]
1224
ie = self._get_dir_ie(path, parent_id)
1225
dir_ids[path] = ie.file_id
1226
ret.append((path, ie))
1229
def _comparison_data(self, entry, path):
1231
return None, False, None
1232
return entry.kind, entry.executable, None
1234
def _unversion_path(self, path):
1235
if self._lock_mode is None:
1236
raise errors.ObjectNotLocked(self)
1237
encoded_path = path.encode("utf-8")
1239
(index, subpath) = self._lookup_index(encoded_path)
1241
self._index_del_entry(index, encoded_path)
1243
# A directory, perhaps?
1244
# TODO(jelmer): Deletes that involve submodules?
1245
for p in list(index):
1246
if p.startswith(subpath + b"/"):
1248
self._index_del_entry(index, p)
1251
self._versioned_dirs = None
1254
def unversion(self, paths):
1255
with self.lock_tree_write():
1257
if self._unversion_path(path) == 0:
1258
raise errors.NoSuchFile(path)
1259
self._versioned_dirs = None
1265
def update_basis_by_delta(self, revid, delta):
1266
# TODO(jelmer): This shouldn't be called, it's inventory specific.
1267
for (old_path, new_path, file_id, ie) in delta:
1268
if old_path is not None:
1269
(index, old_subpath) = self._lookup_index(
1270
old_path.encode('utf-8'))
1271
if old_subpath in index:
1272
self._index_del_entry(index, old_subpath)
1273
self._versioned_dirs = None
1274
if new_path is not None and ie.kind != 'directory':
1275
self._index_add_entry(new_path, ie.kind)
1277
self._set_merges_from_parent_ids([])
1279
def move(self, from_paths, to_dir=None, after=None):
1281
with self.lock_tree_write():
1282
to_abs = self.abspath(to_dir)
1283
if not os.path.isdir(to_abs):
1284
raise errors.BzrMoveFailedError('', to_dir,
1285
errors.NotADirectory(to_abs))
1287
for from_rel in from_paths:
1288
from_tail = os.path.split(from_rel)[-1]
1289
to_rel = os.path.join(to_dir, from_tail)
1290
self.rename_one(from_rel, to_rel, after=after)
1291
rename_tuples.append((from_rel, to_rel))
1293
return rename_tuples
1295
def rename_one(self, from_rel, to_rel, after=None):
1296
from_path = from_rel.encode("utf-8")
1297
to_rel, can_access = osutils.normalized_filename(to_rel)
1299
raise errors.InvalidNormalization(to_rel)
1300
to_path = to_rel.encode("utf-8")
1301
with self.lock_tree_write():
1303
# Perhaps it's already moved?
1305
not self.has_filename(from_rel) and
1306
self.has_filename(to_rel) and
1307
not self.is_versioned(to_rel))
1309
if not self.has_filename(to_rel):
1310
raise errors.BzrMoveFailedError(
1311
from_rel, to_rel, errors.NoSuchFile(to_rel))
1312
if self.basis_tree().is_versioned(to_rel):
1313
raise errors.BzrMoveFailedError(
1314
from_rel, to_rel, errors.AlreadyVersionedError(to_rel))
1316
kind = self.kind(to_rel)
1319
to_kind = self.kind(to_rel)
1320
except errors.NoSuchFile:
1321
exc_type = errors.BzrRenameFailedError
1324
exc_type = errors.BzrMoveFailedError
1325
if self.is_versioned(to_rel):
1326
raise exc_type(from_rel, to_rel,
1327
errors.AlreadyVersionedError(to_rel))
1328
if not self.has_filename(from_rel):
1329
raise errors.BzrMoveFailedError(
1330
from_rel, to_rel, errors.NoSuchFile(from_rel))
1331
kind = self.kind(from_rel)
1332
if not self.is_versioned(from_rel) and kind != 'directory':
1333
raise exc_type(from_rel, to_rel,
1334
errors.NotVersionedError(from_rel))
1335
if self.has_filename(to_rel):
1336
raise errors.RenameFailedFilesExist(
1337
from_rel, to_rel, errors.FileExists(to_rel))
1339
kind = self.kind(from_rel)
1341
if not after and kind != 'directory':
1342
(index, from_subpath) = self._lookup_index(from_path)
1343
if from_subpath not in index:
1345
raise errors.BzrMoveFailedError(
1347
errors.NotVersionedError(path=from_rel))
1351
self._rename_one(from_rel, to_rel)
1352
except OSError as e:
1353
if e.errno == errno.ENOENT:
1354
raise errors.BzrMoveFailedError(
1355
from_rel, to_rel, errors.NoSuchFile(to_rel))
1357
if kind != 'directory':
1358
(index, from_index_path) = self._lookup_index(from_path)
1360
self._index_del_entry(index, from_path)
1363
self._index_add_entry(to_rel, kind)
1365
todo = [(p, i) for (p, i) in self._recurse_index_entries()
1366
if p.startswith(from_path + b'/')]
1367
for child_path, child_value in todo:
1368
(child_to_index, child_to_index_path) = self._lookup_index(
1369
posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
1370
child_to_index[child_to_index_path] = child_value
1371
# TODO(jelmer): Mark individual index as dirty
1372
self._index_dirty = True
1373
(child_from_index, child_from_index_path) = self._lookup_index(
1375
self._index_del_entry(
1376
child_from_index, child_from_index_path)
1378
self._versioned_dirs = None
1381
def find_related_paths_across_trees(self, paths, trees=[],
1382
require_versioned=True):
1386
if require_versioned:
1387
trees = [self] + (trees if trees is not None else [])
1391
if t.is_versioned(p):
1396
raise errors.PathsNotVersionedError(unversioned)
1398
return filter(self.is_versioned, paths)
1400
def path_content_summary(self, path):
1401
"""See Tree.path_content_summary."""
1403
stat_result = self._lstat(path)
1404
except OSError as e:
1405
if getattr(e, 'errno', None) == errno.ENOENT:
1407
return ('missing', None, None, None)
1408
# propagate other errors
1410
kind = mode_kind(stat_result.st_mode)
1412
return self._file_content_summary(path, stat_result)
1413
elif kind == 'directory':
1414
# perhaps it looks like a plain directory, but it's really a
1416
if self._directory_is_tree_reference(path):
1417
kind = 'tree-reference'
1418
return kind, None, None, None
1419
elif kind == 'symlink':
1420
target = osutils.readlink(self.abspath(path))
1421
return ('symlink', None, None, target)
1423
return (kind, None, None, None)
1425
def kind(self, relpath):
1426
kind = osutils.file_kind(self.abspath(relpath))
1427
if kind == 'directory':
1428
(index, index_path) = self._lookup_index(relpath.encode('utf-8'))
1432
mode = index[index_path].mode
1436
if S_ISGITLINK(mode):
1437
return 'tree-reference'
1442
def _live_entry(self, relpath):
1443
raise NotImplementedError(self._live_entry)
1445
def get_transform(self, pb=None):
1446
from ..transform import TreeTransform
1447
return TreeTransform(self, pb=pb)
1451
class InterIndexGitTree(InterGitTrees):
1452
"""InterTree that works between a Git revision tree and an index."""
1454
def __init__(self, source, target):
1455
super(InterIndexGitTree, self).__init__(source, target)
1456
self._index = target.index
1459
def is_compatible(cls, source, target):
1460
return (isinstance(source, GitRevisionTree) and
1461
isinstance(target, MutableGitIndexTree))
1463
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1464
require_versioned=False, extra_trees=None,
1465
want_unversioned=False):
1466
trees = [self.source]
1467
if extra_trees is not None:
1468
trees.extend(extra_trees)
1469
if specific_files is not None:
1470
specific_files = self.target.find_related_paths_across_trees(
1471
specific_files, trees,
1472
require_versioned=require_versioned)
1473
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1474
with self.lock_read():
1475
return changes_between_git_tree_and_working_copy(
1476
self.source.store, self.source.tree,
1477
self.target, want_unchanged=want_unchanged,
1478
want_unversioned=want_unversioned)
1481
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
1484
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1485
want_unchanged=False,
1486
want_unversioned=False):
1487
"""Determine the changes between a git tree and a working tree with index.
1492
# Report dirified directories to commit_tree first, so that they can be
1493
# replaced with non-empty directories if they have contents.
1495
trust_executable = target._supports_executable()
1496
for path, index_entry in target._recurse_index_entries():
1498
live_entry = target._live_entry(path)
1499
except EnvironmentError as e:
1500
if e.errno == errno.ENOENT:
1501
# Entry was removed; keep it listed, but mark it as gone.
1502
blobs[path] = (ZERO_SHA, 0)
1503
elif e.errno == errno.EISDIR:
1504
# Backwards compatibility with Dulwich < 0.19.12;
1505
# newer versions of Dulwich return either an entry for the
1506
# submodule or None for directories.
1507
if S_ISGITLINK(index_entry.mode):
1508
blobs[path] = (index_entry.sha, index_entry.mode)
1510
# Entry was turned into a directory
1511
dirified.append((path, Tree().id, stat.S_IFDIR))
1512
store.add_object(Tree())
1516
if live_entry is None:
1517
# Entry was turned into a directory
1518
dirified.append((path, Tree().id, stat.S_IFDIR))
1519
store.add_object(Tree())
1521
mode = live_entry.mode
1522
if not trust_executable:
1523
if mode_is_executable(index_entry.mode):
1527
blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1528
if want_unversioned:
1529
for e in target.extras():
1530
st = target._lstat(e)
1532
np, accessible = osutils.normalized_filename(e)
1533
except UnicodeDecodeError:
1534
raise errors.BadFilenameEncoding(
1536
if stat.S_ISDIR(st.st_mode):
1539
blob = blob_from_path_and_stat(
1540
target.abspath(e).encode(osutils._fs_enc), st)
1541
store.add_object(blob)
1542
np = np.encode('utf-8')
1543
blobs[np] = (blob.id, cleanup_mode(st.st_mode))
1545
to_tree_sha = commit_tree(
1546
store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
1547
return store.tree_changes(
1548
from_tree_sha, to_tree_sha, include_trees=True,
1549
want_unchanged=want_unchanged, change_type_same=True), extras