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,
59
from ..revision import (
63
from ..sixish import (
68
from .mapping import (
76
class GitTreeDirectory(_mod_tree.TreeDirectory):
78
__slots__ = ['file_id', 'name', 'parent_id', 'children']
80
def __init__(self, file_id, name, parent_id):
81
self.file_id = file_id
83
self.parent_id = parent_id
96
return self.__class__(
97
self.file_id, self.name, self.parent_id)
100
return "%s(file_id=%r, name=%r, parent_id=%r)" % (
101
self.__class__.__name__, self.file_id, self.name,
104
def __eq__(self, other):
105
return (self.kind == other.kind and
106
self.file_id == other.file_id and
107
self.name == other.name and
108
self.parent_id == other.parent_id)
111
class GitTreeFile(_mod_tree.TreeFile):
113
__slots__ = ['file_id', 'name', 'parent_id', 'text_size', 'text_sha1',
116
def __init__(self, file_id, name, parent_id, text_size=None,
117
text_sha1=None, executable=None):
118
self.file_id = file_id
120
self.parent_id = parent_id
121
self.text_size = text_size
122
self.text_sha1 = text_sha1
123
self.executable = executable
129
def __eq__(self, other):
130
return (self.kind == other.kind and
131
self.file_id == other.file_id and
132
self.name == other.name and
133
self.parent_id == other.parent_id and
134
self.text_sha1 == other.text_sha1 and
135
self.text_size == other.text_size and
136
self.executable == other.executable)
139
return "%s(file_id=%r, name=%r, parent_id=%r, text_size=%r, 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, 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(revision_id)
259
if revision_id == NULL_REVISION:
261
self.mapping = default_mapping
262
self._fileid_map = GitFileIdMap(
267
commit = self.store[self.commit_id]
269
raise errors.NoSuchRevision(repository, revision_id)
270
self.tree = commit.tree
271
self._fileid_map = self.mapping.get_fileid_map(self.store.__getitem__, self.tree)
273
def _get_nested_repository(self, path):
274
nested_repo_transport = self._repository.user_transport.clone(path)
275
nested_controldir = _mod_controldir.ControlDir.open_from_transport(nested_repo_transport)
276
return nested_controldir.find_repository()
278
def supports_rename_tracking(self):
281
def get_file_revision(self, path):
282
change_scanner = self._repository._file_change_scanner
283
if self.commit_id == ZERO_SHA:
285
(unused_path, commit_id) = change_scanner.find_last_change_revision(
286
path.encode('utf-8'), self.commit_id)
287
return self._repository.lookup_foreign_revision_id(commit_id, self.mapping)
289
def get_file_mtime(self, path):
291
revid = self.get_file_revision(path)
293
raise errors.NoSuchFile(path)
295
rev = self._repository.get_revision(revid)
296
except errors.NoSuchRevision:
297
raise _mod_tree.FileTimestampUnavailable(path)
300
def id2path(self, file_id):
302
path = self._fileid_map.lookup_path(file_id)
304
raise errors.NoSuchId(self, file_id)
305
if self.is_versioned(path):
307
raise errors.NoSuchId(self, file_id)
309
def is_versioned(self, path):
310
return self.has_filename(path)
312
def path2id(self, path):
313
if self.mapping.is_special_file(path):
315
if not self.is_versioned(path):
317
return self._fileid_map.lookup_file_id(osutils.safe_unicode(path))
319
def all_file_ids(self):
320
return {self.path2id(path) for path in self.all_versioned_paths()}
322
def all_versioned_paths(self):
324
todo = [(self.store, b'', self.tree)]
326
(store, path, tree_id) = todo.pop()
329
tree = store[tree_id]
330
for name, mode, hexsha in tree.items():
331
subpath = posixpath.join(path, name)
332
ret.add(subpath.decode('utf-8'))
333
if stat.S_ISDIR(mode):
334
todo.append((store, subpath, hexsha))
337
def get_root_id(self):
338
if self.tree is None:
340
return self.path2id("")
342
def has_or_had_id(self, file_id):
344
path = self.id2path(file_id)
345
except errors.NoSuchId:
349
def has_id(self, file_id):
351
path = self.id2path(file_id)
352
except errors.NoSuchId:
354
return self.has_filename(path)
356
def _lookup_path(self, path):
357
if self.tree is None:
358
raise errors.NoSuchFile(path)
360
(mode, hexsha) = tree_lookup_path(self.store.__getitem__, self.tree,
361
path.encode('utf-8'))
363
raise errors.NoSuchFile(self, path)
365
return (self.store, mode, hexsha)
367
def is_executable(self, path):
368
(store, mode, hexsha) = self._lookup_path(path)
370
# the tree root is a directory
372
return mode_is_executable(mode)
374
def kind(self, path):
375
(store, mode, hexsha) = self._lookup_path(path)
377
# the tree root is a directory
379
return mode_kind(mode)
381
def has_filename(self, path):
383
self._lookup_path(path)
384
except errors.NoSuchFile:
389
def list_files(self, include_root=False, from_dir=None, recursive=True):
390
if self.tree is None:
394
(store, mode, hexsha) = self._lookup_path(from_dir)
395
if mode is None: # Root
396
root_ie = self._get_dir_ie(b"", None)
398
parent_path = posixpath.dirname(from_dir)
399
parent_id = self._fileid_map.lookup_file_id(parent_path)
400
if mode_kind(mode) == 'directory':
401
root_ie = self._get_dir_ie(from_dir.encode("utf-8"), parent_id)
403
root_ie = self._get_file_ie(store, from_dir.encode("utf-8"),
404
posixpath.basename(from_dir), mode, hexsha)
406
yield (from_dir, "V", root_ie.kind, root_ie.file_id, root_ie)
408
if root_ie.kind == 'directory':
409
todo.append((store, from_dir.encode("utf-8"), b"", hexsha, root_ie.file_id))
411
(store, path, relpath, hexsha, parent_id) = todo.pop()
413
for name, mode, hexsha in tree.iteritems():
414
if self.mapping.is_special_file(name):
416
child_path = posixpath.join(path, name)
417
child_relpath = posixpath.join(relpath, name)
418
if stat.S_ISDIR(mode):
419
ie = self._get_dir_ie(child_path, parent_id)
421
todo.append((store, child_path, child_relpath, hexsha, ie.file_id))
423
ie = self._get_file_ie(store, child_path, name, mode, hexsha, parent_id)
424
yield child_relpath.decode('utf-8'), "V", ie.kind, ie.file_id, ie
426
def _get_file_ie(self, store, path, name, mode, hexsha, parent_id):
427
if not isinstance(path, bytes):
428
raise TypeError(path)
429
if not isinstance(name, bytes):
430
raise TypeError(name)
431
kind = mode_kind(mode)
432
path = path.decode('utf-8')
433
name = name.decode("utf-8")
434
file_id = self._fileid_map.lookup_file_id(path)
435
ie = entry_factory[kind](file_id, name, parent_id)
436
if kind == 'symlink':
437
ie.symlink_target = store[hexsha].data.decode('utf-8')
438
elif kind == 'tree-reference':
439
ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(hexsha)
441
data = store[hexsha].data
442
ie.text_sha1 = osutils.sha_string(data)
443
ie.text_size = len(data)
444
ie.executable = mode_is_executable(mode)
447
def _get_dir_ie(self, path, parent_id):
448
path = path.decode('utf-8')
449
file_id = self._fileid_map.lookup_file_id(path)
450
return GitTreeDirectory(file_id, posixpath.basename(path), parent_id)
452
def iter_child_entries(self, path, file_id=None):
453
(store, mode, tree_sha) = self._lookup_path(path)
455
if mode is not None and not stat.S_ISDIR(mode):
458
encoded_path = path.encode('utf-8')
459
file_id = self.path2id(path)
460
tree = store[tree_sha]
461
for name, mode, hexsha in tree.iteritems():
462
if self.mapping.is_special_file(name):
464
child_path = posixpath.join(encoded_path, name)
465
if stat.S_ISDIR(mode):
466
yield self._get_dir_ie(child_path, file_id)
468
yield self._get_file_ie(store, child_path, name, mode, hexsha,
471
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
472
if self.tree is None:
475
# TODO(jelmer): Support yield parents
476
raise NotImplementedError
477
if specific_files is not None:
478
if specific_files in ([""], []):
479
specific_files = None
481
specific_files = set([p.encode('utf-8') for p in specific_files])
482
todo = deque([(self.store, b"", self.tree, self.get_root_id())])
483
if specific_files is None or u"" in specific_files:
484
yield u"", self._get_dir_ie(b"", None)
486
store, path, tree_sha, parent_id = todo.popleft()
487
tree = store[tree_sha]
489
for name, mode, hexsha in tree.iteritems():
490
if self.mapping.is_special_file(name):
492
child_path = posixpath.join(path, name)
493
child_path_decoded = child_path.decode('utf-8')
494
if stat.S_ISDIR(mode):
495
if (specific_files is None or
496
any(filter(lambda p: p.startswith(child_path), specific_files))):
498
(store, child_path, hexsha, self.path2id(child_path_decoded)))
499
if specific_files is None or child_path in specific_files:
500
if stat.S_ISDIR(mode):
501
yield (child_path_decoded,
502
self._get_dir_ie(child_path, parent_id))
504
yield (child_path_decoded,
505
self._get_file_ie(store, child_path, name, mode,
507
todo.extendleft(reversed(extradirs))
509
def iter_references(self):
510
if self.supports_tree_reference():
511
for path, entry in self.iter_entries_by_dir():
512
if entry.kind == 'tree-reference':
513
yield path, self.mapping.generate_file_id(b'')
515
def get_revision_id(self):
516
"""See RevisionTree.get_revision_id."""
517
return self._revision_id
519
def get_file_sha1(self, path, stat_value=None):
520
if self.tree is None:
521
raise errors.NoSuchFile(path)
522
return osutils.sha_string(self.get_file_text(path))
524
def get_file_verifier(self, path, stat_value=None):
525
(store, mode, hexsha) = self._lookup_path(path)
526
return ("GIT", hexsha)
528
def get_file_size(self, path):
529
(store, mode, hexsha) = self._lookup_path(path)
530
if stat.S_ISREG(mode):
531
return len(store[hexsha].data)
534
def get_file_text(self, path):
535
"""See RevisionTree.get_file_text."""
536
(store, mode, hexsha) = self._lookup_path(path)
537
if stat.S_ISREG(mode):
538
return store[hexsha].data
542
def get_symlink_target(self, path):
543
"""See RevisionTree.get_symlink_target."""
544
(store, mode, hexsha) = self._lookup_path(path)
545
if stat.S_ISLNK(mode):
546
return store[hexsha].data.decode('utf-8')
550
def get_reference_revision(self, path):
551
"""See RevisionTree.get_symlink_target."""
552
(store, mode, hexsha) = self._lookup_path(path)
553
if S_ISGITLINK(mode):
554
nested_repo = self._get_nested_repository(path)
555
return nested_repo.lookup_foreign_revision_id(hexsha)
559
def _comparison_data(self, entry, path):
561
return None, False, None
562
return entry.kind, entry.executable, None
564
def path_content_summary(self, path):
565
"""See Tree.path_content_summary."""
567
(store, mode, hexsha) = self._lookup_path(path)
568
except errors.NoSuchFile:
569
return ('missing', None, None, None)
570
kind = mode_kind(mode)
572
executable = mode_is_executable(mode)
573
contents = store[hexsha].data
574
return (kind, len(contents), executable, osutils.sha_string(contents))
575
elif kind == 'symlink':
576
return (kind, None, None, store[hexsha].data.decode('utf-8'))
577
elif kind == 'tree-reference':
578
nested_repo = self._get_nested_repository(path)
579
return (kind, None, None,
580
nested_repo.lookup_foreign_revision_id(hexsha))
582
return (kind, None, None, None)
584
def find_related_paths_across_trees(self, paths, trees=[],
585
require_versioned=True):
588
if require_versioned:
589
trees = [self] + (trees if trees is not None else [])
593
if t.is_versioned(p):
598
raise errors.PathsNotVersionedError(unversioned)
599
return filter(self.is_versioned, paths)
601
def _iter_tree_contents(self, include_trees=False):
602
if self.tree is None:
604
return self.store.iter_tree_contents(
605
self.tree, include_trees=include_trees)
607
def annotate_iter(self, path, default_revision=CURRENT_REVISION):
608
"""Return an iterator of revision_id, line tuples.
610
For working trees (and mutable trees in general), the special
611
revision_id 'current:' will be used for lines that are new in this
612
tree, e.g. uncommitted changes.
613
:param default_revision: For lines that don't match a basis, mark them
614
with this revision id. Not all implementations will make use of
617
with self.lock_read():
618
# Now we have the parents of this content
619
from breezy.annotate import Annotator
620
from .annotate import AnnotateProvider
621
annotator = Annotator(AnnotateProvider(
622
self._repository._file_change_scanner))
623
this_key = (path, self.get_file_revision(path))
624
annotations = [(key[-1], line)
625
for key, line in annotator.annotate_flat(this_key)]
628
def _get_rules_searcher(self, default_searcher):
629
return default_searcher
631
def walkdirs(self, prefix=u""):
632
(store, mode, hexsha) = self._lookup_path(prefix)
633
todo = deque([(store, prefix.encode('utf-8'), hexsha, self.path2id(prefix))])
635
store, path, tree_sha, parent_id = todo.popleft()
636
path_decoded = path.decode('utf-8')
637
tree = store[tree_sha]
639
for name, mode, hexsha in tree.iteritems():
640
if self.mapping.is_special_file(name):
642
child_path = posixpath.join(path, name)
643
file_id = self.path2id(child_path.decode('utf-8'))
644
if stat.S_ISDIR(mode):
645
todo.append((store, child_path, hexsha, file_id))
647
(child_path.decode('utf-8'), name.decode('utf-8'),
648
mode_kind(mode), None,
649
file_id, mode_kind(mode)))
650
yield (path_decoded, parent_id), children
653
def tree_delta_from_git_changes(changes, mapping,
654
fileid_maps, specific_files=None,
655
require_versioned=False, include_root=False,
657
"""Create a TreeDelta from two git trees.
659
source and target are iterators over tuples with:
660
(filename, sha, mode)
662
(old_fileid_map, new_fileid_map) = fileid_maps
663
if target_extras is None:
664
target_extras = set()
665
ret = delta.TreeDelta()
666
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
667
if newpath == b'' and not include_root:
670
oldpath_encoded = None
672
oldpath_decoded = oldpath.decode('utf-8')
674
newpath_decoded = None
676
newpath_decoded = newpath.decode('utf-8')
677
if not (specific_files is None or
678
(oldpath is not None and osutils.is_inside_or_parent_of_any(specific_files, oldpath_decoded)) or
679
(newpath is not None and osutils.is_inside_or_parent_of_any(specific_files, newpath_decoded))):
681
if mapping.is_special_file(oldpath):
683
if mapping.is_special_file(newpath):
685
if oldpath is None and newpath is None:
688
if newpath in target_extras:
689
ret.unversioned.append(
690
(osutils.normalized_filename(newpath)[0], None, mode_kind(newmode)))
692
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
693
ret.added.append((newpath_decoded, file_id, mode_kind(newmode)))
694
elif newpath is None or newmode == 0:
695
file_id = old_fileid_map.lookup_file_id(oldpath_decoded)
696
ret.removed.append((oldpath_decoded, file_id, mode_kind(oldmode)))
697
elif oldpath != newpath:
698
file_id = old_fileid_map.lookup_file_id(oldpath_decoded)
700
(oldpath_decoded, newpath.decode('utf-8'), file_id,
701
mode_kind(newmode), (oldsha != newsha),
702
(oldmode != newmode)))
703
elif mode_kind(oldmode) != mode_kind(newmode):
704
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
705
ret.kind_changed.append(
706
(newpath_decoded, file_id, mode_kind(oldmode),
708
elif oldsha != newsha or oldmode != newmode:
709
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
711
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
713
(newpath_decoded, file_id, mode_kind(newmode),
714
(oldsha != newsha), (oldmode != newmode)))
716
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
717
ret.unchanged.append((newpath_decoded, file_id, mode_kind(newmode)))
722
def changes_from_git_changes(changes, mapping, specific_files=None, include_unchanged=False,
724
"""Create a iter_changes-like generator from a git stream.
726
source and target are iterators over tuples with:
727
(filename, sha, mode)
729
if target_extras is None:
730
target_extras = set()
731
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
732
if oldpath is not None:
733
oldpath_decoded = oldpath.decode('utf-8')
735
oldpath_decoded = None
736
if newpath is not None:
737
newpath_decoded = newpath.decode('utf-8')
739
newpath_decoded = None
740
if not (specific_files is None or
741
(oldpath_decoded is not None and osutils.is_inside_or_parent_of_any(specific_files, oldpath_decoded)) or
742
(newpath_decoded is not None and osutils.is_inside_or_parent_of_any(specific_files, newpath_decoded))):
744
if oldpath is not None and mapping.is_special_file(oldpath):
746
if newpath is not None and mapping.is_special_file(newpath):
748
if oldpath_decoded is None:
749
fileid = mapping.generate_file_id(newpath_decoded)
758
oldexe = mode_is_executable(oldmode)
759
oldkind = mode_kind(oldmode)
763
if oldpath_decoded == u'':
767
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
768
oldparent = mapping.generate_file_id(oldparentpath)
769
fileid = mapping.generate_file_id(oldpath_decoded)
770
if newpath_decoded is None:
777
newversioned = (newpath_decoded not in target_extras)
779
newexe = mode_is_executable(newmode)
780
newkind = mode_kind(newmode)
784
if newpath_decoded == u'':
788
newparentpath, newname = osutils.split(newpath_decoded)
789
newparent = mapping.generate_file_id(newparentpath)
790
if (not include_unchanged and
791
oldkind == 'directory' and newkind == 'directory' and
792
oldpath_decoded == newpath_decoded):
794
yield (fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
795
(oldversioned, newversioned),
796
(oldparent, newparent), (oldname, newname),
797
(oldkind, newkind), (oldexe, newexe))
800
class InterGitTrees(_mod_tree.InterTree):
801
"""InterTree that works between two git trees."""
803
_matching_from_tree_format = None
804
_matching_to_tree_format = None
805
_test_mutable_trees_to_test_trees = None
808
def is_compatible(cls, source, target):
809
return (isinstance(source, GitRevisionTree) and
810
isinstance(target, GitRevisionTree))
812
def compare(self, want_unchanged=False, specific_files=None,
813
extra_trees=None, require_versioned=False, include_root=False,
814
want_unversioned=False):
815
with self.lock_read():
816
changes, target_extras = self._iter_git_changes(
817
want_unchanged=want_unchanged,
818
require_versioned=require_versioned,
819
specific_files=specific_files,
820
extra_trees=extra_trees,
821
want_unversioned=want_unversioned)
822
source_fileid_map = self.source._fileid_map
823
target_fileid_map = self.target._fileid_map
824
return tree_delta_from_git_changes(changes, self.target.mapping,
825
(source_fileid_map, target_fileid_map),
826
specific_files=specific_files, include_root=include_root,
827
target_extras=target_extras)
829
def iter_changes(self, include_unchanged=False, specific_files=None,
830
pb=None, extra_trees=[], require_versioned=True,
831
want_unversioned=False):
832
with self.lock_read():
833
changes, target_extras = self._iter_git_changes(
834
want_unchanged=include_unchanged,
835
require_versioned=require_versioned,
836
specific_files=specific_files,
837
extra_trees=extra_trees,
838
want_unversioned=want_unversioned)
839
return changes_from_git_changes(
840
changes, self.target.mapping,
841
specific_files=specific_files,
842
include_unchanged=include_unchanged,
843
target_extras=target_extras)
845
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
846
require_versioned=False, extra_trees=None,
847
want_unversioned=False):
848
raise NotImplementedError(self._iter_git_changes)
851
class InterGitRevisionTrees(InterGitTrees):
852
"""InterTree that works between two git revision trees."""
854
_matching_from_tree_format = None
855
_matching_to_tree_format = None
856
_test_mutable_trees_to_test_trees = None
859
def is_compatible(cls, source, target):
860
return (isinstance(source, GitRevisionTree) and
861
isinstance(target, GitRevisionTree))
863
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
864
require_versioned=True, extra_trees=None,
865
want_unversioned=False):
866
trees = [self.source]
867
if extra_trees is not None:
868
trees.extend(extra_trees)
869
if specific_files is not None:
870
specific_files = self.target.find_related_paths_across_trees(
871
specific_files, trees,
872
require_versioned=require_versioned)
874
if self.source._repository._git.object_store != self.target._repository._git.object_store:
875
store = OverlayObjectStore([self.source._repository._git.object_store,
876
self.target._repository._git.object_store])
878
store = self.source._repository._git.object_store
879
return self.source._repository._git.object_store.tree_changes(
880
self.source.tree, self.target.tree, want_unchanged=want_unchanged,
881
include_trees=True, change_type_same=True), set()
884
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
887
class MutableGitIndexTree(mutabletree.MutableTree):
890
self._lock_mode = None
892
self._versioned_dirs = None
893
self._index_dirty = False
895
def is_versioned(self, path):
896
with self.lock_read():
897
path = path.rstrip('/').encode('utf-8')
898
(index, subpath) = self._lookup_index(path)
899
return (subpath in index or self._has_dir(path))
901
def _has_dir(self, path):
902
if not isinstance(path, bytes):
903
raise TypeError(path)
906
if self._versioned_dirs is None:
908
return path in self._versioned_dirs
910
def _load_dirs(self):
911
if self._lock_mode is None:
912
raise errors.ObjectNotLocked(self)
913
self._versioned_dirs = set()
914
# TODO(jelmer): Browse over all indexes
915
for p, i in self._recurse_index_entries():
916
self._ensure_versioned_dir(posixpath.dirname(p))
918
def _ensure_versioned_dir(self, dirname):
919
if not isinstance(dirname, bytes):
920
raise TypeError(dirname)
921
if dirname in self._versioned_dirs:
924
self._ensure_versioned_dir(posixpath.dirname(dirname))
925
self._versioned_dirs.add(dirname)
927
def path2id(self, path):
928
with self.lock_read():
929
path = path.rstrip('/')
930
if self.is_versioned(path.rstrip('/')):
931
return self._fileid_map.lookup_file_id(osutils.safe_unicode(path))
934
def has_id(self, file_id):
936
self.id2path(file_id)
937
except errors.NoSuchId:
942
def id2path(self, file_id):
945
if type(file_id) is not bytes:
946
raise TypeError(file_id)
947
with self.lock_read():
949
path = self._fileid_map.lookup_path(file_id)
951
raise errors.NoSuchId(self, file_id)
952
if self.is_versioned(path):
954
raise errors.NoSuchId(self, file_id)
956
def _set_root_id(self, file_id):
957
self._fileid_map.set_file_id("", file_id)
959
def get_root_id(self):
960
return self.path2id(u"")
962
def _add(self, files, ids, kinds):
963
for (path, file_id, kind) in zip(files, ids, kinds):
964
if file_id is not None:
965
raise workingtree.SettingFileIdUnsupported()
966
path, can_access = osutils.normalized_filename(path)
968
raise errors.InvalidNormalization(path)
969
self._index_add_entry(path, kind)
971
def _read_submodule_head(self, path):
972
raise NotImplementedError(self._read_submodule_head)
974
def _lookup_index(self, encoded_path):
975
if not isinstance(encoded_path, bytes):
976
raise TypeError(encoded_path)
977
# TODO(jelmer): Look in other indexes
978
return self.index, encoded_path
980
def _index_del_entry(self, index, path):
982
# TODO(jelmer): Keep track of dirty per index
983
self._index_dirty = True
985
def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
986
if kind == "directory":
987
# Git indexes don't contain directories
992
file, stat_val = self.get_file_with_stat(path)
993
except (errors.NoSuchFile, IOError):
994
# TODO: Rather than come up with something here, use the old index
996
stat_val = os.stat_result(
997
(stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
999
blob.set_raw_string(file.read())
1000
# Add object to the repository if it didn't exist yet
1001
if not blob.id in self.store:
1002
self.store.add_object(blob)
1004
elif kind == "symlink":
1007
stat_val = self._lstat(path)
1008
except EnvironmentError:
1009
# TODO: Rather than come up with something here, use the
1011
stat_val = os.stat_result(
1012
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1013
blob.set_raw_string(
1014
self.get_symlink_target(path).encode("utf-8"))
1015
# Add object to the repository if it didn't exist yet
1016
if not blob.id in self.store:
1017
self.store.add_object(blob)
1019
elif kind == "tree-reference":
1020
if reference_revision is not None:
1021
hexsha = self.branch.lookup_bzr_revision_id(reference_revision)[0]
1023
hexsha = self._read_submodule_head(path)
1025
raise errors.NoCommits(path)
1027
stat_val = self._lstat(path)
1028
except EnvironmentError:
1029
stat_val = os.stat_result(
1030
(S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1031
stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
1033
raise AssertionError("unknown kind '%s'" % kind)
1034
# Add an entry to the index or update the existing entry
1035
ensure_normalized_path(path)
1036
encoded_path = path.encode("utf-8")
1037
if b'\r' in encoded_path or b'\n' in encoded_path:
1038
# TODO(jelmer): Why do we need to do this?
1039
trace.mutter('ignoring path with invalid newline in it: %r', path)
1041
(index, index_path) = self._lookup_index(encoded_path)
1042
index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
1043
self._index_dirty = True
1044
if self._versioned_dirs is not None:
1045
self._ensure_versioned_dir(index_path)
1047
def _recurse_index_entries(self, index=None, basepath=b""):
1048
# Iterate over all index entries
1049
with self.lock_read():
1052
for path, value in index.items():
1053
yield (posixpath.join(basepath, path), value)
1054
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1055
if S_ISGITLINK(mode):
1056
pass # TODO(jelmer): dive into submodule
1059
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
1061
raise NotImplementedError(self.iter_entries_by_dir)
1062
with self.lock_read():
1063
if specific_files is not None:
1064
specific_files = set(specific_files)
1066
specific_files = None
1067
root_ie = self._get_dir_ie(u"", None)
1069
if specific_files is None or u"" in specific_files:
1070
ret[(u"", u"")] = root_ie
1071
dir_ids = {u"": root_ie.file_id}
1072
for path, value in self._recurse_index_entries():
1073
if self.mapping.is_special_file(path):
1075
path = path.decode("utf-8")
1076
if specific_files is not None and not path in specific_files:
1078
(parent, name) = posixpath.split(path)
1080
file_ie = self._get_file_ie(name, path, value, None)
1081
except errors.NoSuchFile:
1083
if yield_parents or specific_files is None:
1084
for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
1086
ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
1087
file_ie.parent_id = self.path2id(parent)
1088
ret[(posixpath.dirname(path), path)] = file_ie
1089
return ((path, ie) for ((_, path), ie) in sorted(viewitems(ret)))
1091
def iter_references(self):
1092
# TODO(jelmer): Implement a more efficient version of this
1093
for path, entry in self.iter_entries_by_dir():
1094
if entry.kind == 'tree-reference':
1095
yield path, self.mapping.generate_file_id(b'')
1097
def _get_dir_ie(self, path, parent_id):
1098
file_id = self.path2id(path)
1099
return GitTreeDirectory(file_id,
1100
posixpath.basename(path).strip("/"), parent_id)
1102
def _get_file_ie(self, name, path, value, parent_id):
1103
if not isinstance(name, text_type):
1104
raise TypeError(name)
1105
if not isinstance(path, text_type):
1106
raise TypeError(path)
1107
if not isinstance(value, tuple) or len(value) != 10:
1108
raise TypeError(value)
1109
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1110
file_id = self.path2id(path)
1111
if not isinstance(file_id, bytes):
1112
raise TypeError(file_id)
1113
kind = mode_kind(mode)
1114
ie = entry_factory[kind](file_id, name, parent_id)
1115
if kind == 'symlink':
1116
ie.symlink_target = self.get_symlink_target(path)
1117
elif kind == 'tree-reference':
1118
ie.reference_revision = self.get_reference_revision(path)
1121
data = self.get_file_text(path)
1122
except errors.NoSuchFile:
1124
except IOError as e:
1125
if e.errno != errno.ENOENT:
1129
data = self.branch.repository._git.object_store[sha].data
1130
ie.text_sha1 = osutils.sha_string(data)
1131
ie.text_size = len(data)
1132
ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1135
def _add_missing_parent_ids(self, path, dir_ids):
1138
parent = posixpath.dirname(path).strip("/")
1139
ret = self._add_missing_parent_ids(parent, dir_ids)
1140
parent_id = dir_ids[parent]
1141
ie = self._get_dir_ie(path, parent_id)
1142
dir_ids[path] = ie.file_id
1143
ret.append((path, ie))
1146
def _comparison_data(self, entry, path):
1148
return None, False, None
1149
return entry.kind, entry.executable, None
1151
def _unversion_path(self, path):
1152
if self._lock_mode is None:
1153
raise errors.ObjectNotLocked(self)
1154
encoded_path = path.encode("utf-8")
1156
(index, subpath) = self._lookup_index(encoded_path)
1158
self._index_del_entry(index, encoded_path)
1160
# A directory, perhaps?
1161
# TODO(jelmer): Deletes that involve submodules?
1162
for p in list(index):
1163
if p.startswith(subpath+b"/"):
1165
self._index_del_entry(index, p)
1168
self._versioned_dirs = None
1171
def unversion(self, paths):
1172
with self.lock_tree_write():
1174
if self._unversion_path(path) == 0:
1175
raise errors.NoSuchFile(path)
1176
self._versioned_dirs = None
1182
def update_basis_by_delta(self, revid, delta):
1183
# TODO(jelmer): This shouldn't be called, it's inventory specific.
1184
for (old_path, new_path, file_id, ie) in delta:
1185
if old_path is not None:
1186
(index, old_subpath) = self._lookup_index(old_path.encode('utf-8'))
1187
if old_subpath in index:
1188
self._index_del_entry(index, old_subpath)
1189
self._versioned_dirs = None
1190
if new_path is not None and ie.kind != 'directory':
1191
self._index_add_entry(new_path, ie.kind)
1193
self._set_merges_from_parent_ids([])
1195
def move(self, from_paths, to_dir=None, after=None):
1197
with self.lock_tree_write():
1198
to_abs = self.abspath(to_dir)
1199
if not os.path.isdir(to_abs):
1200
raise errors.BzrMoveFailedError('', to_dir,
1201
errors.NotADirectory(to_abs))
1203
for from_rel in from_paths:
1204
from_tail = os.path.split(from_rel)[-1]
1205
to_rel = os.path.join(to_dir, from_tail)
1206
self.rename_one(from_rel, to_rel, after=after)
1207
rename_tuples.append((from_rel, to_rel))
1209
return rename_tuples
1211
def rename_one(self, from_rel, to_rel, after=None):
1212
from_path = from_rel.encode("utf-8")
1213
to_rel, can_access = osutils.normalized_filename(to_rel)
1215
raise errors.InvalidNormalization(to_rel)
1216
to_path = to_rel.encode("utf-8")
1217
with self.lock_tree_write():
1219
# Perhaps it's already moved?
1221
not self.has_filename(from_rel) and
1222
self.has_filename(to_rel) and
1223
not self.is_versioned(to_rel))
1225
if not self.has_filename(to_rel):
1226
raise errors.BzrMoveFailedError(from_rel, to_rel,
1227
errors.NoSuchFile(to_rel))
1228
if self.basis_tree().is_versioned(to_rel):
1229
raise errors.BzrMoveFailedError(from_rel, to_rel,
1230
errors.AlreadyVersionedError(to_rel))
1232
kind = self.kind(to_rel)
1235
to_kind = self.kind(to_rel)
1236
except errors.NoSuchFile:
1237
exc_type = errors.BzrRenameFailedError
1240
exc_type = errors.BzrMoveFailedError
1241
if self.is_versioned(to_rel):
1242
raise exc_type(from_rel, to_rel,
1243
errors.AlreadyVersionedError(to_rel))
1244
if not self.has_filename(from_rel):
1245
raise errors.BzrMoveFailedError(from_rel, to_rel,
1246
errors.NoSuchFile(from_rel))
1247
kind = self.kind(from_rel)
1248
if not self.is_versioned(from_rel) and kind != 'directory':
1249
raise exc_type(from_rel, to_rel,
1250
errors.NotVersionedError(from_rel))
1251
if self.has_filename(to_rel):
1252
raise errors.RenameFailedFilesExist(
1253
from_rel, to_rel, errors.FileExists(to_rel))
1255
kind = self.kind(from_rel)
1257
if not after and kind != 'directory':
1258
(index, from_subpath) = self._lookup_index(from_path)
1259
if from_subpath not in index:
1261
raise errors.BzrMoveFailedError(from_rel, to_rel,
1262
errors.NotVersionedError(path=from_rel))
1266
self._rename_one(from_rel, to_rel)
1267
except OSError as e:
1268
if e.errno == errno.ENOENT:
1269
raise errors.BzrMoveFailedError(from_rel, to_rel,
1270
errors.NoSuchFile(to_rel))
1272
if kind != 'directory':
1273
(index, from_index_path) = self._lookup_index(from_path)
1275
self._index_del_entry(index, from_path)
1278
self._index_add_entry(to_rel, kind)
1280
todo = [(p, i) for (p, i) in self._recurse_index_entries() if p.startswith(from_path+b'/')]
1281
for child_path, child_value in todo:
1282
(child_to_index, child_to_index_path) = self._lookup_index(
1283
posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
1284
child_to_index[child_to_index_path] = child_value
1285
# TODO(jelmer): Mark individual index as dirty
1286
self._index_dirty = True
1287
(child_from_index, child_from_index_path) = self._lookup_index(child_path)
1288
self._index_del_entry(child_from_index, child_from_index_path)
1290
self._versioned_dirs = None
1293
def find_related_paths_across_trees(self, paths, trees=[],
1294
require_versioned=True):
1298
if require_versioned:
1299
trees = [self] + (trees if trees is not None else [])
1303
if t.is_versioned(p):
1308
raise errors.PathsNotVersionedError(unversioned)
1310
return filter(self.is_versioned, paths)
1312
def path_content_summary(self, path):
1313
"""See Tree.path_content_summary."""
1315
stat_result = self._lstat(path)
1316
except OSError as e:
1317
if getattr(e, 'errno', None) == errno.ENOENT:
1319
return ('missing', None, None, None)
1320
# propagate other errors
1322
kind = mode_kind(stat_result.st_mode)
1324
return self._file_content_summary(path, stat_result)
1325
elif kind == 'directory':
1326
# perhaps it looks like a plain directory, but it's really a
1328
if self._directory_is_tree_reference(path):
1329
kind = 'tree-reference'
1330
return kind, None, None, None
1331
elif kind == 'symlink':
1332
target = osutils.readlink(self.abspath(path))
1333
return ('symlink', None, None, target)
1335
return (kind, None, None, None)
1337
def kind(self, relpath):
1338
kind = osutils.file_kind(self.abspath(relpath))
1339
if kind == 'directory':
1340
(index, index_path) = self._lookup_index(relpath.encode('utf-8'))
1344
mode = index[index_path].mode
1348
if S_ISGITLINK(mode):
1349
return 'tree-reference'
1354
def _live_entry(self, relpath):
1355
raise NotImplementedError(self._live_entry)
1358
class InterIndexGitTree(InterGitTrees):
1359
"""InterTree that works between a Git revision tree and an index."""
1361
def __init__(self, source, target):
1362
super(InterIndexGitTree, self).__init__(source, target)
1363
self._index = target.index
1366
def is_compatible(cls, source, target):
1367
return (isinstance(source, GitRevisionTree) and
1368
isinstance(target, MutableGitIndexTree))
1370
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1371
require_versioned=False, extra_trees=None,
1372
want_unversioned=False):
1373
trees = [self.source]
1374
if extra_trees is not None:
1375
trees.extend(extra_trees)
1376
if specific_files is not None:
1377
specific_files = self.target.find_related_paths_across_trees(
1378
specific_files, trees,
1379
require_versioned=require_versioned)
1380
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1381
with self.lock_read():
1382
return changes_between_git_tree_and_working_copy(
1383
self.source.store, self.source.tree,
1384
self.target, want_unchanged=want_unchanged,
1385
want_unversioned=want_unversioned)
1388
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
1391
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1392
want_unchanged=False, want_unversioned=False):
1393
"""Determine the changes between a git tree and a working tree with index.
1398
# Report dirified directories to commit_tree first, so that they can be
1399
# replaced with non-empty directories if they have contents.
1401
for path, index_entry in target._recurse_index_entries():
1403
live_entry = target._live_entry(path)
1404
except EnvironmentError as e:
1405
if e.errno == errno.ENOENT:
1406
# Entry was removed; keep it listed, but mark it as gone.
1407
blobs[path] = (ZERO_SHA, 0)
1408
elif e.errno == errno.EISDIR:
1409
# Entry was turned into a directory
1410
dirified.append((path, Tree().id, stat.S_IFDIR))
1411
store.add_object(Tree())
1415
blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1416
if want_unversioned:
1417
for e in target.extras():
1418
st = target._lstat(e)
1420
np, accessible = osutils.normalized_filename(e)
1421
except UnicodeDecodeError:
1422
raise errors.BadFilenameEncoding(
1424
if stat.S_ISDIR(st.st_mode):
1427
blob = blob_from_path_and_stat(target.abspath(e).encode(osutils._fs_enc), st)
1428
store.add_object(blob)
1429
np = np.encode('utf-8')
1430
blobs[np] = (blob.id, cleanup_mode(st.st_mode))
1432
to_tree_sha = commit_tree(store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
1433
return store.tree_changes(
1434
from_tree_sha, to_tree_sha, include_trees=True,
1435
want_unchanged=want_unchanged, change_type_same=True), extras