1
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
from __future__ import absolute_import
22
from collections import deque
24
from io import BytesIO
27
from dulwich.index import (
28
blob_from_path_and_stat,
31
index_entry_from_stat,
33
from dulwich.object_store import (
37
from dulwich.objects import (
48
controldir as _mod_controldir,
58
from ..revision import (
62
from ..sixish import (
67
from .mapping import (
75
class GitTreeDirectory(_mod_tree.TreeDirectory):
77
__slots__ = ['file_id', 'name', 'parent_id', 'children']
79
def __init__(self, file_id, name, parent_id):
80
self.file_id = file_id
82
self.parent_id = parent_id
95
return self.__class__(
96
self.file_id, self.name, self.parent_id)
99
return "%s(file_id=%r, name=%r, parent_id=%r)" % (
100
self.__class__.__name__, self.file_id, self.name,
103
def __eq__(self, other):
104
return (self.kind == other.kind and
105
self.file_id == other.file_id and
106
self.name == other.name and
107
self.parent_id == other.parent_id)
110
class GitTreeFile(_mod_tree.TreeFile):
112
__slots__ = ['file_id', 'name', 'parent_id', 'text_size', 'text_sha1',
115
def __init__(self, file_id, name, parent_id, text_size=None,
116
text_sha1=None, executable=None):
117
self.file_id = file_id
119
self.parent_id = parent_id
120
self.text_size = text_size
121
self.text_sha1 = text_sha1
122
self.executable = executable
128
def __eq__(self, other):
129
return (self.kind == other.kind and
130
self.file_id == other.file_id and
131
self.name == other.name and
132
self.parent_id == other.parent_id and
133
self.text_sha1 == other.text_sha1 and
134
self.text_size == other.text_size and
135
self.executable == other.executable)
138
return ("%s(file_id=%r, name=%r, parent_id=%r, text_size=%r, "
139
"text_sha1=%r, executable=%r)") % (
140
type(self).__name__, self.file_id, self.name, self.parent_id,
141
self.text_size, self.text_sha1, self.executable)
144
ret = self.__class__(
145
self.file_id, self.name, self.parent_id)
146
ret.text_sha1 = self.text_sha1
147
ret.text_size = self.text_size
148
ret.executable = self.executable
152
class GitTreeSymlink(_mod_tree.TreeLink):
154
__slots__ = ['file_id', 'name', 'parent_id', 'symlink_target']
156
def __init__(self, file_id, name, parent_id,
157
symlink_target=None):
158
self.file_id = file_id
160
self.parent_id = parent_id
161
self.symlink_target = symlink_target
168
def executable(self):
176
return "%s(file_id=%r, name=%r, parent_id=%r, symlink_target=%r)" % (
177
type(self).__name__, self.file_id, self.name, self.parent_id,
180
def __eq__(self, other):
181
return (self.kind == other.kind and
182
self.file_id == other.file_id and
183
self.name == other.name and
184
self.parent_id == other.parent_id and
185
self.symlink_target == other.symlink_target)
188
return self.__class__(
189
self.file_id, self.name, self.parent_id,
193
class GitTreeSubmodule(_mod_tree.TreeLink):
195
__slots__ = ['file_id', 'name', 'parent_id', 'reference_revision']
197
def __init__(self, file_id, name, parent_id, reference_revision=None):
198
self.file_id = file_id
200
self.parent_id = parent_id
201
self.reference_revision = reference_revision
205
return 'tree-reference'
208
return ("%s(file_id=%r, name=%r, parent_id=%r, "
209
"reference_revision=%r)") % (
210
type(self).__name__, self.file_id, self.name, self.parent_id,
211
self.reference_revision)
213
def __eq__(self, other):
214
return (self.kind == other.kind and
215
self.file_id == other.file_id and
216
self.name == other.name and
217
self.parent_id == other.parent_id and
218
self.reference_revision == other.reference_revision)
221
return self.__class__(
222
self.file_id, self.name, self.parent_id,
223
self.reference_revision)
227
'directory': GitTreeDirectory,
229
'symlink': GitTreeSymlink,
230
'tree-reference': GitTreeSubmodule,
234
def ensure_normalized_path(path):
235
"""Check whether path is normalized.
237
:raises InvalidNormalization: When path is not normalized, and cannot be
238
accessed on this platform by the normalized path.
239
:return: The NFC normalised version of path.
241
norm_path, can_access = osutils.normalized_filename(path)
242
if norm_path != path:
246
raise errors.InvalidNormalization(path)
250
class GitRevisionTree(revisiontree.RevisionTree):
251
"""Revision tree implementation based on Git objects."""
253
def __init__(self, repository, revision_id):
254
self._revision_id = revision_id
255
self._repository = repository
256
self._submodules = None
257
self.store = repository._git.object_store
258
if not isinstance(revision_id, bytes):
259
raise TypeError(revision_id)
260
self.commit_id, self.mapping = repository.lookup_bzr_revision_id(
262
if revision_id == NULL_REVISION:
264
self.mapping = default_mapping
265
self._fileid_map = GitFileIdMap(
270
commit = self.store[self.commit_id]
272
raise errors.NoSuchRevision(repository, revision_id)
273
self.tree = commit.tree
274
self._fileid_map = self.mapping.get_fileid_map(
275
self.store.__getitem__, self.tree)
277
def _submodule_info(self):
278
if self._submodules is None:
280
with self.get_file('.gitmodules') as f:
281
config = GitConfigFile.from_file(f)
284
for path, url, section in parse_submodules(config)}
285
except errors.NoSuchFile:
286
self._submodules = {}
287
return self._submodules
289
def _get_submodule_repository(self, relpath):
290
if not isinstance(relpath, bytes):
291
raise TypeError(relpath)
293
info = self._submodule_info()[relpath]
295
nested_repo_transport = self._repository.user_transport.clone(relpath.decode('utf-8'))
297
nested_repo_transport = self._repository.control_transport.clone(
298
posixpath.join('modules', info[0]))
299
nested_controldir = _mod_controldir.ControlDir.open_from_transport(
300
nested_repo_transport)
301
return nested_controldir.find_repository()
303
def get_nested_tree(self, path):
304
encoded_path = path.encode('utf-8')
305
nested_repo = self._get_submodule_repository(encoded_path)
306
ref_rev = self.get_reference_revision(path)
307
return nested_repo.revision_tree(ref_rev)
309
def supports_rename_tracking(self):
312
def get_file_revision(self, path):
313
change_scanner = self._repository._file_change_scanner
314
if self.commit_id == ZERO_SHA:
316
(unused_path, commit_id) = change_scanner.find_last_change_revision(
317
path.encode('utf-8'), self.commit_id)
318
return self._repository.lookup_foreign_revision_id(
319
commit_id, self.mapping)
321
def get_file_mtime(self, path):
323
revid = self.get_file_revision(path)
325
raise errors.NoSuchFile(path)
327
rev = self._repository.get_revision(revid)
328
except errors.NoSuchRevision:
329
raise _mod_tree.FileTimestampUnavailable(path)
332
def id2path(self, file_id):
334
path = self._fileid_map.lookup_path(file_id)
336
raise errors.NoSuchId(self, file_id)
337
if self.is_versioned(path):
339
raise errors.NoSuchId(self, file_id)
341
def is_versioned(self, path):
342
return self.has_filename(path)
344
def path2id(self, path):
345
if self.mapping.is_special_file(path):
347
if not self.is_versioned(path):
349
return self._fileid_map.lookup_file_id(osutils.safe_unicode(path))
351
def all_file_ids(self):
352
raise errors.UnsupportedOperation(self.all_file_ids, self)
354
def all_versioned_paths(self):
356
todo = [(self.store, b'', self.tree)]
358
(store, path, tree_id) = todo.pop()
361
tree = store[tree_id]
362
for name, mode, hexsha in tree.items():
363
subpath = posixpath.join(path, name)
364
ret.add(subpath.decode('utf-8'))
365
if stat.S_ISDIR(mode):
366
todo.append((store, subpath, hexsha))
369
def get_root_id(self):
370
if self.tree is None:
372
return self.path2id("")
374
def has_or_had_id(self, file_id):
376
self.id2path(file_id)
377
except errors.NoSuchId:
381
def has_id(self, file_id):
383
path = self.id2path(file_id)
384
except errors.NoSuchId:
386
return self.has_filename(path)
388
def _lookup_path(self, path):
389
if self.tree is None:
390
raise errors.NoSuchFile(path)
392
(mode, hexsha) = tree_lookup_path(
393
self.store.__getitem__, self.tree, path.encode('utf-8'))
395
raise errors.NoSuchFile(self, path)
397
return (self.store, mode, hexsha)
399
def is_executable(self, path):
400
(store, mode, hexsha) = self._lookup_path(path)
402
# the tree root is a directory
404
return mode_is_executable(mode)
406
def kind(self, path):
407
(store, mode, hexsha) = self._lookup_path(path)
409
# the tree root is a directory
411
return mode_kind(mode)
413
def has_filename(self, path):
415
self._lookup_path(path)
416
except errors.NoSuchFile:
421
def list_files(self, include_root=False, from_dir=None, recursive=True):
422
if self.tree is None:
424
if from_dir is None or from_dir == '.':
426
(store, mode, hexsha) = self._lookup_path(from_dir)
427
if mode is None: # Root
428
root_ie = self._get_dir_ie(b"", None)
430
parent_path = posixpath.dirname(from_dir)
431
parent_id = self._fileid_map.lookup_file_id(parent_path)
432
if mode_kind(mode) == 'directory':
433
root_ie = self._get_dir_ie(from_dir.encode("utf-8"), parent_id)
435
root_ie = self._get_file_ie(
436
store, from_dir.encode("utf-8"),
437
posixpath.basename(from_dir), mode, hexsha)
439
yield (from_dir, "V", root_ie.kind, root_ie)
441
if root_ie.kind == 'directory':
442
todo.append((store, from_dir.encode("utf-8"),
443
b"", hexsha, root_ie.file_id))
445
(store, path, relpath, hexsha, parent_id) = todo.pop()
447
for name, mode, hexsha in tree.iteritems():
448
if self.mapping.is_special_file(name):
450
child_path = posixpath.join(path, name)
451
child_relpath = posixpath.join(relpath, name)
452
if stat.S_ISDIR(mode):
453
ie = self._get_dir_ie(child_path, parent_id)
456
(store, child_path, child_relpath, hexsha,
459
ie = self._get_file_ie(
460
store, child_path, name, mode, hexsha, parent_id)
461
yield (child_relpath.decode('utf-8'), "V", ie.kind, ie)
463
def _get_file_ie(self, store, path, name, mode, hexsha, parent_id):
464
if not isinstance(path, bytes):
465
raise TypeError(path)
466
if not isinstance(name, bytes):
467
raise TypeError(name)
468
kind = mode_kind(mode)
469
path = path.decode('utf-8')
470
name = name.decode("utf-8")
471
file_id = self._fileid_map.lookup_file_id(path)
472
ie = entry_factory[kind](file_id, name, parent_id)
473
if kind == 'symlink':
474
ie.symlink_target = store[hexsha].data.decode('utf-8')
475
elif kind == 'tree-reference':
476
ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(
479
data = store[hexsha].data
480
ie.text_sha1 = osutils.sha_string(data)
481
ie.text_size = len(data)
482
ie.executable = mode_is_executable(mode)
485
def _get_dir_ie(self, path, parent_id):
486
path = path.decode('utf-8')
487
file_id = self._fileid_map.lookup_file_id(path)
488
return GitTreeDirectory(file_id, posixpath.basename(path), parent_id)
490
def iter_child_entries(self, path):
491
(store, mode, tree_sha) = self._lookup_path(path)
493
if mode is not None and not stat.S_ISDIR(mode):
496
encoded_path = path.encode('utf-8')
497
file_id = self.path2id(path)
498
tree = store[tree_sha]
499
for name, mode, hexsha in tree.iteritems():
500
if self.mapping.is_special_file(name):
502
child_path = posixpath.join(encoded_path, name)
503
if stat.S_ISDIR(mode):
504
yield self._get_dir_ie(child_path, file_id)
506
yield self._get_file_ie(store, child_path, name, mode, hexsha,
509
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
510
if self.tree is None:
513
# TODO(jelmer): Support yield parents
514
raise NotImplementedError
515
if specific_files is not None:
516
if specific_files in ([""], []):
517
specific_files = None
519
specific_files = set([p.encode('utf-8')
520
for p in specific_files])
521
todo = deque([(self.store, b"", self.tree, self.get_root_id())])
522
if specific_files is None or u"" in specific_files:
523
yield u"", self._get_dir_ie(b"", None)
525
store, path, tree_sha, parent_id = todo.popleft()
526
tree = store[tree_sha]
528
for name, mode, hexsha in tree.iteritems():
529
if self.mapping.is_special_file(name):
531
child_path = posixpath.join(path, name)
532
child_path_decoded = child_path.decode('utf-8')
533
if stat.S_ISDIR(mode):
534
if (specific_files is None or
535
any([p for p in specific_files if p.startswith(
538
(store, child_path, hexsha,
539
self.path2id(child_path_decoded)))
540
if specific_files is None or child_path in specific_files:
541
if stat.S_ISDIR(mode):
542
yield (child_path_decoded,
543
self._get_dir_ie(child_path, parent_id))
545
yield (child_path_decoded,
546
self._get_file_ie(store, child_path, name, mode,
548
todo.extendleft(reversed(extradirs))
550
def iter_references(self):
551
if self.supports_tree_reference():
552
for path, entry in self.iter_entries_by_dir():
553
if entry.kind == 'tree-reference':
556
def get_revision_id(self):
557
"""See RevisionTree.get_revision_id."""
558
return self._revision_id
560
def get_file_sha1(self, path, stat_value=None):
561
if self.tree is None:
562
raise errors.NoSuchFile(path)
563
return osutils.sha_string(self.get_file_text(path))
565
def get_file_verifier(self, path, stat_value=None):
566
(store, mode, hexsha) = self._lookup_path(path)
567
return ("GIT", hexsha)
569
def get_file_size(self, path):
570
(store, mode, hexsha) = self._lookup_path(path)
571
if stat.S_ISREG(mode):
572
return len(store[hexsha].data)
575
def get_file_text(self, path):
576
"""See RevisionTree.get_file_text."""
577
(store, mode, hexsha) = self._lookup_path(path)
578
if stat.S_ISREG(mode):
579
return store[hexsha].data
583
def get_symlink_target(self, path):
584
"""See RevisionTree.get_symlink_target."""
585
(store, mode, hexsha) = self._lookup_path(path)
586
if stat.S_ISLNK(mode):
587
return store[hexsha].data.decode('utf-8')
591
def get_reference_revision(self, path):
592
"""See RevisionTree.get_symlink_target."""
593
(store, mode, hexsha) = self._lookup_path(path)
594
if S_ISGITLINK(mode):
595
nested_repo = self._get_submodule_repository(path.encode('utf-8'))
596
return nested_repo.lookup_foreign_revision_id(hexsha)
600
def _comparison_data(self, entry, path):
602
return None, False, None
603
return entry.kind, entry.executable, None
605
def path_content_summary(self, path):
606
"""See Tree.path_content_summary."""
608
(store, mode, hexsha) = self._lookup_path(path)
609
except errors.NoSuchFile:
610
return ('missing', None, None, None)
611
kind = mode_kind(mode)
613
executable = mode_is_executable(mode)
614
contents = store[hexsha].data
615
return (kind, len(contents), executable,
616
osutils.sha_string(contents))
617
elif kind == 'symlink':
618
return (kind, None, None, store[hexsha].data.decode('utf-8'))
619
elif kind == 'tree-reference':
620
nested_repo = self._get_submodule_repository(path.encode('utf-8'))
621
return (kind, None, None,
622
nested_repo.lookup_foreign_revision_id(hexsha))
624
return (kind, None, None, None)
626
def find_related_paths_across_trees(self, paths, trees=[],
627
require_versioned=True):
630
if require_versioned:
631
trees = [self] + (trees if trees is not None else [])
635
if t.is_versioned(p):
640
raise errors.PathsNotVersionedError(unversioned)
641
return filter(self.is_versioned, paths)
643
def _iter_tree_contents(self, include_trees=False):
644
if self.tree is None:
646
return self.store.iter_tree_contents(
647
self.tree, include_trees=include_trees)
649
def annotate_iter(self, path, default_revision=CURRENT_REVISION):
650
"""Return an iterator of revision_id, line tuples.
652
For working trees (and mutable trees in general), the special
653
revision_id 'current:' will be used for lines that are new in this
654
tree, e.g. uncommitted changes.
655
:param default_revision: For lines that don't match a basis, mark them
656
with this revision id. Not all implementations will make use of
659
with self.lock_read():
660
# Now we have the parents of this content
661
from breezy.annotate import Annotator
662
from .annotate import AnnotateProvider
663
annotator = Annotator(AnnotateProvider(
664
self._repository._file_change_scanner))
665
this_key = (path, self.get_file_revision(path))
666
annotations = [(key[-1], line)
667
for key, line in annotator.annotate_flat(this_key)]
670
def _get_rules_searcher(self, default_searcher):
671
return default_searcher
673
def walkdirs(self, prefix=u""):
674
(store, mode, hexsha) = self._lookup_path(prefix)
676
[(store, prefix.encode('utf-8'), hexsha, self.path2id(prefix))])
678
store, path, tree_sha, parent_id = todo.popleft()
679
path_decoded = path.decode('utf-8')
680
tree = store[tree_sha]
682
for name, mode, hexsha in tree.iteritems():
683
if self.mapping.is_special_file(name):
685
child_path = posixpath.join(path, name)
686
file_id = self.path2id(child_path.decode('utf-8'))
687
if stat.S_ISDIR(mode):
688
todo.append((store, child_path, hexsha, file_id))
690
(child_path.decode('utf-8'), name.decode('utf-8'),
691
mode_kind(mode), None,
692
file_id, mode_kind(mode)))
693
yield (path_decoded, parent_id), children
696
def tree_delta_from_git_changes(changes, mapping,
697
fileid_maps, specific_files=None,
698
require_versioned=False, include_root=False,
700
"""Create a TreeDelta from two git trees.
702
source and target are iterators over tuples with:
703
(filename, sha, mode)
705
(old_fileid_map, new_fileid_map) = fileid_maps
706
if target_extras is None:
707
target_extras = set()
708
ret = delta.TreeDelta()
710
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
711
if newpath == b'' and not include_root:
714
oldpath_decoded = None
716
oldpath_decoded = oldpath.decode('utf-8')
718
newpath_decoded = None
720
newpath_decoded = newpath.decode('utf-8')
721
if not (specific_files is None or
722
(oldpath is not None and
723
osutils.is_inside_or_parent_of_any(
724
specific_files, oldpath_decoded)) or
725
(newpath is not None and
726
osutils.is_inside_or_parent_of_any(
727
specific_files, newpath_decoded))):
729
if mapping.is_special_file(oldpath):
731
if mapping.is_special_file(newpath):
733
if oldpath is None and newpath is None:
736
added.append((newpath, mode_kind(newmode)))
737
elif newpath is None or newmode == 0:
738
file_id = old_fileid_map.lookup_file_id(oldpath_decoded)
739
ret.removed.append((oldpath_decoded, file_id, mode_kind(oldmode)))
740
elif oldpath != newpath:
741
file_id = old_fileid_map.lookup_file_id(oldpath_decoded)
743
(oldpath_decoded, newpath.decode('utf-8'), file_id,
744
mode_kind(newmode), (oldsha != newsha),
745
(oldmode != newmode)))
746
elif mode_kind(oldmode) != mode_kind(newmode):
747
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
748
ret.kind_changed.append(
749
(newpath_decoded, file_id, mode_kind(oldmode),
751
elif oldsha != newsha or oldmode != newmode:
752
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
754
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
756
(newpath_decoded, file_id, mode_kind(newmode),
757
(oldsha != newsha), (oldmode != newmode)))
759
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
760
ret.unchanged.append(
761
(newpath_decoded, file_id, mode_kind(newmode)))
763
implicit_dirs = {b''}
764
for path, kind in added:
765
if kind == 'directory' or path in target_extras:
767
implicit_dirs.update(osutils.parent_directories(path))
769
for path, kind in added:
770
if kind == 'directory' and path not in implicit_dirs:
772
path_decoded = osutils.normalized_filename(path)[0]
773
if path in target_extras:
774
ret.unversioned.append((path_decoded, None, kind))
776
file_id = new_fileid_map.lookup_file_id(path_decoded)
777
ret.added.append((path_decoded, file_id, kind))
782
def changes_from_git_changes(changes, mapping, specific_files=None,
783
include_unchanged=False, target_extras=None):
784
"""Create a iter_changes-like generator from a git stream.
786
source and target are iterators over tuples with:
787
(filename, sha, mode)
789
if target_extras is None:
790
target_extras = set()
791
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
792
if oldpath is not None:
793
oldpath_decoded = oldpath.decode('utf-8')
795
oldpath_decoded = None
796
if newpath is not None:
797
newpath_decoded = newpath.decode('utf-8')
799
newpath_decoded = None
800
if not (specific_files is None or
801
(oldpath_decoded is not None and
802
osutils.is_inside_or_parent_of_any(
803
specific_files, oldpath_decoded)) or
804
(newpath_decoded is not None and
805
osutils.is_inside_or_parent_of_any(
806
specific_files, newpath_decoded))):
808
if oldpath is not None and mapping.is_special_file(oldpath):
810
if newpath is not None and mapping.is_special_file(newpath):
812
if oldpath_decoded is None:
813
fileid = mapping.generate_file_id(newpath_decoded)
822
oldexe = mode_is_executable(oldmode)
823
oldkind = mode_kind(oldmode)
827
if oldpath_decoded == u'':
831
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
832
oldparent = mapping.generate_file_id(oldparentpath)
833
fileid = mapping.generate_file_id(oldpath_decoded)
834
if newpath_decoded is None:
841
newversioned = (newpath_decoded not in target_extras)
843
newexe = mode_is_executable(newmode)
844
newkind = mode_kind(newmode)
848
if newpath_decoded == u'':
852
newparentpath, newname = osutils.split(newpath_decoded)
853
newparent = mapping.generate_file_id(newparentpath)
854
if (not include_unchanged and
855
oldkind == 'directory' and newkind == 'directory' and
856
oldpath_decoded == newpath_decoded):
858
yield _mod_tree.TreeChange(
859
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
860
(oldversioned, newversioned),
861
(oldparent, newparent), (oldname, newname),
862
(oldkind, newkind), (oldexe, newexe))
865
class InterGitTrees(_mod_tree.InterTree):
866
"""InterTree that works between two git trees."""
868
_matching_from_tree_format = None
869
_matching_to_tree_format = None
870
_test_mutable_trees_to_test_trees = None
873
def is_compatible(cls, source, target):
874
return (isinstance(source, GitRevisionTree) and
875
isinstance(target, GitRevisionTree))
877
def compare(self, want_unchanged=False, specific_files=None,
878
extra_trees=None, require_versioned=False, include_root=False,
879
want_unversioned=False):
880
with self.lock_read():
881
changes, target_extras = self._iter_git_changes(
882
want_unchanged=want_unchanged,
883
require_versioned=require_versioned,
884
specific_files=specific_files,
885
extra_trees=extra_trees,
886
want_unversioned=want_unversioned)
887
source_fileid_map = self.source._fileid_map
888
target_fileid_map = self.target._fileid_map
889
return tree_delta_from_git_changes(
890
changes, self.target.mapping,
891
(source_fileid_map, target_fileid_map),
892
specific_files=specific_files,
893
include_root=include_root, target_extras=target_extras)
895
def iter_changes(self, include_unchanged=False, specific_files=None,
896
pb=None, extra_trees=[], require_versioned=True,
897
want_unversioned=False):
898
with self.lock_read():
899
changes, target_extras = self._iter_git_changes(
900
want_unchanged=include_unchanged,
901
require_versioned=require_versioned,
902
specific_files=specific_files,
903
extra_trees=extra_trees,
904
want_unversioned=want_unversioned)
905
return changes_from_git_changes(
906
changes, self.target.mapping,
907
specific_files=specific_files,
908
include_unchanged=include_unchanged,
909
target_extras=target_extras)
911
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
912
require_versioned=False, extra_trees=None,
913
want_unversioned=False):
914
raise NotImplementedError(self._iter_git_changes)
917
class InterGitRevisionTrees(InterGitTrees):
918
"""InterTree that works between two git revision trees."""
920
_matching_from_tree_format = None
921
_matching_to_tree_format = None
922
_test_mutable_trees_to_test_trees = None
925
def is_compatible(cls, source, target):
926
return (isinstance(source, GitRevisionTree) and
927
isinstance(target, GitRevisionTree))
929
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
930
require_versioned=True, extra_trees=None,
931
want_unversioned=False):
932
trees = [self.source]
933
if extra_trees is not None:
934
trees.extend(extra_trees)
935
if specific_files is not None:
936
specific_files = self.target.find_related_paths_across_trees(
937
specific_files, trees,
938
require_versioned=require_versioned)
940
if (self.source._repository._git.object_store !=
941
self.target._repository._git.object_store):
942
store = OverlayObjectStore(
943
[self.source._repository._git.object_store,
944
self.target._repository._git.object_store])
946
store = self.source._repository._git.object_store
947
return store.tree_changes(
948
self.source.tree, self.target.tree, want_unchanged=want_unchanged,
949
include_trees=True, change_type_same=True), set()
952
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
955
class MutableGitIndexTree(mutabletree.MutableTree):
958
self._lock_mode = None
960
self._versioned_dirs = None
961
self._index_dirty = False
963
def is_versioned(self, path):
964
with self.lock_read():
965
path = path.rstrip('/').encode('utf-8')
966
(index, subpath) = self._lookup_index(path)
967
return (subpath in index or self._has_dir(path))
969
def _has_dir(self, path):
970
if not isinstance(path, bytes):
971
raise TypeError(path)
974
if self._versioned_dirs is None:
976
return path in self._versioned_dirs
978
def _load_dirs(self):
979
if self._lock_mode is None:
980
raise errors.ObjectNotLocked(self)
981
self._versioned_dirs = set()
982
# TODO(jelmer): Browse over all indexes
983
for p, i in self._recurse_index_entries():
984
self._ensure_versioned_dir(posixpath.dirname(p))
986
def _ensure_versioned_dir(self, dirname):
987
if not isinstance(dirname, bytes):
988
raise TypeError(dirname)
989
if dirname in self._versioned_dirs:
992
self._ensure_versioned_dir(posixpath.dirname(dirname))
993
self._versioned_dirs.add(dirname)
995
def path2id(self, path):
996
with self.lock_read():
997
path = path.rstrip('/')
998
if self.is_versioned(path.rstrip('/')):
999
return self._fileid_map.lookup_file_id(
1000
osutils.safe_unicode(path))
1003
def has_id(self, file_id):
1005
self.id2path(file_id)
1006
except errors.NoSuchId:
1011
def id2path(self, file_id):
1014
if type(file_id) is not bytes:
1015
raise TypeError(file_id)
1016
with self.lock_read():
1018
path = self._fileid_map.lookup_path(file_id)
1020
raise errors.NoSuchId(self, file_id)
1021
if self.is_versioned(path):
1023
raise errors.NoSuchId(self, file_id)
1025
def _set_root_id(self, file_id):
1026
raise errors.UnsupportedOperation(self._set_root_id, self)
1028
def get_root_id(self):
1029
return self.path2id(u"")
1031
def _add(self, files, ids, kinds):
1032
for (path, file_id, kind) in zip(files, ids, kinds):
1033
if file_id is not None:
1034
raise workingtree.SettingFileIdUnsupported()
1035
path, can_access = osutils.normalized_filename(path)
1037
raise errors.InvalidNormalization(path)
1038
self._index_add_entry(path, kind)
1040
def _read_submodule_head(self, path):
1041
raise NotImplementedError(self._read_submodule_head)
1043
def _lookup_index(self, encoded_path):
1044
if not isinstance(encoded_path, bytes):
1045
raise TypeError(encoded_path)
1046
# TODO(jelmer): Look in other indexes
1047
return self.index, encoded_path
1049
def _index_del_entry(self, index, path):
1051
# TODO(jelmer): Keep track of dirty per index
1052
self._index_dirty = True
1054
def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
1055
if kind == "directory":
1056
# Git indexes don't contain directories
1061
file, stat_val = self.get_file_with_stat(path)
1062
except (errors.NoSuchFile, IOError):
1063
# TODO: Rather than come up with something here, use the old
1066
stat_val = os.stat_result(
1067
(stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1069
blob.set_raw_string(file.read())
1070
# Add object to the repository if it didn't exist yet
1071
if blob.id not in self.store:
1072
self.store.add_object(blob)
1074
elif kind == "symlink":
1077
stat_val = self._lstat(path)
1078
except EnvironmentError:
1079
# TODO: Rather than come up with something here, use the
1081
stat_val = os.stat_result(
1082
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1083
blob.set_raw_string(
1084
self.get_symlink_target(path).encode("utf-8"))
1085
# Add object to the repository if it didn't exist yet
1086
if blob.id not in self.store:
1087
self.store.add_object(blob)
1089
elif kind == "tree-reference":
1090
if reference_revision is not None:
1091
hexsha = self.branch.lookup_bzr_revision_id(
1092
reference_revision)[0]
1094
hexsha = self._read_submodule_head(path)
1096
raise errors.NoCommits(path)
1098
stat_val = self._lstat(path)
1099
except EnvironmentError:
1100
stat_val = os.stat_result(
1101
(S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1102
stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
1104
raise AssertionError("unknown kind '%s'" % kind)
1105
# Add an entry to the index or update the existing entry
1106
ensure_normalized_path(path)
1107
encoded_path = path.encode("utf-8")
1108
if b'\r' in encoded_path or b'\n' in encoded_path:
1109
# TODO(jelmer): Why do we need to do this?
1110
trace.mutter('ignoring path with invalid newline in it: %r', path)
1112
(index, index_path) = self._lookup_index(encoded_path)
1113
index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
1114
self._index_dirty = True
1115
if self._versioned_dirs is not None:
1116
self._ensure_versioned_dir(index_path)
1118
def _recurse_index_entries(self, index=None, basepath=b""):
1119
# Iterate over all index entries
1120
with self.lock_read():
1123
for path, value in index.items():
1124
yield (posixpath.join(basepath, path), value)
1125
(ctime, mtime, dev, ino, mode, uid, gid, size, sha,
1127
if S_ISGITLINK(mode):
1128
pass # TODO(jelmer): dive into submodule
1130
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
1132
raise NotImplementedError(self.iter_entries_by_dir)
1133
with self.lock_read():
1134
if specific_files is not None:
1135
specific_files = set(specific_files)
1137
specific_files = None
1138
root_ie = self._get_dir_ie(u"", None)
1140
if specific_files is None or u"" in specific_files:
1141
ret[(u"", u"")] = root_ie
1142
dir_ids = {u"": root_ie.file_id}
1143
for path, value in self._recurse_index_entries():
1144
if self.mapping.is_special_file(path):
1146
path = path.decode("utf-8")
1147
if specific_files is not None and path not in specific_files:
1149
(parent, name) = posixpath.split(path)
1151
file_ie = self._get_file_ie(name, path, value, None)
1152
except errors.NoSuchFile:
1154
if yield_parents or specific_files is None:
1155
for (dir_path, dir_ie) in self._add_missing_parent_ids(
1157
ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
1158
file_ie.parent_id = self.path2id(parent)
1159
ret[(posixpath.dirname(path), path)] = file_ie
1160
return ((path, ie) for ((_, path), ie) in sorted(viewitems(ret)))
1162
def iter_references(self):
1163
# TODO(jelmer): Implement a more efficient version of this
1164
for path, entry in self.iter_entries_by_dir():
1165
if entry.kind == 'tree-reference':
1168
def _get_dir_ie(self, path, parent_id):
1169
file_id = self.path2id(path)
1170
return GitTreeDirectory(file_id,
1171
posixpath.basename(path).strip("/"), parent_id)
1173
def _get_file_ie(self, name, path, value, parent_id):
1174
if not isinstance(name, text_type):
1175
raise TypeError(name)
1176
if not isinstance(path, text_type):
1177
raise TypeError(path)
1178
if not isinstance(value, tuple) or len(value) != 10:
1179
raise TypeError(value)
1180
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1181
file_id = self.path2id(path)
1182
if not isinstance(file_id, bytes):
1183
raise TypeError(file_id)
1184
kind = mode_kind(mode)
1185
ie = entry_factory[kind](file_id, name, parent_id)
1186
if kind == 'symlink':
1187
ie.symlink_target = self.get_symlink_target(path)
1188
elif kind == 'tree-reference':
1189
ie.reference_revision = self.get_reference_revision(path)
1192
data = self.get_file_text(path)
1193
except errors.NoSuchFile:
1195
except IOError as e:
1196
if e.errno != errno.ENOENT:
1200
data = self.branch.repository._git.object_store[sha].data
1201
ie.text_sha1 = osutils.sha_string(data)
1202
ie.text_size = len(data)
1203
ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1206
def _add_missing_parent_ids(self, path, dir_ids):
1209
parent = posixpath.dirname(path).strip("/")
1210
ret = self._add_missing_parent_ids(parent, dir_ids)
1211
parent_id = dir_ids[parent]
1212
ie = self._get_dir_ie(path, parent_id)
1213
dir_ids[path] = ie.file_id
1214
ret.append((path, ie))
1217
def _comparison_data(self, entry, path):
1219
return None, False, None
1220
return entry.kind, entry.executable, None
1222
def _unversion_path(self, path):
1223
if self._lock_mode is None:
1224
raise errors.ObjectNotLocked(self)
1225
encoded_path = path.encode("utf-8")
1227
(index, subpath) = self._lookup_index(encoded_path)
1229
self._index_del_entry(index, encoded_path)
1231
# A directory, perhaps?
1232
# TODO(jelmer): Deletes that involve submodules?
1233
for p in list(index):
1234
if p.startswith(subpath + b"/"):
1236
self._index_del_entry(index, p)
1239
self._versioned_dirs = None
1242
def unversion(self, paths):
1243
with self.lock_tree_write():
1245
if self._unversion_path(path) == 0:
1246
raise errors.NoSuchFile(path)
1247
self._versioned_dirs = None
1253
def update_basis_by_delta(self, revid, delta):
1254
# TODO(jelmer): This shouldn't be called, it's inventory specific.
1255
for (old_path, new_path, file_id, ie) in delta:
1256
if old_path is not None:
1257
(index, old_subpath) = self._lookup_index(
1258
old_path.encode('utf-8'))
1259
if old_subpath in index:
1260
self._index_del_entry(index, old_subpath)
1261
self._versioned_dirs = None
1262
if new_path is not None and ie.kind != 'directory':
1263
self._index_add_entry(new_path, ie.kind)
1265
self._set_merges_from_parent_ids([])
1267
def move(self, from_paths, to_dir=None, after=None):
1269
with self.lock_tree_write():
1270
to_abs = self.abspath(to_dir)
1271
if not os.path.isdir(to_abs):
1272
raise errors.BzrMoveFailedError('', to_dir,
1273
errors.NotADirectory(to_abs))
1275
for from_rel in from_paths:
1276
from_tail = os.path.split(from_rel)[-1]
1277
to_rel = os.path.join(to_dir, from_tail)
1278
self.rename_one(from_rel, to_rel, after=after)
1279
rename_tuples.append((from_rel, to_rel))
1281
return rename_tuples
1283
def rename_one(self, from_rel, to_rel, after=None):
1284
from_path = from_rel.encode("utf-8")
1285
to_rel, can_access = osutils.normalized_filename(to_rel)
1287
raise errors.InvalidNormalization(to_rel)
1288
to_path = to_rel.encode("utf-8")
1289
with self.lock_tree_write():
1291
# Perhaps it's already moved?
1293
not self.has_filename(from_rel) and
1294
self.has_filename(to_rel) and
1295
not self.is_versioned(to_rel))
1297
if not self.has_filename(to_rel):
1298
raise errors.BzrMoveFailedError(
1299
from_rel, to_rel, errors.NoSuchFile(to_rel))
1300
if self.basis_tree().is_versioned(to_rel):
1301
raise errors.BzrMoveFailedError(
1302
from_rel, to_rel, errors.AlreadyVersionedError(to_rel))
1304
kind = self.kind(to_rel)
1307
to_kind = self.kind(to_rel)
1308
except errors.NoSuchFile:
1309
exc_type = errors.BzrRenameFailedError
1312
exc_type = errors.BzrMoveFailedError
1313
if self.is_versioned(to_rel):
1314
raise exc_type(from_rel, to_rel,
1315
errors.AlreadyVersionedError(to_rel))
1316
if not self.has_filename(from_rel):
1317
raise errors.BzrMoveFailedError(
1318
from_rel, to_rel, errors.NoSuchFile(from_rel))
1319
kind = self.kind(from_rel)
1320
if not self.is_versioned(from_rel) and kind != 'directory':
1321
raise exc_type(from_rel, to_rel,
1322
errors.NotVersionedError(from_rel))
1323
if self.has_filename(to_rel):
1324
raise errors.RenameFailedFilesExist(
1325
from_rel, to_rel, errors.FileExists(to_rel))
1327
kind = self.kind(from_rel)
1329
if not after and kind != 'directory':
1330
(index, from_subpath) = self._lookup_index(from_path)
1331
if from_subpath not in index:
1333
raise errors.BzrMoveFailedError(
1335
errors.NotVersionedError(path=from_rel))
1339
self._rename_one(from_rel, to_rel)
1340
except OSError as e:
1341
if e.errno == errno.ENOENT:
1342
raise errors.BzrMoveFailedError(
1343
from_rel, to_rel, errors.NoSuchFile(to_rel))
1345
if kind != 'directory':
1346
(index, from_index_path) = self._lookup_index(from_path)
1348
self._index_del_entry(index, from_path)
1351
self._index_add_entry(to_rel, kind)
1353
todo = [(p, i) for (p, i) in self._recurse_index_entries()
1354
if p.startswith(from_path + b'/')]
1355
for child_path, child_value in todo:
1356
(child_to_index, child_to_index_path) = self._lookup_index(
1357
posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
1358
child_to_index[child_to_index_path] = child_value
1359
# TODO(jelmer): Mark individual index as dirty
1360
self._index_dirty = True
1361
(child_from_index, child_from_index_path) = self._lookup_index(
1363
self._index_del_entry(
1364
child_from_index, child_from_index_path)
1366
self._versioned_dirs = None
1369
def find_related_paths_across_trees(self, paths, trees=[],
1370
require_versioned=True):
1374
if require_versioned:
1375
trees = [self] + (trees if trees is not None else [])
1379
if t.is_versioned(p):
1384
raise errors.PathsNotVersionedError(unversioned)
1386
return filter(self.is_versioned, paths)
1388
def path_content_summary(self, path):
1389
"""See Tree.path_content_summary."""
1391
stat_result = self._lstat(path)
1392
except OSError as e:
1393
if getattr(e, 'errno', None) == errno.ENOENT:
1395
return ('missing', None, None, None)
1396
# propagate other errors
1398
kind = mode_kind(stat_result.st_mode)
1400
return self._file_content_summary(path, stat_result)
1401
elif kind == 'directory':
1402
# perhaps it looks like a plain directory, but it's really a
1404
if self._directory_is_tree_reference(path):
1405
kind = 'tree-reference'
1406
return kind, None, None, None
1407
elif kind == 'symlink':
1408
target = osutils.readlink(self.abspath(path))
1409
return ('symlink', None, None, target)
1411
return (kind, None, None, None)
1413
def kind(self, relpath):
1414
kind = osutils.file_kind(self.abspath(relpath))
1415
if kind == 'directory':
1416
(index, index_path) = self._lookup_index(relpath.encode('utf-8'))
1420
mode = index[index_path].mode
1424
if S_ISGITLINK(mode):
1425
return 'tree-reference'
1430
def _live_entry(self, relpath):
1431
raise NotImplementedError(self._live_entry)
1433
def get_transform(self, pb=None):
1434
from ..transform import TreeTransform
1435
return TreeTransform(self, pb=pb)
1439
class InterIndexGitTree(InterGitTrees):
1440
"""InterTree that works between a Git revision tree and an index."""
1442
def __init__(self, source, target):
1443
super(InterIndexGitTree, self).__init__(source, target)
1444
self._index = target.index
1447
def is_compatible(cls, source, target):
1448
return (isinstance(source, GitRevisionTree) and
1449
isinstance(target, MutableGitIndexTree))
1451
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1452
require_versioned=False, extra_trees=None,
1453
want_unversioned=False):
1454
trees = [self.source]
1455
if extra_trees is not None:
1456
trees.extend(extra_trees)
1457
if specific_files is not None:
1458
specific_files = self.target.find_related_paths_across_trees(
1459
specific_files, trees,
1460
require_versioned=require_versioned)
1461
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1462
with self.lock_read():
1463
return changes_between_git_tree_and_working_copy(
1464
self.source.store, self.source.tree,
1465
self.target, want_unchanged=want_unchanged,
1466
want_unversioned=want_unversioned)
1469
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
1472
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1473
want_unchanged=False,
1474
want_unversioned=False):
1475
"""Determine the changes between a git tree and a working tree with index.
1480
# Report dirified directories to commit_tree first, so that they can be
1481
# replaced with non-empty directories if they have contents.
1483
trust_executable = target._supports_executable()
1484
for path, index_entry in target._recurse_index_entries():
1486
live_entry = target._live_entry(path)
1487
except EnvironmentError as e:
1488
if e.errno == errno.ENOENT:
1489
# Entry was removed; keep it listed, but mark it as gone.
1490
blobs[path] = (ZERO_SHA, 0)
1491
elif e.errno == errno.EISDIR:
1492
# Backwards compatibility with Dulwich < 0.19.12;
1493
# newer versions of Dulwich return either an entry for the
1494
# submodule or None for directories.
1495
if S_ISGITLINK(index_entry.mode):
1496
blobs[path] = (index_entry.sha, index_entry.mode)
1498
# Entry was turned into a directory
1499
dirified.append((path, Tree().id, stat.S_IFDIR))
1500
store.add_object(Tree())
1504
if live_entry is None:
1505
# Entry was turned into a directory
1506
dirified.append((path, Tree().id, stat.S_IFDIR))
1507
store.add_object(Tree())
1509
mode = live_entry.mode
1510
if not trust_executable:
1511
if mode_is_executable(index_entry.mode):
1515
blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1516
if want_unversioned:
1517
for e in target.extras():
1518
st = target._lstat(e)
1520
np, accessible = osutils.normalized_filename(e)
1521
except UnicodeDecodeError:
1522
raise errors.BadFilenameEncoding(
1524
if stat.S_ISDIR(st.st_mode):
1527
blob = blob_from_path_and_stat(
1528
target.abspath(e).encode(osutils._fs_enc), st)
1529
store.add_object(blob)
1530
np = np.encode('utf-8')
1531
blobs[np] = (blob.id, cleanup_mode(st.st_mode))
1533
to_tree_sha = commit_tree(
1534
store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
1535
return store.tree_changes(
1536
from_tree_sha, to_tree_sha, include_trees=True,
1537
want_unchanged=want_unchanged, change_type_same=True), extras