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):
365
path = self.id2path(file_id)
366
except errors.NoSuchId:
368
return self.has_filename(path)
370
def _lookup_path(self, path):
371
if self.tree is None:
372
raise errors.NoSuchFile(path)
374
(mode, hexsha) = tree_lookup_path(
375
self.store.__getitem__, self.tree, path.encode('utf-8'))
377
raise errors.NoSuchFile(self, path)
379
return (self.store, mode, hexsha)
381
def is_executable(self, path):
382
(store, mode, hexsha) = self._lookup_path(path)
384
# the tree root is a directory
386
return mode_is_executable(mode)
388
def kind(self, path):
389
(store, mode, hexsha) = self._lookup_path(path)
391
# the tree root is a directory
393
return mode_kind(mode)
395
def has_filename(self, path):
397
self._lookup_path(path)
398
except errors.NoSuchFile:
403
def list_files(self, include_root=False, from_dir=None, recursive=True):
404
if self.tree is None:
406
if from_dir is None or from_dir == '.':
408
(store, mode, hexsha) = self._lookup_path(from_dir)
409
if mode is None: # Root
410
root_ie = self._get_dir_ie(b"", None)
412
parent_path = posixpath.dirname(from_dir)
413
parent_id = self.mapping.generate_file_id(parent_path)
414
if mode_kind(mode) == 'directory':
415
root_ie = self._get_dir_ie(from_dir.encode("utf-8"), parent_id)
417
root_ie = self._get_file_ie(
418
store, from_dir.encode("utf-8"),
419
posixpath.basename(from_dir), mode, hexsha)
421
yield (from_dir, "V", root_ie.kind, root_ie)
423
if root_ie.kind == 'directory':
424
todo.append((store, from_dir.encode("utf-8"),
425
b"", hexsha, root_ie.file_id))
427
(store, path, relpath, hexsha, parent_id) = todo.pop()
429
for name, mode, hexsha in tree.iteritems():
430
if self.mapping.is_special_file(name):
432
child_path = posixpath.join(path, name)
433
child_relpath = posixpath.join(relpath, name)
434
if stat.S_ISDIR(mode):
435
ie = self._get_dir_ie(child_path, parent_id)
438
(store, child_path, child_relpath, hexsha,
441
ie = self._get_file_ie(
442
store, child_path, name, mode, hexsha, parent_id)
443
yield (child_relpath.decode('utf-8'), "V", ie.kind, ie)
445
def _get_file_ie(self, store, path, name, mode, hexsha, parent_id):
446
if not isinstance(path, bytes):
447
raise TypeError(path)
448
if not isinstance(name, bytes):
449
raise TypeError(name)
450
kind = mode_kind(mode)
451
path = path.decode('utf-8')
452
name = name.decode("utf-8")
453
file_id = self.mapping.generate_file_id(path)
454
ie = entry_factory[kind](file_id, name, parent_id)
455
if kind == 'symlink':
456
ie.symlink_target = store[hexsha].data.decode('utf-8')
457
elif kind == 'tree-reference':
458
ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(
461
data = store[hexsha].data
462
ie.text_sha1 = osutils.sha_string(data)
463
ie.text_size = len(data)
464
ie.executable = mode_is_executable(mode)
467
def _get_dir_ie(self, path, parent_id):
468
path = path.decode('utf-8')
469
file_id = self.mapping.generate_file_id(path)
470
return GitTreeDirectory(file_id, posixpath.basename(path), parent_id)
472
def iter_child_entries(self, path):
473
(store, mode, tree_sha) = self._lookup_path(path)
475
if mode is not None and not stat.S_ISDIR(mode):
478
encoded_path = path.encode('utf-8')
479
file_id = self.path2id(path)
480
tree = store[tree_sha]
481
for name, mode, hexsha in tree.iteritems():
482
if self.mapping.is_special_file(name):
484
child_path = posixpath.join(encoded_path, name)
485
if stat.S_ISDIR(mode):
486
yield self._get_dir_ie(child_path, file_id)
488
yield self._get_file_ie(store, child_path, name, mode, hexsha,
491
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
492
if self.tree is None:
495
# TODO(jelmer): Support yield parents
496
raise NotImplementedError
497
if specific_files is not None:
498
if specific_files in ([""], []):
499
specific_files = None
501
specific_files = set([p.encode('utf-8')
502
for p in specific_files])
503
todo = deque([(self.store, b"", self.tree, self.path2id(''))])
504
if specific_files is None or u"" in specific_files:
505
yield u"", self._get_dir_ie(b"", None)
507
store, path, tree_sha, parent_id = todo.popleft()
508
tree = store[tree_sha]
510
for name, mode, hexsha in tree.iteritems():
511
if self.mapping.is_special_file(name):
513
child_path = posixpath.join(path, name)
514
child_path_decoded = child_path.decode('utf-8')
515
if stat.S_ISDIR(mode):
516
if (specific_files is None or
517
any([p for p in specific_files if p.startswith(
520
(store, child_path, hexsha,
521
self.path2id(child_path_decoded)))
522
if specific_files is None or child_path in specific_files:
523
if stat.S_ISDIR(mode):
524
yield (child_path_decoded,
525
self._get_dir_ie(child_path, parent_id))
527
yield (child_path_decoded,
528
self._get_file_ie(store, child_path, name, mode,
530
todo.extendleft(reversed(extradirs))
532
def iter_references(self):
533
if self.supports_tree_reference():
534
for path, entry in self.iter_entries_by_dir():
535
if entry.kind == 'tree-reference':
538
def get_revision_id(self):
539
"""See RevisionTree.get_revision_id."""
540
return self._revision_id
542
def get_file_sha1(self, path, stat_value=None):
543
if self.tree is None:
544
raise errors.NoSuchFile(path)
545
return osutils.sha_string(self.get_file_text(path))
547
def get_file_verifier(self, path, stat_value=None):
548
(store, mode, hexsha) = self._lookup_path(path)
549
return ("GIT", hexsha)
551
def get_file_size(self, path):
552
(store, mode, hexsha) = self._lookup_path(path)
553
if stat.S_ISREG(mode):
554
return len(store[hexsha].data)
557
def get_file_text(self, path):
558
"""See RevisionTree.get_file_text."""
559
(store, mode, hexsha) = self._lookup_path(path)
560
if stat.S_ISREG(mode):
561
return store[hexsha].data
565
def get_symlink_target(self, path):
566
"""See RevisionTree.get_symlink_target."""
567
(store, mode, hexsha) = self._lookup_path(path)
568
if stat.S_ISLNK(mode):
569
return store[hexsha].data.decode('utf-8')
573
def get_reference_revision(self, path):
574
"""See RevisionTree.get_symlink_target."""
575
(store, mode, hexsha) = self._lookup_path(path)
576
if S_ISGITLINK(mode):
577
nested_repo = self._get_submodule_repository(path.encode('utf-8'))
578
return nested_repo.lookup_foreign_revision_id(hexsha)
582
def _comparison_data(self, entry, path):
584
return None, False, None
585
return entry.kind, entry.executable, None
587
def path_content_summary(self, path):
588
"""See Tree.path_content_summary."""
590
(store, mode, hexsha) = self._lookup_path(path)
591
except errors.NoSuchFile:
592
return ('missing', None, None, None)
593
kind = mode_kind(mode)
595
executable = mode_is_executable(mode)
596
contents = store[hexsha].data
597
return (kind, len(contents), executable,
598
osutils.sha_string(contents))
599
elif kind == 'symlink':
600
return (kind, None, None, store[hexsha].data.decode('utf-8'))
601
elif kind == 'tree-reference':
602
nested_repo = self._get_submodule_repository(path.encode('utf-8'))
603
return (kind, None, None,
604
nested_repo.lookup_foreign_revision_id(hexsha))
606
return (kind, None, None, None)
608
def find_related_paths_across_trees(self, paths, trees=[],
609
require_versioned=True):
612
if require_versioned:
613
trees = [self] + (trees if trees is not None else [])
617
if t.is_versioned(p):
622
raise errors.PathsNotVersionedError(unversioned)
623
return filter(self.is_versioned, paths)
625
def _iter_tree_contents(self, include_trees=False):
626
if self.tree is None:
628
return self.store.iter_tree_contents(
629
self.tree, include_trees=include_trees)
631
def annotate_iter(self, path, default_revision=CURRENT_REVISION):
632
"""Return an iterator of revision_id, line tuples.
634
For working trees (and mutable trees in general), the special
635
revision_id 'current:' will be used for lines that are new in this
636
tree, e.g. uncommitted changes.
637
:param default_revision: For lines that don't match a basis, mark them
638
with this revision id. Not all implementations will make use of
641
with self.lock_read():
642
# Now we have the parents of this content
643
from breezy.annotate import Annotator
644
from .annotate import AnnotateProvider
645
annotator = Annotator(AnnotateProvider(
646
self._repository._file_change_scanner))
647
this_key = (path, self.get_file_revision(path))
648
annotations = [(key[-1], line)
649
for key, line in annotator.annotate_flat(this_key)]
652
def _get_rules_searcher(self, default_searcher):
653
return default_searcher
655
def walkdirs(self, prefix=u""):
656
(store, mode, hexsha) = self._lookup_path(prefix)
658
[(store, prefix.encode('utf-8'), hexsha, self.path2id(prefix))])
660
store, path, tree_sha, parent_id = todo.popleft()
661
path_decoded = path.decode('utf-8')
662
tree = store[tree_sha]
664
for name, mode, hexsha in tree.iteritems():
665
if self.mapping.is_special_file(name):
667
child_path = posixpath.join(path, name)
668
file_id = self.path2id(child_path.decode('utf-8'))
669
if stat.S_ISDIR(mode):
670
todo.append((store, child_path, hexsha, file_id))
672
(child_path.decode('utf-8'), name.decode('utf-8'),
673
mode_kind(mode), None,
674
file_id, mode_kind(mode)))
675
yield (path_decoded, parent_id), children
678
def tree_delta_from_git_changes(changes, mappings,
680
require_versioned=False, include_root=False,
682
"""Create a TreeDelta from two git trees.
684
source and target are iterators over tuples with:
685
(filename, sha, mode)
687
(old_mapping, new_mapping) = mappings
688
if target_extras is None:
689
target_extras = set()
690
ret = delta.TreeDelta()
692
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
693
if newpath == b'' and not include_root:
695
if oldpath is not None:
696
oldpath_decoded = oldpath.decode('utf-8')
698
oldpath_decoded = None
699
if newpath is not None:
700
newpath_decoded = newpath.decode('utf-8')
702
newpath_decoded = None
703
if not (specific_files is None or
704
(oldpath is not None and
705
osutils.is_inside_or_parent_of_any(
706
specific_files, oldpath_decoded)) or
707
(newpath is not None and
708
osutils.is_inside_or_parent_of_any(
709
specific_files, newpath_decoded))):
712
if oldpath_decoded is None:
713
fileid = new_mapping.generate_file_id(newpath_decoded)
722
oldexe = mode_is_executable(oldmode)
723
oldkind = mode_kind(oldmode)
727
if oldpath_decoded == u'':
731
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
732
oldparent = old_mapping.generate_file_id(oldparentpath)
733
fileid = old_mapping.generate_file_id(oldpath_decoded)
734
if newpath_decoded is None:
741
newversioned = (newpath_decoded not in target_extras)
743
newexe = mode_is_executable(newmode)
744
newkind = mode_kind(newmode)
748
if newpath_decoded == u'':
752
newparentpath, newname = osutils.split(newpath_decoded)
753
newparent = new_mapping.generate_file_id(newparentpath)
754
if old_mapping.is_special_file(oldpath):
756
if new_mapping.is_special_file(newpath):
758
if oldpath is None and newpath is None:
760
change = _mod_tree.TreeChange(
761
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
762
(oldversioned, newversioned),
763
(oldparent, newparent), (oldname, newname),
764
(oldkind, newkind), (oldexe, newexe))
766
added.append((newpath, newkind))
767
elif newpath is None or newmode == 0:
768
ret.removed.append(change)
769
elif oldpath != newpath:
770
ret.renamed.append(change)
771
elif mode_kind(oldmode) != mode_kind(newmode):
772
ret.kind_changed.append(change)
773
elif oldsha != newsha or oldmode != newmode:
774
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
776
ret.modified.append(change)
778
ret.unchanged.append(change)
780
implicit_dirs = {b''}
781
for path, kind in added:
782
if kind == 'directory' or path in target_extras:
784
implicit_dirs.update(osutils.parent_directories(path))
786
for path, kind in added:
787
if kind == 'directory' and path not in implicit_dirs:
789
path_decoded = osutils.normalized_filename(path)[0]
790
parent_path, basename = osutils.split(path_decoded)
791
parent_id = new_mapping.generate_file_id(parent_path)
792
if path in target_extras:
793
ret.unversioned.append(_mod_tree.TreeChange(
794
None, (None, path_decoded),
795
True, (False, False), (None, parent_id),
796
(None, basename), (None, kind), (None, False)))
798
file_id = new_mapping.generate_file_id(path_decoded)
800
_mod_tree.TreeChange(
801
file_id, (None, path_decoded), True,
804
(None, basename), (None, kind), (None, False)))
809
def changes_from_git_changes(changes, mapping, specific_files=None,
810
include_unchanged=False, target_extras=None):
811
"""Create a iter_changes-like generator from a git stream.
813
source and target are iterators over tuples with:
814
(filename, sha, mode)
816
if target_extras is None:
817
target_extras = set()
818
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
819
if oldpath is not None:
820
oldpath_decoded = oldpath.decode('utf-8')
822
oldpath_decoded = None
823
if newpath is not None:
824
newpath_decoded = newpath.decode('utf-8')
826
newpath_decoded = None
827
if not (specific_files is None or
828
(oldpath_decoded is not None and
829
osutils.is_inside_or_parent_of_any(
830
specific_files, oldpath_decoded)) or
831
(newpath_decoded is not None and
832
osutils.is_inside_or_parent_of_any(
833
specific_files, newpath_decoded))):
835
if oldpath is not None and mapping.is_special_file(oldpath):
837
if newpath is not None and mapping.is_special_file(newpath):
839
if oldpath_decoded is None:
840
fileid = mapping.generate_file_id(newpath_decoded)
849
oldexe = mode_is_executable(oldmode)
850
oldkind = mode_kind(oldmode)
854
if oldpath_decoded == u'':
858
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
859
oldparent = mapping.generate_file_id(oldparentpath)
860
fileid = mapping.generate_file_id(oldpath_decoded)
861
if newpath_decoded is None:
868
newversioned = (newpath_decoded not in target_extras)
870
newexe = mode_is_executable(newmode)
871
newkind = mode_kind(newmode)
875
if newpath_decoded == u'':
879
newparentpath, newname = osutils.split(newpath_decoded)
880
newparent = mapping.generate_file_id(newparentpath)
881
if (not include_unchanged and
882
oldkind == 'directory' and newkind == 'directory' and
883
oldpath_decoded == newpath_decoded):
885
yield _mod_tree.TreeChange(
886
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
887
(oldversioned, newversioned),
888
(oldparent, newparent), (oldname, newname),
889
(oldkind, newkind), (oldexe, newexe))
892
class InterGitTrees(_mod_tree.InterTree):
893
"""InterTree that works between two git trees."""
895
_matching_from_tree_format = None
896
_matching_to_tree_format = None
897
_test_mutable_trees_to_test_trees = None
900
def is_compatible(cls, source, target):
901
return (isinstance(source, GitRevisionTree) and
902
isinstance(target, GitRevisionTree))
904
def compare(self, want_unchanged=False, specific_files=None,
905
extra_trees=None, require_versioned=False, include_root=False,
906
want_unversioned=False):
907
with self.lock_read():
908
changes, target_extras = self._iter_git_changes(
909
want_unchanged=want_unchanged,
910
require_versioned=require_versioned,
911
specific_files=specific_files,
912
extra_trees=extra_trees,
913
want_unversioned=want_unversioned)
914
return tree_delta_from_git_changes(
915
changes, (self.source.mapping, self.target.mapping),
916
specific_files=specific_files,
917
include_root=include_root, target_extras=target_extras)
919
def iter_changes(self, include_unchanged=False, specific_files=None,
920
pb=None, extra_trees=[], require_versioned=True,
921
want_unversioned=False):
922
with self.lock_read():
923
changes, target_extras = self._iter_git_changes(
924
want_unchanged=include_unchanged,
925
require_versioned=require_versioned,
926
specific_files=specific_files,
927
extra_trees=extra_trees,
928
want_unversioned=want_unversioned)
929
return changes_from_git_changes(
930
changes, self.target.mapping,
931
specific_files=specific_files,
932
include_unchanged=include_unchanged,
933
target_extras=target_extras)
935
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
936
require_versioned=False, extra_trees=None,
937
want_unversioned=False):
938
raise NotImplementedError(self._iter_git_changes)
941
class InterGitRevisionTrees(InterGitTrees):
942
"""InterTree that works between two git revision trees."""
944
_matching_from_tree_format = None
945
_matching_to_tree_format = None
946
_test_mutable_trees_to_test_trees = None
949
def is_compatible(cls, source, target):
950
return (isinstance(source, GitRevisionTree) and
951
isinstance(target, GitRevisionTree))
953
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
954
require_versioned=True, extra_trees=None,
955
want_unversioned=False):
956
trees = [self.source]
957
if extra_trees is not None:
958
trees.extend(extra_trees)
959
if specific_files is not None:
960
specific_files = self.target.find_related_paths_across_trees(
961
specific_files, trees,
962
require_versioned=require_versioned)
964
if (self.source._repository._git.object_store !=
965
self.target._repository._git.object_store):
966
store = OverlayObjectStore(
967
[self.source._repository._git.object_store,
968
self.target._repository._git.object_store])
970
store = self.source._repository._git.object_store
971
return store.tree_changes(
972
self.source.tree, self.target.tree, want_unchanged=want_unchanged,
973
include_trees=True, change_type_same=True), set()
976
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
979
class MutableGitIndexTree(mutabletree.MutableTree):
982
self._lock_mode = None
984
self._versioned_dirs = None
985
self._index_dirty = False
987
def is_versioned(self, path):
988
with self.lock_read():
989
path = path.rstrip('/').encode('utf-8')
990
(index, subpath) = self._lookup_index(path)
991
return (subpath in index or self._has_dir(path))
993
def _has_dir(self, path):
994
if not isinstance(path, bytes):
995
raise TypeError(path)
998
if self._versioned_dirs is None:
1000
return path in self._versioned_dirs
1002
def _load_dirs(self):
1003
if self._lock_mode is None:
1004
raise errors.ObjectNotLocked(self)
1005
self._versioned_dirs = set()
1006
# TODO(jelmer): Browse over all indexes
1007
for p, i in self._recurse_index_entries():
1008
self._ensure_versioned_dir(posixpath.dirname(p))
1010
def _ensure_versioned_dir(self, dirname):
1011
if not isinstance(dirname, bytes):
1012
raise TypeError(dirname)
1013
if dirname in self._versioned_dirs:
1016
self._ensure_versioned_dir(posixpath.dirname(dirname))
1017
self._versioned_dirs.add(dirname)
1019
def path2id(self, path):
1020
with self.lock_read():
1021
path = path.rstrip('/')
1022
if self.is_versioned(path.rstrip('/')):
1023
return self.mapping.generate_file_id(
1024
osutils.safe_unicode(path))
1027
def has_id(self, file_id):
1029
self.id2path(file_id)
1030
except errors.NoSuchId:
1035
def id2path(self, file_id):
1038
if type(file_id) is not bytes:
1039
raise TypeError(file_id)
1040
with self.lock_read():
1042
path = self.mapping.parse_file_id(file_id)
1044
raise errors.NoSuchId(self, file_id)
1045
if self.is_versioned(path):
1047
raise errors.NoSuchId(self, file_id)
1049
def _set_root_id(self, file_id):
1050
raise errors.UnsupportedOperation(self._set_root_id, self)
1052
def _add(self, files, ids, kinds):
1053
for (path, file_id, kind) in zip(files, ids, kinds):
1054
if file_id is not None:
1055
raise workingtree.SettingFileIdUnsupported()
1056
path, can_access = osutils.normalized_filename(path)
1058
raise errors.InvalidNormalization(path)
1059
self._index_add_entry(path, kind)
1061
def _read_submodule_head(self, path):
1062
raise NotImplementedError(self._read_submodule_head)
1064
def _lookup_index(self, encoded_path):
1065
if not isinstance(encoded_path, bytes):
1066
raise TypeError(encoded_path)
1067
# TODO(jelmer): Look in other indexes
1068
return self.index, encoded_path
1070
def _index_del_entry(self, index, path):
1072
# TODO(jelmer): Keep track of dirty per index
1073
self._index_dirty = True
1075
def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
1076
if kind == "directory":
1077
# Git indexes don't contain directories
1082
file, stat_val = self.get_file_with_stat(path)
1083
except (errors.NoSuchFile, IOError):
1084
# TODO: Rather than come up with something here, use the old
1087
stat_val = os.stat_result(
1088
(stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1090
blob.set_raw_string(file.read())
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 == "symlink":
1098
stat_val = self._lstat(path)
1099
except EnvironmentError:
1100
# TODO: Rather than come up with something here, use the
1102
stat_val = os.stat_result(
1103
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1104
blob.set_raw_string(
1105
self.get_symlink_target(path).encode("utf-8"))
1106
# Add object to the repository if it didn't exist yet
1107
if blob.id not in self.store:
1108
self.store.add_object(blob)
1110
elif kind == "tree-reference":
1111
if reference_revision is not None:
1112
hexsha = self.branch.lookup_bzr_revision_id(
1113
reference_revision)[0]
1115
hexsha = self._read_submodule_head(path)
1117
raise errors.NoCommits(path)
1119
stat_val = self._lstat(path)
1120
except EnvironmentError:
1121
stat_val = os.stat_result(
1122
(S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1123
stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
1125
raise AssertionError("unknown kind '%s'" % kind)
1126
# Add an entry to the index or update the existing entry
1127
ensure_normalized_path(path)
1128
encoded_path = path.encode("utf-8")
1129
if b'\r' in encoded_path or b'\n' in encoded_path:
1130
# TODO(jelmer): Why do we need to do this?
1131
trace.mutter('ignoring path with invalid newline in it: %r', path)
1133
(index, index_path) = self._lookup_index(encoded_path)
1134
index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
1135
self._index_dirty = True
1136
if self._versioned_dirs is not None:
1137
self._ensure_versioned_dir(index_path)
1139
def _recurse_index_entries(self, index=None, basepath=b""):
1140
# Iterate over all index entries
1141
with self.lock_read():
1144
for path, value in index.items():
1145
yield (posixpath.join(basepath, path), value)
1146
(ctime, mtime, dev, ino, mode, uid, gid, size, sha,
1148
if S_ISGITLINK(mode):
1149
pass # TODO(jelmer): dive into submodule
1151
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
1153
raise NotImplementedError(self.iter_entries_by_dir)
1154
with self.lock_read():
1155
if specific_files is not None:
1156
specific_files = set(specific_files)
1158
specific_files = None
1159
root_ie = self._get_dir_ie(u"", None)
1161
if specific_files is None or u"" in specific_files:
1162
ret[(u"", u"")] = root_ie
1163
dir_ids = {u"": root_ie.file_id}
1164
for path, value in self._recurse_index_entries():
1165
if self.mapping.is_special_file(path):
1167
path = path.decode("utf-8")
1168
if specific_files is not None and path not in specific_files:
1170
(parent, name) = posixpath.split(path)
1172
file_ie = self._get_file_ie(name, path, value, None)
1173
except errors.NoSuchFile:
1175
if yield_parents or specific_files is None:
1176
for (dir_path, dir_ie) in self._add_missing_parent_ids(
1178
ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
1179
file_ie.parent_id = self.path2id(parent)
1180
ret[(posixpath.dirname(path), path)] = file_ie
1181
return ((path, ie) for ((_, path), ie) in sorted(viewitems(ret)))
1183
def iter_references(self):
1184
# TODO(jelmer): Implement a more efficient version of this
1185
for path, entry in self.iter_entries_by_dir():
1186
if entry.kind == 'tree-reference':
1189
def _get_dir_ie(self, path, parent_id):
1190
file_id = self.path2id(path)
1191
return GitTreeDirectory(file_id,
1192
posixpath.basename(path).strip("/"), parent_id)
1194
def _get_file_ie(self, name, path, value, parent_id):
1195
if not isinstance(name, text_type):
1196
raise TypeError(name)
1197
if not isinstance(path, text_type):
1198
raise TypeError(path)
1199
if not isinstance(value, tuple) or len(value) != 10:
1200
raise TypeError(value)
1201
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1202
file_id = self.path2id(path)
1203
if not isinstance(file_id, bytes):
1204
raise TypeError(file_id)
1205
kind = mode_kind(mode)
1206
ie = entry_factory[kind](file_id, name, parent_id)
1207
if kind == 'symlink':
1208
ie.symlink_target = self.get_symlink_target(path)
1209
elif kind == 'tree-reference':
1210
ie.reference_revision = self.get_reference_revision(path)
1213
data = self.get_file_text(path)
1214
except errors.NoSuchFile:
1216
except IOError as e:
1217
if e.errno != errno.ENOENT:
1221
data = self.branch.repository._git.object_store[sha].data
1222
ie.text_sha1 = osutils.sha_string(data)
1223
ie.text_size = len(data)
1224
ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1227
def _add_missing_parent_ids(self, path, dir_ids):
1230
parent = posixpath.dirname(path).strip("/")
1231
ret = self._add_missing_parent_ids(parent, dir_ids)
1232
parent_id = dir_ids[parent]
1233
ie = self._get_dir_ie(path, parent_id)
1234
dir_ids[path] = ie.file_id
1235
ret.append((path, ie))
1238
def _comparison_data(self, entry, path):
1240
return None, False, None
1241
return entry.kind, entry.executable, None
1243
def _unversion_path(self, path):
1244
if self._lock_mode is None:
1245
raise errors.ObjectNotLocked(self)
1246
encoded_path = path.encode("utf-8")
1248
(index, subpath) = self._lookup_index(encoded_path)
1250
self._index_del_entry(index, encoded_path)
1252
# A directory, perhaps?
1253
# TODO(jelmer): Deletes that involve submodules?
1254
for p in list(index):
1255
if p.startswith(subpath + b"/"):
1257
self._index_del_entry(index, p)
1260
self._versioned_dirs = None
1263
def unversion(self, paths):
1264
with self.lock_tree_write():
1266
if self._unversion_path(path) == 0:
1267
raise errors.NoSuchFile(path)
1268
self._versioned_dirs = None
1274
def update_basis_by_delta(self, revid, delta):
1275
# TODO(jelmer): This shouldn't be called, it's inventory specific.
1276
for (old_path, new_path, file_id, ie) in delta:
1277
if old_path is not None:
1278
(index, old_subpath) = self._lookup_index(
1279
old_path.encode('utf-8'))
1280
if old_subpath in index:
1281
self._index_del_entry(index, old_subpath)
1282
self._versioned_dirs = None
1283
if new_path is not None and ie.kind != 'directory':
1284
self._index_add_entry(new_path, ie.kind)
1286
self._set_merges_from_parent_ids([])
1288
def move(self, from_paths, to_dir=None, after=None):
1290
with self.lock_tree_write():
1291
to_abs = self.abspath(to_dir)
1292
if not os.path.isdir(to_abs):
1293
raise errors.BzrMoveFailedError('', to_dir,
1294
errors.NotADirectory(to_abs))
1296
for from_rel in from_paths:
1297
from_tail = os.path.split(from_rel)[-1]
1298
to_rel = os.path.join(to_dir, from_tail)
1299
self.rename_one(from_rel, to_rel, after=after)
1300
rename_tuples.append((from_rel, to_rel))
1302
return rename_tuples
1304
def rename_one(self, from_rel, to_rel, after=None):
1305
from_path = from_rel.encode("utf-8")
1306
to_rel, can_access = osutils.normalized_filename(to_rel)
1308
raise errors.InvalidNormalization(to_rel)
1309
to_path = to_rel.encode("utf-8")
1310
with self.lock_tree_write():
1312
# Perhaps it's already moved?
1314
not self.has_filename(from_rel) and
1315
self.has_filename(to_rel) and
1316
not self.is_versioned(to_rel))
1318
if not self.has_filename(to_rel):
1319
raise errors.BzrMoveFailedError(
1320
from_rel, to_rel, errors.NoSuchFile(to_rel))
1321
if self.basis_tree().is_versioned(to_rel):
1322
raise errors.BzrMoveFailedError(
1323
from_rel, to_rel, errors.AlreadyVersionedError(to_rel))
1325
kind = self.kind(to_rel)
1328
to_kind = self.kind(to_rel)
1329
except errors.NoSuchFile:
1330
exc_type = errors.BzrRenameFailedError
1333
exc_type = errors.BzrMoveFailedError
1334
if self.is_versioned(to_rel):
1335
raise exc_type(from_rel, to_rel,
1336
errors.AlreadyVersionedError(to_rel))
1337
if not self.has_filename(from_rel):
1338
raise errors.BzrMoveFailedError(
1339
from_rel, to_rel, errors.NoSuchFile(from_rel))
1340
kind = self.kind(from_rel)
1341
if not self.is_versioned(from_rel) and kind != 'directory':
1342
raise exc_type(from_rel, to_rel,
1343
errors.NotVersionedError(from_rel))
1344
if self.has_filename(to_rel):
1345
raise errors.RenameFailedFilesExist(
1346
from_rel, to_rel, errors.FileExists(to_rel))
1348
kind = self.kind(from_rel)
1350
if not after and kind != 'directory':
1351
(index, from_subpath) = self._lookup_index(from_path)
1352
if from_subpath not in index:
1354
raise errors.BzrMoveFailedError(
1356
errors.NotVersionedError(path=from_rel))
1360
self._rename_one(from_rel, to_rel)
1361
except OSError as e:
1362
if e.errno == errno.ENOENT:
1363
raise errors.BzrMoveFailedError(
1364
from_rel, to_rel, errors.NoSuchFile(to_rel))
1366
if kind != 'directory':
1367
(index, from_index_path) = self._lookup_index(from_path)
1369
self._index_del_entry(index, from_path)
1372
self._index_add_entry(to_rel, kind)
1374
todo = [(p, i) for (p, i) in self._recurse_index_entries()
1375
if p.startswith(from_path + b'/')]
1376
for child_path, child_value in todo:
1377
(child_to_index, child_to_index_path) = self._lookup_index(
1378
posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
1379
child_to_index[child_to_index_path] = child_value
1380
# TODO(jelmer): Mark individual index as dirty
1381
self._index_dirty = True
1382
(child_from_index, child_from_index_path) = self._lookup_index(
1384
self._index_del_entry(
1385
child_from_index, child_from_index_path)
1387
self._versioned_dirs = None
1390
def find_related_paths_across_trees(self, paths, trees=[],
1391
require_versioned=True):
1395
if require_versioned:
1396
trees = [self] + (trees if trees is not None else [])
1400
if t.is_versioned(p):
1405
raise errors.PathsNotVersionedError(unversioned)
1407
return filter(self.is_versioned, paths)
1409
def path_content_summary(self, path):
1410
"""See Tree.path_content_summary."""
1412
stat_result = self._lstat(path)
1413
except OSError as e:
1414
if getattr(e, 'errno', None) == errno.ENOENT:
1416
return ('missing', None, None, None)
1417
# propagate other errors
1419
kind = mode_kind(stat_result.st_mode)
1421
return self._file_content_summary(path, stat_result)
1422
elif kind == 'directory':
1423
# perhaps it looks like a plain directory, but it's really a
1425
if self._directory_is_tree_reference(path):
1426
kind = 'tree-reference'
1427
return kind, None, None, None
1428
elif kind == 'symlink':
1429
target = osutils.readlink(self.abspath(path))
1430
return ('symlink', None, None, target)
1432
return (kind, None, None, None)
1434
def kind(self, relpath):
1435
kind = osutils.file_kind(self.abspath(relpath))
1436
if kind == 'directory':
1437
(index, index_path) = self._lookup_index(relpath.encode('utf-8'))
1441
mode = index[index_path].mode
1445
if S_ISGITLINK(mode):
1446
return 'tree-reference'
1451
def _live_entry(self, relpath):
1452
raise NotImplementedError(self._live_entry)
1454
def get_transform(self, pb=None):
1455
from ..transform import TreeTransform
1456
return TreeTransform(self, pb=pb)
1460
class InterIndexGitTree(InterGitTrees):
1461
"""InterTree that works between a Git revision tree and an index."""
1463
def __init__(self, source, target):
1464
super(InterIndexGitTree, self).__init__(source, target)
1465
self._index = target.index
1468
def is_compatible(cls, source, target):
1469
return (isinstance(source, GitRevisionTree) and
1470
isinstance(target, MutableGitIndexTree))
1472
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1473
require_versioned=False, extra_trees=None,
1474
want_unversioned=False):
1475
trees = [self.source]
1476
if extra_trees is not None:
1477
trees.extend(extra_trees)
1478
if specific_files is not None:
1479
specific_files = self.target.find_related_paths_across_trees(
1480
specific_files, trees,
1481
require_versioned=require_versioned)
1482
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1483
with self.lock_read():
1484
return changes_between_git_tree_and_working_copy(
1485
self.source.store, self.source.tree,
1486
self.target, want_unchanged=want_unchanged,
1487
want_unversioned=want_unversioned)
1490
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
1493
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1494
want_unchanged=False,
1495
want_unversioned=False):
1496
"""Determine the changes between a git tree and a working tree with index.
1501
# Report dirified directories to commit_tree first, so that they can be
1502
# replaced with non-empty directories if they have contents.
1504
trust_executable = target._supports_executable()
1505
for path, index_entry in target._recurse_index_entries():
1507
live_entry = target._live_entry(path)
1508
except EnvironmentError as e:
1509
if e.errno == errno.ENOENT:
1510
# Entry was removed; keep it listed, but mark it as gone.
1511
blobs[path] = (ZERO_SHA, 0)
1512
elif e.errno == errno.EISDIR:
1513
# Backwards compatibility with Dulwich < 0.19.12;
1514
# newer versions of Dulwich return either an entry for the
1515
# submodule or None for directories.
1516
if S_ISGITLINK(index_entry.mode):
1517
blobs[path] = (index_entry.sha, index_entry.mode)
1519
# Entry was turned into a directory
1520
dirified.append((path, Tree().id, stat.S_IFDIR))
1521
store.add_object(Tree())
1525
if live_entry is None:
1526
# Entry was turned into a directory
1527
dirified.append((path, Tree().id, stat.S_IFDIR))
1528
store.add_object(Tree())
1530
mode = live_entry.mode
1531
if not trust_executable:
1532
if mode_is_executable(index_entry.mode):
1536
blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1537
if want_unversioned:
1538
for e in target.extras():
1539
st = target._lstat(e)
1541
np, accessible = osutils.normalized_filename(e)
1542
except UnicodeDecodeError:
1543
raise errors.BadFilenameEncoding(
1545
if stat.S_ISDIR(st.st_mode):
1548
blob = blob_from_path_and_stat(
1549
target.abspath(e).encode(osutils._fs_enc), st)
1550
store.add_object(blob)
1551
np = np.encode('utf-8')
1552
blobs[np] = (blob.id, cleanup_mode(st.st_mode))
1554
to_tree_sha = commit_tree(
1555
store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
1556
return store.tree_changes(
1557
from_tree_sha, to_tree_sha, include_trees=True,
1558
want_unchanged=want_unchanged, change_type_same=True), extras