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.store = repository._git.object_store
256
if not isinstance(revision_id, bytes):
257
raise TypeError(revision_id)
258
self.commit_id, self.mapping = repository.lookup_bzr_revision_id(
260
if revision_id == NULL_REVISION:
262
self.mapping = default_mapping
265
commit = self.store[self.commit_id]
267
raise errors.NoSuchRevision(repository, revision_id)
268
self.tree = commit.tree
270
def _get_nested_repository(self, path):
271
nested_repo_transport = self._repository.user_transport.clone(path)
272
nested_controldir = _mod_controldir.ControlDir.open_from_transport(
273
nested_repo_transport)
274
return nested_controldir.find_repository()
276
def supports_rename_tracking(self):
279
def get_file_revision(self, path):
280
change_scanner = self._repository._file_change_scanner
281
if self.commit_id == ZERO_SHA:
283
(unused_path, commit_id) = change_scanner.find_last_change_revision(
284
path.encode('utf-8'), self.commit_id)
285
return self._repository.lookup_foreign_revision_id(
286
commit_id, self.mapping)
288
def get_file_mtime(self, path):
290
revid = self.get_file_revision(path)
292
raise errors.NoSuchFile(path)
294
rev = self._repository.get_revision(revid)
295
except errors.NoSuchRevision:
296
raise _mod_tree.FileTimestampUnavailable(path)
299
def id2path(self, file_id):
301
path = self.mapping.parse_file_id(file_id)
303
raise errors.NoSuchId(self, file_id)
304
if self.is_versioned(path):
306
raise errors.NoSuchId(self, file_id)
308
def is_versioned(self, path):
309
return self.has_filename(path)
311
def path2id(self, path):
312
if self.mapping.is_special_file(path):
314
if not self.is_versioned(path):
316
return self.mapping.generate_file_id(osutils.safe_unicode(path))
318
def all_file_ids(self):
319
raise errors.UnsupportedOperation(self.all_file_ids, self)
321
def all_versioned_paths(self):
323
todo = [(self.store, b'', self.tree)]
325
(store, path, tree_id) = todo.pop()
328
tree = store[tree_id]
329
for name, mode, hexsha in tree.items():
330
subpath = posixpath.join(path, name)
331
ret.add(subpath.decode('utf-8'))
332
if stat.S_ISDIR(mode):
333
todo.append((store, subpath, hexsha))
336
def get_root_id(self):
337
if self.tree is None:
339
return self.path2id("")
341
def has_or_had_id(self, file_id):
343
self.id2path(file_id)
344
except errors.NoSuchId:
348
def has_id(self, file_id):
350
path = self.id2path(file_id)
351
except errors.NoSuchId:
353
return self.has_filename(path)
355
def _lookup_path(self, path):
356
if self.tree is None:
357
raise errors.NoSuchFile(path)
359
(mode, hexsha) = tree_lookup_path(
360
self.store.__getitem__, self.tree, path.encode('utf-8'))
362
raise errors.NoSuchFile(self, path)
364
return (self.store, mode, hexsha)
366
def is_executable(self, path):
367
(store, mode, hexsha) = self._lookup_path(path)
369
# the tree root is a directory
371
return mode_is_executable(mode)
373
def kind(self, path):
374
(store, mode, hexsha) = self._lookup_path(path)
376
# the tree root is a directory
378
return mode_kind(mode)
380
def has_filename(self, path):
382
self._lookup_path(path)
383
except errors.NoSuchFile:
388
def list_files(self, include_root=False, from_dir=None, recursive=True):
389
if self.tree is None:
391
if from_dir is None or from_dir == '.':
393
(store, mode, hexsha) = self._lookup_path(from_dir)
394
if mode is None: # Root
395
root_ie = self._get_dir_ie(b"", None)
397
parent_path = posixpath.dirname(from_dir)
398
parent_id = self.mapping.generate_file_id(parent_path)
399
if mode_kind(mode) == 'directory':
400
root_ie = self._get_dir_ie(from_dir.encode("utf-8"), parent_id)
402
root_ie = self._get_file_ie(
403
store, from_dir.encode("utf-8"),
404
posixpath.basename(from_dir), mode, hexsha)
406
yield (from_dir, "V", root_ie.kind, root_ie)
408
if root_ie.kind == 'directory':
409
todo.append((store, from_dir.encode("utf-8"),
410
b"", hexsha, root_ie.file_id))
412
(store, path, relpath, hexsha, parent_id) = todo.pop()
414
for name, mode, hexsha in tree.iteritems():
415
if self.mapping.is_special_file(name):
417
child_path = posixpath.join(path, name)
418
child_relpath = posixpath.join(relpath, name)
419
if stat.S_ISDIR(mode):
420
ie = self._get_dir_ie(child_path, parent_id)
423
(store, child_path, child_relpath, hexsha,
426
ie = self._get_file_ie(
427
store, child_path, name, mode, hexsha, parent_id)
428
yield (child_relpath.decode('utf-8'), "V", ie.kind, ie)
430
def _get_file_ie(self, store, path, name, mode, hexsha, parent_id):
431
if not isinstance(path, bytes):
432
raise TypeError(path)
433
if not isinstance(name, bytes):
434
raise TypeError(name)
435
kind = mode_kind(mode)
436
path = path.decode('utf-8')
437
name = name.decode("utf-8")
438
file_id = self.mapping.generate_file_id(path)
439
ie = entry_factory[kind](file_id, name, parent_id)
440
if kind == 'symlink':
441
ie.symlink_target = store[hexsha].data.decode('utf-8')
442
elif kind == 'tree-reference':
443
ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(
446
data = store[hexsha].data
447
ie.text_sha1 = osutils.sha_string(data)
448
ie.text_size = len(data)
449
ie.executable = mode_is_executable(mode)
452
def _get_dir_ie(self, path, parent_id):
453
path = path.decode('utf-8')
454
file_id = self.mapping.generate_file_id(path)
455
return GitTreeDirectory(file_id, posixpath.basename(path), parent_id)
457
def iter_child_entries(self, path):
458
(store, mode, tree_sha) = self._lookup_path(path)
460
if mode is not None and not stat.S_ISDIR(mode):
463
encoded_path = path.encode('utf-8')
464
file_id = self.path2id(path)
465
tree = store[tree_sha]
466
for name, mode, hexsha in tree.iteritems():
467
if self.mapping.is_special_file(name):
469
child_path = posixpath.join(encoded_path, name)
470
if stat.S_ISDIR(mode):
471
yield self._get_dir_ie(child_path, file_id)
473
yield self._get_file_ie(store, child_path, name, mode, hexsha,
476
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
477
if self.tree is None:
480
# TODO(jelmer): Support yield parents
481
raise NotImplementedError
482
if specific_files is not None:
483
if specific_files in ([""], []):
484
specific_files = None
486
specific_files = set([p.encode('utf-8')
487
for p in specific_files])
488
todo = deque([(self.store, b"", self.tree, self.get_root_id())])
489
if specific_files is None or u"" in specific_files:
490
yield u"", self._get_dir_ie(b"", None)
492
store, path, tree_sha, parent_id = todo.popleft()
493
tree = store[tree_sha]
495
for name, mode, hexsha in tree.iteritems():
496
if self.mapping.is_special_file(name):
498
child_path = posixpath.join(path, name)
499
child_path_decoded = child_path.decode('utf-8')
500
if stat.S_ISDIR(mode):
501
if (specific_files is None or
502
any([p for p in specific_files if p.startswith(
505
(store, child_path, hexsha,
506
self.path2id(child_path_decoded)))
507
if specific_files is None or child_path in specific_files:
508
if stat.S_ISDIR(mode):
509
yield (child_path_decoded,
510
self._get_dir_ie(child_path, parent_id))
512
yield (child_path_decoded,
513
self._get_file_ie(store, child_path, name, mode,
515
todo.extendleft(reversed(extradirs))
517
def iter_references(self):
518
if self.supports_tree_reference():
519
for path, entry in self.iter_entries_by_dir():
520
if entry.kind == 'tree-reference':
523
def get_revision_id(self):
524
"""See RevisionTree.get_revision_id."""
525
return self._revision_id
527
def get_file_sha1(self, path, stat_value=None):
528
if self.tree is None:
529
raise errors.NoSuchFile(path)
530
return osutils.sha_string(self.get_file_text(path))
532
def get_file_verifier(self, path, stat_value=None):
533
(store, mode, hexsha) = self._lookup_path(path)
534
return ("GIT", hexsha)
536
def get_file_size(self, path):
537
(store, mode, hexsha) = self._lookup_path(path)
538
if stat.S_ISREG(mode):
539
return len(store[hexsha].data)
542
def get_file_text(self, path):
543
"""See RevisionTree.get_file_text."""
544
(store, mode, hexsha) = self._lookup_path(path)
545
if stat.S_ISREG(mode):
546
return store[hexsha].data
550
def get_symlink_target(self, path):
551
"""See RevisionTree.get_symlink_target."""
552
(store, mode, hexsha) = self._lookup_path(path)
553
if stat.S_ISLNK(mode):
554
return store[hexsha].data.decode('utf-8')
558
def get_reference_revision(self, path):
559
"""See RevisionTree.get_symlink_target."""
560
(store, mode, hexsha) = self._lookup_path(path)
561
if S_ISGITLINK(mode):
562
nested_repo = self._get_nested_repository(path)
563
return nested_repo.lookup_foreign_revision_id(hexsha)
567
def _comparison_data(self, entry, path):
569
return None, False, None
570
return entry.kind, entry.executable, None
572
def path_content_summary(self, path):
573
"""See Tree.path_content_summary."""
575
(store, mode, hexsha) = self._lookup_path(path)
576
except errors.NoSuchFile:
577
return ('missing', None, None, None)
578
kind = mode_kind(mode)
580
executable = mode_is_executable(mode)
581
contents = store[hexsha].data
582
return (kind, len(contents), executable,
583
osutils.sha_string(contents))
584
elif kind == 'symlink':
585
return (kind, None, None, store[hexsha].data.decode('utf-8'))
586
elif kind == 'tree-reference':
587
nested_repo = self._get_nested_repository(path)
588
return (kind, None, None,
589
nested_repo.lookup_foreign_revision_id(hexsha))
591
return (kind, None, None, None)
593
def find_related_paths_across_trees(self, paths, trees=[],
594
require_versioned=True):
597
if require_versioned:
598
trees = [self] + (trees if trees is not None else [])
602
if t.is_versioned(p):
607
raise errors.PathsNotVersionedError(unversioned)
608
return filter(self.is_versioned, paths)
610
def _iter_tree_contents(self, include_trees=False):
611
if self.tree is None:
613
return self.store.iter_tree_contents(
614
self.tree, include_trees=include_trees)
616
def annotate_iter(self, path, default_revision=CURRENT_REVISION):
617
"""Return an iterator of revision_id, line tuples.
619
For working trees (and mutable trees in general), the special
620
revision_id 'current:' will be used for lines that are new in this
621
tree, e.g. uncommitted changes.
622
:param default_revision: For lines that don't match a basis, mark them
623
with this revision id. Not all implementations will make use of
626
with self.lock_read():
627
# Now we have the parents of this content
628
from breezy.annotate import Annotator
629
from .annotate import AnnotateProvider
630
annotator = Annotator(AnnotateProvider(
631
self._repository._file_change_scanner))
632
this_key = (path, self.get_file_revision(path))
633
annotations = [(key[-1], line)
634
for key, line in annotator.annotate_flat(this_key)]
637
def _get_rules_searcher(self, default_searcher):
638
return default_searcher
640
def walkdirs(self, prefix=u""):
641
(store, mode, hexsha) = self._lookup_path(prefix)
643
[(store, prefix.encode('utf-8'), hexsha, self.path2id(prefix))])
645
store, path, tree_sha, parent_id = todo.popleft()
646
path_decoded = path.decode('utf-8')
647
tree = store[tree_sha]
649
for name, mode, hexsha in tree.iteritems():
650
if self.mapping.is_special_file(name):
652
child_path = posixpath.join(path, name)
653
file_id = self.path2id(child_path.decode('utf-8'))
654
if stat.S_ISDIR(mode):
655
todo.append((store, child_path, hexsha, file_id))
657
(child_path.decode('utf-8'), name.decode('utf-8'),
658
mode_kind(mode), None,
659
file_id, mode_kind(mode)))
660
yield (path_decoded, parent_id), children
663
def tree_delta_from_git_changes(changes, mappings,
665
require_versioned=False, include_root=False,
667
"""Create a TreeDelta from two git trees.
669
source and target are iterators over tuples with:
670
(filename, sha, mode)
672
(old_mapping, new_mapping) = mappings
673
if target_extras is None:
674
target_extras = set()
675
ret = delta.TreeDelta()
677
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
678
if newpath == b'' and not include_root:
681
oldpath_decoded = None
683
oldpath_decoded = oldpath.decode('utf-8')
685
newpath_decoded = None
687
newpath_decoded = newpath.decode('utf-8')
688
if not (specific_files is None or
689
(oldpath is not None and
690
osutils.is_inside_or_parent_of_any(
691
specific_files, oldpath_decoded)) or
692
(newpath is not None and
693
osutils.is_inside_or_parent_of_any(
694
specific_files, newpath_decoded))):
696
if old_mapping.is_special_file(oldpath):
698
if new_mapping.is_special_file(newpath):
700
if oldpath is None and newpath is None:
703
added.append((newpath, mode_kind(newmode)))
704
elif newpath is None or newmode == 0:
705
file_id = old_mapping.generate_file_id(oldpath_decoded)
706
ret.removed.append((oldpath_decoded, file_id, mode_kind(oldmode)))
707
elif oldpath != newpath:
708
file_id = old_mapping.generate_file_id(oldpath_decoded)
710
(oldpath_decoded, newpath.decode('utf-8'), file_id,
711
mode_kind(newmode), (oldsha != newsha),
712
(oldmode != newmode)))
713
elif mode_kind(oldmode) != mode_kind(newmode):
714
file_id = new_mapping.generate_file_id(newpath_decoded)
715
ret.kind_changed.append(
716
(newpath_decoded, file_id, mode_kind(oldmode),
718
elif oldsha != newsha or oldmode != newmode:
719
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
721
file_id = new_mapping.generate_file_id(newpath_decoded)
723
(newpath_decoded, file_id, mode_kind(newmode),
724
(oldsha != newsha), (oldmode != newmode)))
726
file_id = new_mapping.generate_file_id(newpath_decoded)
727
ret.unchanged.append(
728
(newpath_decoded, file_id, mode_kind(newmode)))
730
implicit_dirs = {b''}
731
for path, kind in added:
732
if kind == 'directory' or path in target_extras:
734
implicit_dirs.update(osutils.parent_directories(path))
736
for path, kind in added:
737
if kind == 'directory' and path not in implicit_dirs:
739
path_decoded = osutils.normalized_filename(path)[0]
740
if path in target_extras:
741
ret.unversioned.append((path_decoded, None, kind))
743
file_id = new_mapping.generate_file_id(path_decoded)
744
ret.added.append((path_decoded, file_id, kind))
749
def changes_from_git_changes(changes, mapping, specific_files=None,
750
include_unchanged=False, target_extras=None):
751
"""Create a iter_changes-like generator from a git stream.
753
source and target are iterators over tuples with:
754
(filename, sha, mode)
756
if target_extras is None:
757
target_extras = set()
758
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
759
if oldpath is not None:
760
oldpath_decoded = oldpath.decode('utf-8')
762
oldpath_decoded = None
763
if newpath is not None:
764
newpath_decoded = newpath.decode('utf-8')
766
newpath_decoded = None
767
if not (specific_files is None or
768
(oldpath_decoded is not None and
769
osutils.is_inside_or_parent_of_any(
770
specific_files, oldpath_decoded)) or
771
(newpath_decoded is not None and
772
osutils.is_inside_or_parent_of_any(
773
specific_files, newpath_decoded))):
775
if oldpath is not None and mapping.is_special_file(oldpath):
777
if newpath is not None and mapping.is_special_file(newpath):
779
if oldpath_decoded is None:
780
fileid = mapping.generate_file_id(newpath_decoded)
789
oldexe = mode_is_executable(oldmode)
790
oldkind = mode_kind(oldmode)
794
if oldpath_decoded == u'':
798
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
799
oldparent = mapping.generate_file_id(oldparentpath)
800
fileid = mapping.generate_file_id(oldpath_decoded)
801
if newpath_decoded is None:
808
newversioned = (newpath_decoded not in target_extras)
810
newexe = mode_is_executable(newmode)
811
newkind = mode_kind(newmode)
815
if newpath_decoded == u'':
819
newparentpath, newname = osutils.split(newpath_decoded)
820
newparent = mapping.generate_file_id(newparentpath)
821
if (not include_unchanged and
822
oldkind == 'directory' and newkind == 'directory' and
823
oldpath_decoded == newpath_decoded):
825
yield _mod_tree.TreeChange(
826
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
827
(oldversioned, newversioned),
828
(oldparent, newparent), (oldname, newname),
829
(oldkind, newkind), (oldexe, newexe))
832
class InterGitTrees(_mod_tree.InterTree):
833
"""InterTree that works between two git trees."""
835
_matching_from_tree_format = None
836
_matching_to_tree_format = None
837
_test_mutable_trees_to_test_trees = None
840
def is_compatible(cls, source, target):
841
return (isinstance(source, GitRevisionTree) and
842
isinstance(target, GitRevisionTree))
844
def compare(self, want_unchanged=False, specific_files=None,
845
extra_trees=None, require_versioned=False, include_root=False,
846
want_unversioned=False):
847
with self.lock_read():
848
changes, target_extras = self._iter_git_changes(
849
want_unchanged=want_unchanged,
850
require_versioned=require_versioned,
851
specific_files=specific_files,
852
extra_trees=extra_trees,
853
want_unversioned=want_unversioned)
854
return tree_delta_from_git_changes(
855
changes, (self.source.mapping, self.target.mapping),
856
specific_files=specific_files,
857
include_root=include_root, target_extras=target_extras)
859
def iter_changes(self, include_unchanged=False, specific_files=None,
860
pb=None, extra_trees=[], require_versioned=True,
861
want_unversioned=False):
862
with self.lock_read():
863
changes, target_extras = self._iter_git_changes(
864
want_unchanged=include_unchanged,
865
require_versioned=require_versioned,
866
specific_files=specific_files,
867
extra_trees=extra_trees,
868
want_unversioned=want_unversioned)
869
return changes_from_git_changes(
870
changes, self.target.mapping,
871
specific_files=specific_files,
872
include_unchanged=include_unchanged,
873
target_extras=target_extras)
875
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
876
require_versioned=False, extra_trees=None,
877
want_unversioned=False):
878
raise NotImplementedError(self._iter_git_changes)
881
class InterGitRevisionTrees(InterGitTrees):
882
"""InterTree that works between two git revision trees."""
884
_matching_from_tree_format = None
885
_matching_to_tree_format = None
886
_test_mutable_trees_to_test_trees = None
889
def is_compatible(cls, source, target):
890
return (isinstance(source, GitRevisionTree) and
891
isinstance(target, GitRevisionTree))
893
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
894
require_versioned=True, extra_trees=None,
895
want_unversioned=False):
896
trees = [self.source]
897
if extra_trees is not None:
898
trees.extend(extra_trees)
899
if specific_files is not None:
900
specific_files = self.target.find_related_paths_across_trees(
901
specific_files, trees,
902
require_versioned=require_versioned)
904
if (self.source._repository._git.object_store !=
905
self.target._repository._git.object_store):
906
store = OverlayObjectStore(
907
[self.source._repository._git.object_store,
908
self.target._repository._git.object_store])
910
store = self.source._repository._git.object_store
911
return store.tree_changes(
912
self.source.tree, self.target.tree, want_unchanged=want_unchanged,
913
include_trees=True, change_type_same=True), set()
916
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
919
class MutableGitIndexTree(mutabletree.MutableTree):
922
self._lock_mode = None
924
self._versioned_dirs = None
925
self._index_dirty = False
927
def is_versioned(self, path):
928
with self.lock_read():
929
path = path.rstrip('/').encode('utf-8')
930
(index, subpath) = self._lookup_index(path)
931
return (subpath in index or self._has_dir(path))
933
def _has_dir(self, path):
934
if not isinstance(path, bytes):
935
raise TypeError(path)
938
if self._versioned_dirs is None:
940
return path in self._versioned_dirs
942
def _load_dirs(self):
943
if self._lock_mode is None:
944
raise errors.ObjectNotLocked(self)
945
self._versioned_dirs = set()
946
# TODO(jelmer): Browse over all indexes
947
for p, i in self._recurse_index_entries():
948
self._ensure_versioned_dir(posixpath.dirname(p))
950
def _ensure_versioned_dir(self, dirname):
951
if not isinstance(dirname, bytes):
952
raise TypeError(dirname)
953
if dirname in self._versioned_dirs:
956
self._ensure_versioned_dir(posixpath.dirname(dirname))
957
self._versioned_dirs.add(dirname)
959
def path2id(self, path):
960
with self.lock_read():
961
path = path.rstrip('/')
962
if self.is_versioned(path.rstrip('/')):
963
return self.mapping.generate_file_id(
964
osutils.safe_unicode(path))
967
def has_id(self, file_id):
969
self.id2path(file_id)
970
except errors.NoSuchId:
975
def id2path(self, file_id):
978
if type(file_id) is not bytes:
979
raise TypeError(file_id)
980
with self.lock_read():
982
path = self.mapping.parse_file_id(file_id)
984
raise errors.NoSuchId(self, file_id)
985
if self.is_versioned(path):
987
raise errors.NoSuchId(self, file_id)
989
def _set_root_id(self, file_id):
990
raise errors.UnsupportedOperation(self._set_root_id, self)
992
def get_root_id(self):
993
return self.path2id(u"")
995
def _add(self, files, ids, kinds):
996
for (path, file_id, kind) in zip(files, ids, kinds):
997
if file_id is not None:
998
raise workingtree.SettingFileIdUnsupported()
999
path, can_access = osutils.normalized_filename(path)
1001
raise errors.InvalidNormalization(path)
1002
self._index_add_entry(path, kind)
1004
def _read_submodule_head(self, path):
1005
raise NotImplementedError(self._read_submodule_head)
1007
def _lookup_index(self, encoded_path):
1008
if not isinstance(encoded_path, bytes):
1009
raise TypeError(encoded_path)
1010
# TODO(jelmer): Look in other indexes
1011
return self.index, encoded_path
1013
def _index_del_entry(self, index, path):
1015
# TODO(jelmer): Keep track of dirty per index
1016
self._index_dirty = True
1018
def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
1019
if kind == "directory":
1020
# Git indexes don't contain directories
1025
file, stat_val = self.get_file_with_stat(path)
1026
except (errors.NoSuchFile, IOError):
1027
# TODO: Rather than come up with something here, use the old
1030
stat_val = os.stat_result(
1031
(stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1033
blob.set_raw_string(file.read())
1034
# Add object to the repository if it didn't exist yet
1035
if blob.id not in self.store:
1036
self.store.add_object(blob)
1038
elif kind == "symlink":
1041
stat_val = self._lstat(path)
1042
except EnvironmentError:
1043
# TODO: Rather than come up with something here, use the
1045
stat_val = os.stat_result(
1046
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1047
blob.set_raw_string(
1048
self.get_symlink_target(path).encode("utf-8"))
1049
# Add object to the repository if it didn't exist yet
1050
if blob.id not in self.store:
1051
self.store.add_object(blob)
1053
elif kind == "tree-reference":
1054
if reference_revision is not None:
1055
hexsha = self.branch.lookup_bzr_revision_id(
1056
reference_revision)[0]
1058
hexsha = self._read_submodule_head(path)
1060
raise errors.NoCommits(path)
1062
stat_val = self._lstat(path)
1063
except EnvironmentError:
1064
stat_val = os.stat_result(
1065
(S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1066
stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
1068
raise AssertionError("unknown kind '%s'" % kind)
1069
# Add an entry to the index or update the existing entry
1070
ensure_normalized_path(path)
1071
encoded_path = path.encode("utf-8")
1072
if b'\r' in encoded_path or b'\n' in encoded_path:
1073
# TODO(jelmer): Why do we need to do this?
1074
trace.mutter('ignoring path with invalid newline in it: %r', path)
1076
(index, index_path) = self._lookup_index(encoded_path)
1077
index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
1078
self._index_dirty = True
1079
if self._versioned_dirs is not None:
1080
self._ensure_versioned_dir(index_path)
1082
def _recurse_index_entries(self, index=None, basepath=b""):
1083
# Iterate over all index entries
1084
with self.lock_read():
1087
for path, value in index.items():
1088
yield (posixpath.join(basepath, path), value)
1089
(ctime, mtime, dev, ino, mode, uid, gid, size, sha,
1091
if S_ISGITLINK(mode):
1092
pass # TODO(jelmer): dive into submodule
1094
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
1096
raise NotImplementedError(self.iter_entries_by_dir)
1097
with self.lock_read():
1098
if specific_files is not None:
1099
specific_files = set(specific_files)
1101
specific_files = None
1102
root_ie = self._get_dir_ie(u"", None)
1104
if specific_files is None or u"" in specific_files:
1105
ret[(u"", u"")] = root_ie
1106
dir_ids = {u"": root_ie.file_id}
1107
for path, value in self._recurse_index_entries():
1108
if self.mapping.is_special_file(path):
1110
path = path.decode("utf-8")
1111
if specific_files is not None and path not in specific_files:
1113
(parent, name) = posixpath.split(path)
1115
file_ie = self._get_file_ie(name, path, value, None)
1116
except errors.NoSuchFile:
1118
if yield_parents or specific_files is None:
1119
for (dir_path, dir_ie) in self._add_missing_parent_ids(
1121
ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
1122
file_ie.parent_id = self.path2id(parent)
1123
ret[(posixpath.dirname(path), path)] = file_ie
1124
return ((path, ie) for ((_, path), ie) in sorted(viewitems(ret)))
1126
def iter_references(self):
1127
# TODO(jelmer): Implement a more efficient version of this
1128
for path, entry in self.iter_entries_by_dir():
1129
if entry.kind == 'tree-reference':
1132
def _get_dir_ie(self, path, parent_id):
1133
file_id = self.path2id(path)
1134
return GitTreeDirectory(file_id,
1135
posixpath.basename(path).strip("/"), parent_id)
1137
def _get_file_ie(self, name, path, value, parent_id):
1138
if not isinstance(name, text_type):
1139
raise TypeError(name)
1140
if not isinstance(path, text_type):
1141
raise TypeError(path)
1142
if not isinstance(value, tuple) or len(value) != 10:
1143
raise TypeError(value)
1144
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1145
file_id = self.path2id(path)
1146
if not isinstance(file_id, bytes):
1147
raise TypeError(file_id)
1148
kind = mode_kind(mode)
1149
ie = entry_factory[kind](file_id, name, parent_id)
1150
if kind == 'symlink':
1151
ie.symlink_target = self.get_symlink_target(path)
1152
elif kind == 'tree-reference':
1153
ie.reference_revision = self.get_reference_revision(path)
1156
data = self.get_file_text(path)
1157
except errors.NoSuchFile:
1159
except IOError as e:
1160
if e.errno != errno.ENOENT:
1164
data = self.branch.repository._git.object_store[sha].data
1165
ie.text_sha1 = osutils.sha_string(data)
1166
ie.text_size = len(data)
1167
ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1170
def _add_missing_parent_ids(self, path, dir_ids):
1173
parent = posixpath.dirname(path).strip("/")
1174
ret = self._add_missing_parent_ids(parent, dir_ids)
1175
parent_id = dir_ids[parent]
1176
ie = self._get_dir_ie(path, parent_id)
1177
dir_ids[path] = ie.file_id
1178
ret.append((path, ie))
1181
def _comparison_data(self, entry, path):
1183
return None, False, None
1184
return entry.kind, entry.executable, None
1186
def _unversion_path(self, path):
1187
if self._lock_mode is None:
1188
raise errors.ObjectNotLocked(self)
1189
encoded_path = path.encode("utf-8")
1191
(index, subpath) = self._lookup_index(encoded_path)
1193
self._index_del_entry(index, encoded_path)
1195
# A directory, perhaps?
1196
# TODO(jelmer): Deletes that involve submodules?
1197
for p in list(index):
1198
if p.startswith(subpath + b"/"):
1200
self._index_del_entry(index, p)
1203
self._versioned_dirs = None
1206
def unversion(self, paths):
1207
with self.lock_tree_write():
1209
if self._unversion_path(path) == 0:
1210
raise errors.NoSuchFile(path)
1211
self._versioned_dirs = None
1217
def update_basis_by_delta(self, revid, delta):
1218
# TODO(jelmer): This shouldn't be called, it's inventory specific.
1219
for (old_path, new_path, file_id, ie) in delta:
1220
if old_path is not None:
1221
(index, old_subpath) = self._lookup_index(
1222
old_path.encode('utf-8'))
1223
if old_subpath in index:
1224
self._index_del_entry(index, old_subpath)
1225
self._versioned_dirs = None
1226
if new_path is not None and ie.kind != 'directory':
1227
self._index_add_entry(new_path, ie.kind)
1229
self._set_merges_from_parent_ids([])
1231
def move(self, from_paths, to_dir=None, after=None):
1233
with self.lock_tree_write():
1234
to_abs = self.abspath(to_dir)
1235
if not os.path.isdir(to_abs):
1236
raise errors.BzrMoveFailedError('', to_dir,
1237
errors.NotADirectory(to_abs))
1239
for from_rel in from_paths:
1240
from_tail = os.path.split(from_rel)[-1]
1241
to_rel = os.path.join(to_dir, from_tail)
1242
self.rename_one(from_rel, to_rel, after=after)
1243
rename_tuples.append((from_rel, to_rel))
1245
return rename_tuples
1247
def rename_one(self, from_rel, to_rel, after=None):
1248
from_path = from_rel.encode("utf-8")
1249
to_rel, can_access = osutils.normalized_filename(to_rel)
1251
raise errors.InvalidNormalization(to_rel)
1252
to_path = to_rel.encode("utf-8")
1253
with self.lock_tree_write():
1255
# Perhaps it's already moved?
1257
not self.has_filename(from_rel) and
1258
self.has_filename(to_rel) and
1259
not self.is_versioned(to_rel))
1261
if not self.has_filename(to_rel):
1262
raise errors.BzrMoveFailedError(
1263
from_rel, to_rel, errors.NoSuchFile(to_rel))
1264
if self.basis_tree().is_versioned(to_rel):
1265
raise errors.BzrMoveFailedError(
1266
from_rel, to_rel, errors.AlreadyVersionedError(to_rel))
1268
kind = self.kind(to_rel)
1271
to_kind = self.kind(to_rel)
1272
except errors.NoSuchFile:
1273
exc_type = errors.BzrRenameFailedError
1276
exc_type = errors.BzrMoveFailedError
1277
if self.is_versioned(to_rel):
1278
raise exc_type(from_rel, to_rel,
1279
errors.AlreadyVersionedError(to_rel))
1280
if not self.has_filename(from_rel):
1281
raise errors.BzrMoveFailedError(
1282
from_rel, to_rel, errors.NoSuchFile(from_rel))
1283
kind = self.kind(from_rel)
1284
if not self.is_versioned(from_rel) and kind != 'directory':
1285
raise exc_type(from_rel, to_rel,
1286
errors.NotVersionedError(from_rel))
1287
if self.has_filename(to_rel):
1288
raise errors.RenameFailedFilesExist(
1289
from_rel, to_rel, errors.FileExists(to_rel))
1291
kind = self.kind(from_rel)
1293
if not after and kind != 'directory':
1294
(index, from_subpath) = self._lookup_index(from_path)
1295
if from_subpath not in index:
1297
raise errors.BzrMoveFailedError(
1299
errors.NotVersionedError(path=from_rel))
1303
self._rename_one(from_rel, to_rel)
1304
except OSError as e:
1305
if e.errno == errno.ENOENT:
1306
raise errors.BzrMoveFailedError(
1307
from_rel, to_rel, errors.NoSuchFile(to_rel))
1309
if kind != 'directory':
1310
(index, from_index_path) = self._lookup_index(from_path)
1312
self._index_del_entry(index, from_path)
1315
self._index_add_entry(to_rel, kind)
1317
todo = [(p, i) for (p, i) in self._recurse_index_entries()
1318
if p.startswith(from_path + b'/')]
1319
for child_path, child_value in todo:
1320
(child_to_index, child_to_index_path) = self._lookup_index(
1321
posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
1322
child_to_index[child_to_index_path] = child_value
1323
# TODO(jelmer): Mark individual index as dirty
1324
self._index_dirty = True
1325
(child_from_index, child_from_index_path) = self._lookup_index(
1327
self._index_del_entry(
1328
child_from_index, child_from_index_path)
1330
self._versioned_dirs = None
1333
def find_related_paths_across_trees(self, paths, trees=[],
1334
require_versioned=True):
1338
if require_versioned:
1339
trees = [self] + (trees if trees is not None else [])
1343
if t.is_versioned(p):
1348
raise errors.PathsNotVersionedError(unversioned)
1350
return filter(self.is_versioned, paths)
1352
def path_content_summary(self, path):
1353
"""See Tree.path_content_summary."""
1355
stat_result = self._lstat(path)
1356
except OSError as e:
1357
if getattr(e, 'errno', None) == errno.ENOENT:
1359
return ('missing', None, None, None)
1360
# propagate other errors
1362
kind = mode_kind(stat_result.st_mode)
1364
return self._file_content_summary(path, stat_result)
1365
elif kind == 'directory':
1366
# perhaps it looks like a plain directory, but it's really a
1368
if self._directory_is_tree_reference(path):
1369
kind = 'tree-reference'
1370
return kind, None, None, None
1371
elif kind == 'symlink':
1372
target = osutils.readlink(self.abspath(path))
1373
return ('symlink', None, None, target)
1375
return (kind, None, None, None)
1377
def kind(self, relpath):
1378
kind = osutils.file_kind(self.abspath(relpath))
1379
if kind == 'directory':
1380
(index, index_path) = self._lookup_index(relpath.encode('utf-8'))
1384
mode = index[index_path].mode
1388
if S_ISGITLINK(mode):
1389
return 'tree-reference'
1394
def _live_entry(self, relpath):
1395
raise NotImplementedError(self._live_entry)
1397
def get_transform(self, pb=None):
1398
from ..transform import TreeTransform
1399
return TreeTransform(self, pb=pb)
1403
class InterIndexGitTree(InterGitTrees):
1404
"""InterTree that works between a Git revision tree and an index."""
1406
def __init__(self, source, target):
1407
super(InterIndexGitTree, self).__init__(source, target)
1408
self._index = target.index
1411
def is_compatible(cls, source, target):
1412
return (isinstance(source, GitRevisionTree) and
1413
isinstance(target, MutableGitIndexTree))
1415
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1416
require_versioned=False, extra_trees=None,
1417
want_unversioned=False):
1418
trees = [self.source]
1419
if extra_trees is not None:
1420
trees.extend(extra_trees)
1421
if specific_files is not None:
1422
specific_files = self.target.find_related_paths_across_trees(
1423
specific_files, trees,
1424
require_versioned=require_versioned)
1425
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1426
with self.lock_read():
1427
return changes_between_git_tree_and_working_copy(
1428
self.source.store, self.source.tree,
1429
self.target, want_unchanged=want_unchanged,
1430
want_unversioned=want_unversioned)
1433
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
1436
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1437
want_unchanged=False,
1438
want_unversioned=False):
1439
"""Determine the changes between a git tree and a working tree with index.
1444
# Report dirified directories to commit_tree first, so that they can be
1445
# replaced with non-empty directories if they have contents.
1447
trust_executable = target._supports_executable()
1448
for path, index_entry in target._recurse_index_entries():
1450
live_entry = target._live_entry(path)
1451
except EnvironmentError as e:
1452
if e.errno == errno.ENOENT:
1453
# Entry was removed; keep it listed, but mark it as gone.
1454
blobs[path] = (ZERO_SHA, 0)
1455
elif e.errno == errno.EISDIR:
1456
# Backwards compatibility with Dulwich < 0.19.12;
1457
# newer versions of Dulwich return either an entry for the
1458
# submodule or None for directories.
1459
if S_ISGITLINK(index_entry.mode):
1460
blobs[path] = (index_entry.sha, index_entry.mode)
1462
# Entry was turned into a directory
1463
dirified.append((path, Tree().id, stat.S_IFDIR))
1464
store.add_object(Tree())
1468
if live_entry is None:
1469
# Entry was turned into a directory
1470
dirified.append((path, Tree().id, stat.S_IFDIR))
1471
store.add_object(Tree())
1473
mode = live_entry.mode
1474
if not trust_executable:
1475
if mode_is_executable(index_entry.mode):
1479
blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1480
if want_unversioned:
1481
for e in target.extras():
1482
st = target._lstat(e)
1484
np, accessible = osutils.normalized_filename(e)
1485
except UnicodeDecodeError:
1486
raise errors.BadFilenameEncoding(
1488
if stat.S_ISDIR(st.st_mode):
1491
blob = blob_from_path_and_stat(
1492
target.abspath(e).encode(osutils._fs_enc), st)
1493
store.add_object(blob)
1494
np = np.encode('utf-8')
1495
blobs[np] = (blob.id, cleanup_mode(st.st_mode))
1497
to_tree_sha = commit_tree(
1498
store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
1499
return store.tree_changes(
1500
from_tree_sha, to_tree_sha, include_trees=True,
1501
want_unchanged=want_unchanged, change_type_same=True), extras