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
23
from io import BytesIO
26
from dulwich.index import (
27
blob_from_path_and_stat,
30
index_entry_from_stat,
32
from dulwich.object_store import (
36
from dulwich.objects import (
47
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, 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, reference_revision=%r)" % (
208
type(self).__name__, self.file_id, self.name, self.parent_id,
209
self.reference_revision)
211
def __eq__(self, other):
212
return (self.kind == other.kind and
213
self.file_id == other.file_id and
214
self.name == other.name and
215
self.parent_id == other.parent_id and
216
self.reference_revision == other.reference_revision)
219
return self.__class__(
220
self.file_id, self.name, self.parent_id,
221
self.reference_revision)
225
'directory': GitTreeDirectory,
227
'symlink': GitTreeSymlink,
228
'tree-reference': GitTreeSubmodule,
232
def ensure_normalized_path(path):
233
"""Check whether path is normalized.
235
:raises InvalidNormalization: When path is not normalized, and cannot be
236
accessed on this platform by the normalized path.
237
:return: The NFC normalised version of path.
239
norm_path, can_access = osutils.normalized_filename(path)
240
if norm_path != path:
244
raise errors.InvalidNormalization(path)
248
class GitRevisionTree(revisiontree.RevisionTree):
249
"""Revision tree implementation based on Git objects."""
251
def __init__(self, repository, revision_id):
252
self._revision_id = revision_id
253
self._repository = repository
254
self.store = repository._git.object_store
255
if not isinstance(revision_id, bytes):
256
raise TypeError(revision_id)
257
self.commit_id, self.mapping = repository.lookup_bzr_revision_id(revision_id)
258
if revision_id == NULL_REVISION:
260
self.mapping = default_mapping
261
self._fileid_map = GitFileIdMap(
266
commit = self.store[self.commit_id]
268
raise errors.NoSuchRevision(repository, revision_id)
269
self.tree = commit.tree
270
self._fileid_map = self.mapping.get_fileid_map(self.store.__getitem__, self.tree)
272
def _get_nested_repository(self, path):
273
nested_repo_transport = self._repository.user_transport.clone(path)
274
nested_controldir = _mod_controldir.ControlDir.open_from_transport(nested_repo_transport)
275
return nested_controldir.find_repository()
277
def supports_rename_tracking(self):
280
def get_file_revision(self, path, file_id=None):
281
change_scanner = self._repository._file_change_scanner
282
if self.commit_id == ZERO_SHA:
284
(unused_path, commit_id) = change_scanner.find_last_change_revision(
285
path.encode('utf-8'), self.commit_id)
286
return self._repository.lookup_foreign_revision_id(commit_id, self.mapping)
288
def get_file_mtime(self, path, file_id=None):
290
revid = self.get_file_revision(path, file_id)
292
raise _mod_tree.FileTimestampUnavailable(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._fileid_map.lookup_path(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
return self._fileid_map.lookup_file_id(osutils.safe_unicode(path))
316
def all_file_ids(self):
317
return set(self._fileid_map.all_file_ids())
319
def all_versioned_paths(self):
321
todo = [(self.store, b'', self.tree)]
323
(store, path, tree_id) = todo.pop()
326
tree = store[tree_id]
327
for name, mode, hexsha in tree.items():
328
subpath = posixpath.join(path, name)
329
if stat.S_ISDIR(mode):
330
todo.append((store, subpath, hexsha))
332
ret.add(subpath.decode('utf-8'))
335
def get_root_id(self):
336
if self.tree is None:
338
return self.path2id("")
340
def has_or_had_id(self, file_id):
342
path = self.id2path(file_id)
343
except errors.NoSuchId:
347
def has_id(self, file_id):
349
path = self.id2path(file_id)
350
except errors.NoSuchId:
352
return self.has_filename(path)
354
def _lookup_path(self, path):
355
if self.tree is None:
356
raise errors.NoSuchFile(path)
358
(mode, hexsha) = tree_lookup_path(self.store.__getitem__, self.tree,
359
path.encode('utf-8'))
361
raise errors.NoSuchFile(self, path)
363
return (self.store, mode, hexsha)
365
def is_executable(self, path, file_id=None):
366
(store, mode, hexsha) = self._lookup_path(path)
368
# the tree root is a directory
370
return mode_is_executable(mode)
372
def kind(self, path, file_id=None):
373
(store, mode, hexsha) = self._lookup_path(path)
375
# the tree root is a directory
377
return mode_kind(mode)
379
def has_filename(self, path):
381
self._lookup_path(path)
382
except errors.NoSuchFile:
387
def list_files(self, include_root=False, from_dir=None, recursive=True):
388
if self.tree is None:
392
(store, mode, hexsha) = self._lookup_path(from_dir)
393
if mode is None: # Root
394
root_ie = self._get_dir_ie(b"", None)
396
parent_path = posixpath.dirname(from_dir.encode("utf-8"))
397
parent_id = self._fileid_map.lookup_file_id(parent_path)
398
if mode_kind(mode) == 'directory':
399
root_ie = self._get_dir_ie(from_dir.encode("utf-8"), parent_id)
401
root_ie = self._get_file_ie(store, from_dir.encode("utf-8"),
402
posixpath.basename(from_dir), mode, hexsha)
403
if from_dir != "" or include_root:
404
yield (from_dir, "V", root_ie.kind, root_ie.file_id, root_ie)
406
if root_ie.kind == 'directory':
407
todo.append((store, from_dir.encode("utf-8"), hexsha, root_ie.file_id))
409
(store, path, hexsha, parent_id) = todo.pop()
411
for name, mode, hexsha in tree.iteritems():
412
if self.mapping.is_special_file(name):
414
child_path = posixpath.join(path, name)
415
if stat.S_ISDIR(mode):
416
ie = self._get_dir_ie(child_path, parent_id)
418
todo.append((store, child_path, hexsha, ie.file_id))
420
ie = self._get_file_ie(store, child_path, name, mode, hexsha, parent_id)
421
yield child_path.decode('utf-8'), "V", ie.kind, ie.file_id, ie
423
def _get_file_ie(self, store, path, name, mode, hexsha, parent_id):
424
if not isinstance(path, bytes):
425
raise TypeError(path)
426
if not isinstance(name, bytes):
427
raise TypeError(name)
428
kind = mode_kind(mode)
429
path = path.decode('utf-8')
430
name = name.decode("utf-8")
431
file_id = self._fileid_map.lookup_file_id(path)
432
ie = entry_factory[kind](file_id, name, parent_id)
433
if kind == 'symlink':
434
ie.symlink_target = store[hexsha].data.decode('utf-8')
435
elif kind == 'tree-reference':
436
ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(hexsha)
438
data = store[hexsha].data
439
ie.text_sha1 = osutils.sha_string(data)
440
ie.text_size = len(data)
441
ie.executable = mode_is_executable(mode)
444
def _get_dir_ie(self, path, parent_id):
445
path = path.decode('utf-8')
446
file_id = self._fileid_map.lookup_file_id(path)
447
return GitTreeDirectory(file_id, posixpath.basename(path), parent_id)
449
def iter_child_entries(self, path, file_id=None):
450
(store, mode, tree_sha) = self._lookup_path(path)
452
if not stat.S_ISDIR(mode):
455
encoded_path = path.encode('utf-8')
456
file_id = self.path2id(path)
457
tree = store[tree_sha]
458
for name, mode, hexsha in tree.iteritems():
459
if self.mapping.is_special_file(name):
461
child_path = posixpath.join(encoded_path, name)
462
if stat.S_ISDIR(mode):
463
yield self._get_dir_ie(child_path, file_id)
465
yield self._get_file_ie(store, child_path, name, mode, hexsha,
468
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
469
if self.tree is None:
472
# TODO(jelmer): Support yield parents
473
raise NotImplementedError
474
if specific_files is not None:
475
if specific_files in ([""], []):
476
specific_files = None
478
specific_files = set([p.encode('utf-8') for p in specific_files])
479
todo = [(self.store, b"", self.tree, None)]
481
store, path, tree_sha, parent_id = todo.pop()
482
ie = self._get_dir_ie(path, parent_id)
483
if specific_files is None or path in specific_files:
484
yield path.decode("utf-8"), ie
485
tree = store[tree_sha]
486
for name, mode, hexsha in tree.iteritems():
487
if self.mapping.is_special_file(name):
489
child_path = posixpath.join(path, name)
490
if stat.S_ISDIR(mode):
491
if (specific_files is None or
492
any(filter(lambda p: p.startswith(child_path), specific_files))):
493
todo.append((store, child_path, hexsha, ie.file_id))
494
elif specific_files is None or child_path in specific_files:
495
yield (child_path.decode("utf-8"),
496
self._get_file_ie(store, child_path, name, mode, hexsha,
499
def get_revision_id(self):
500
"""See RevisionTree.get_revision_id."""
501
return self._revision_id
503
def get_file_sha1(self, path, file_id=None, stat_value=None):
504
if self.tree is None:
505
raise errors.NoSuchFile(path)
506
return osutils.sha_string(self.get_file_text(path, file_id))
508
def get_file_verifier(self, path, file_id=None, stat_value=None):
509
(store, mode, hexsha) = self._lookup_path(path)
510
return ("GIT", hexsha)
512
def get_file_text(self, path, file_id=None):
513
"""See RevisionTree.get_file_text."""
514
(store, mode, hexsha) = self._lookup_path(path)
515
if stat.S_ISREG(mode):
516
return store[hexsha].data
520
def get_symlink_target(self, path, file_id=None):
521
"""See RevisionTree.get_symlink_target."""
522
(store, mode, hexsha) = self._lookup_path(path)
523
if stat.S_ISLNK(mode):
524
return store[hexsha].data.decode('utf-8')
528
def get_reference_revision(self, path, file_id=None):
529
"""See RevisionTree.get_symlink_target."""
530
(store, mode, hexsha) = self._lookup_path(path)
531
if S_ISGITLINK(mode):
532
nested_repo = self._get_nested_repository(path)
533
return nested_repo.lookup_foreign_revision_id(hexsha)
537
def _comparison_data(self, entry, path):
539
return None, False, None
540
return entry.kind, entry.executable, None
542
def path_content_summary(self, path):
543
"""See Tree.path_content_summary."""
545
(store, mode, hexsha) = self._lookup_path(path)
546
except errors.NoSuchFile:
547
return ('missing', None, None, None)
548
kind = mode_kind(mode)
550
executable = mode_is_executable(mode)
551
contents = store[hexsha].data
552
return (kind, len(contents), executable, osutils.sha_string(contents))
553
elif kind == 'symlink':
554
return (kind, None, None, store[hexsha].data)
555
elif kind == 'tree-reference':
556
nested_repo = self._get_nested_repository(path)
557
return (kind, None, None,
558
nested_repo.lookup_foreign_revision_id(hexsha))
560
return (kind, None, None, None)
562
def find_related_paths_across_trees(self, paths, trees=[],
563
require_versioned=True):
566
if require_versioned:
567
trees = [self] + (trees if trees is not None else [])
571
if t.is_versioned(p):
576
raise errors.PathsNotVersionedError(unversioned)
577
return filter(self.is_versioned, paths)
579
def _iter_tree_contents(self, include_trees=False):
580
if self.tree is None:
582
return self.store.iter_tree_contents(
583
self.tree, include_trees=include_trees)
585
def annotate_iter(self, path, file_id=None,
586
default_revision=CURRENT_REVISION):
587
"""Return an iterator of revision_id, line tuples.
589
For working trees (and mutable trees in general), the special
590
revision_id 'current:' will be used for lines that are new in this
591
tree, e.g. uncommitted changes.
592
:param file_id: The file to produce an annotated version from
593
:param default_revision: For lines that don't match a basis, mark them
594
with this revision id. Not all implementations will make use of
597
with self.lock_read():
598
# Now we have the parents of this content
599
from breezy.annotate import Annotator
600
from .annotate import AnnotateProvider
601
annotator = Annotator(AnnotateProvider(
602
self._repository._file_change_scanner))
603
this_key = (path, self.get_file_revision(path))
604
annotations = [(key[-1], line)
605
for key, line in annotator.annotate_flat(this_key)]
609
def tree_delta_from_git_changes(changes, mapping,
610
fileid_maps, specific_files=None,
611
require_versioned=False, include_root=False,
613
"""Create a TreeDelta from two git trees.
615
source and target are iterators over tuples with:
616
(filename, sha, mode)
618
(old_fileid_map, new_fileid_map) = fileid_maps
619
if target_extras is None:
620
target_extras = set()
621
ret = delta.TreeDelta()
622
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
623
if newpath == b'' and not include_root:
626
oldpath_encoded = None
628
oldpath_decoded = oldpath.decode('utf-8')
630
newpath_decoded = None
632
newpath_decoded = newpath.decode('utf-8')
633
if not (specific_files is None or
634
(oldpath is not None and osutils.is_inside_or_parent_of_any(specific_files, oldpath_decoded)) or
635
(newpath is not None and osutils.is_inside_or_parent_of_any(specific_files, newpath_decoded))):
637
if mapping.is_special_file(oldpath):
639
if mapping.is_special_file(newpath):
641
if oldpath is None and newpath is None:
644
if newpath in target_extras:
645
ret.unversioned.append(
646
(osutils.normalized_filename(newpath)[0], None, mode_kind(newmode)))
648
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
649
ret.added.append((newpath_decoded, file_id, mode_kind(newmode)))
650
elif newpath is None or newmode == 0:
651
file_id = old_fileid_map.lookup_file_id(oldpath_decoded)
652
ret.removed.append((oldpath_decoded, file_id, mode_kind(oldmode)))
653
elif oldpath != newpath:
654
file_id = old_fileid_map.lookup_file_id(oldpath_decoded)
656
(oldpath_decoded, newpath.decode('utf-8'), file_id,
657
mode_kind(newmode), (oldsha != newsha),
658
(oldmode != newmode)))
659
elif mode_kind(oldmode) != mode_kind(newmode):
660
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
661
ret.kind_changed.append(
662
(newpath_decoded, file_id, mode_kind(oldmode),
664
elif oldsha != newsha or oldmode != newmode:
665
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
667
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
669
(newpath_decoded, file_id, mode_kind(newmode),
670
(oldsha != newsha), (oldmode != newmode)))
672
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
673
ret.unchanged.append((newpath_decoded, file_id, mode_kind(newmode)))
678
def changes_from_git_changes(changes, mapping, specific_files=None, include_unchanged=False,
680
"""Create a iter_changes-like generator from a git stream.
682
source and target are iterators over tuples with:
683
(filename, sha, mode)
685
if target_extras is None:
686
target_extras = set()
687
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
688
if oldpath is not None:
689
oldpath_decoded = oldpath.decode('utf-8')
691
oldpath_decoded = None
692
if newpath is not None:
693
newpath_decoded = newpath.decode('utf-8')
695
newpath_decoded = None
696
if not (specific_files is None or
697
(oldpath_decoded is not None and osutils.is_inside_or_parent_of_any(specific_files, oldpath_decoded)) or
698
(newpath_decoded is not None and osutils.is_inside_or_parent_of_any(specific_files, newpath_decoded))):
700
if oldpath is not None and mapping.is_special_file(oldpath):
702
if newpath is not None and mapping.is_special_file(newpath):
704
if oldpath_decoded is None:
705
fileid = mapping.generate_file_id(newpath_decoded)
714
oldexe = mode_is_executable(oldmode)
715
oldkind = mode_kind(oldmode)
719
if oldpath_decoded == u'':
723
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
724
oldparent = mapping.generate_file_id(oldparentpath)
725
fileid = mapping.generate_file_id(oldpath_decoded)
726
if newpath_decoded is None:
733
newversioned = (newpath_decoded not in target_extras)
735
newexe = mode_is_executable(newmode)
736
newkind = mode_kind(newmode)
740
if newpath_decoded == u'':
744
newparentpath, newname = osutils.split(newpath_decoded)
745
newparent = mapping.generate_file_id(newparentpath)
746
if (not include_unchanged and
747
oldkind == 'directory' and newkind == 'directory' and
748
oldpath_decoded == newpath_decoded):
750
yield (fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
751
(oldversioned, newversioned),
752
(oldparent, newparent), (oldname, newname),
753
(oldkind, newkind), (oldexe, newexe))
756
class InterGitTrees(_mod_tree.InterTree):
757
"""InterTree that works between two git trees."""
759
_matching_from_tree_format = None
760
_matching_to_tree_format = None
761
_test_mutable_trees_to_test_trees = None
764
def is_compatible(cls, source, target):
765
return (isinstance(source, GitRevisionTree) and
766
isinstance(target, GitRevisionTree))
768
def compare(self, want_unchanged=False, specific_files=None,
769
extra_trees=None, require_versioned=False, include_root=False,
770
want_unversioned=False):
771
with self.lock_read():
772
changes, target_extras = self._iter_git_changes(
773
want_unchanged=want_unchanged,
774
require_versioned=require_versioned,
775
specific_files=specific_files,
776
extra_trees=extra_trees,
777
want_unversioned=want_unversioned)
778
source_fileid_map = self.source._fileid_map
779
target_fileid_map = self.target._fileid_map
780
return tree_delta_from_git_changes(changes, self.target.mapping,
781
(source_fileid_map, target_fileid_map),
782
specific_files=specific_files, include_root=include_root,
783
target_extras=target_extras)
785
def iter_changes(self, include_unchanged=False, specific_files=None,
786
pb=None, extra_trees=[], require_versioned=True,
787
want_unversioned=False):
788
with self.lock_read():
789
changes, target_extras = self._iter_git_changes(
790
want_unchanged=include_unchanged,
791
require_versioned=require_versioned,
792
specific_files=specific_files,
793
extra_trees=extra_trees,
794
want_unversioned=want_unversioned)
795
return changes_from_git_changes(
796
changes, self.target.mapping,
797
specific_files=specific_files,
798
include_unchanged=include_unchanged,
799
target_extras=target_extras)
801
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
802
require_versioned=False, extra_trees=None,
803
want_unversioned=False):
804
raise NotImplementedError(self._iter_git_changes)
807
class InterGitRevisionTrees(InterGitTrees):
808
"""InterTree that works between two git revision trees."""
810
_matching_from_tree_format = None
811
_matching_to_tree_format = None
812
_test_mutable_trees_to_test_trees = None
815
def is_compatible(cls, source, target):
816
return (isinstance(source, GitRevisionTree) and
817
isinstance(target, GitRevisionTree))
819
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
820
require_versioned=True, extra_trees=None,
821
want_unversioned=False):
822
trees = [self.source]
823
if extra_trees is not None:
824
trees.extend(extra_trees)
825
if specific_files is not None:
826
specific_files = self.target.find_related_paths_across_trees(
827
specific_files, trees,
828
require_versioned=require_versioned)
830
if self.source._repository._git.object_store != self.target._repository._git.object_store:
831
store = OverlayObjectStore([self.source._repository._git.object_store,
832
self.target._repository._git.object_store])
834
store = self.source._repository._git.object_store
835
return self.source._repository._git.object_store.tree_changes(
836
self.source.tree, self.target.tree, want_unchanged=want_unchanged,
837
include_trees=True, change_type_same=True), set()
840
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
843
class MutableGitIndexTree(mutabletree.MutableTree):
846
self._lock_mode = None
848
self._versioned_dirs = None
849
self._index_dirty = False
851
def is_versioned(self, path):
852
with self.lock_read():
853
path = path.rstrip('/').encode('utf-8')
854
(index, subpath) = self._lookup_index(path)
855
return (subpath in index or self._has_dir(path))
857
def _has_dir(self, path):
858
if not isinstance(path, bytes):
859
raise TypeError(path)
862
if self._versioned_dirs is None:
864
return path in self._versioned_dirs
866
def _load_dirs(self):
867
if self._lock_mode is None:
868
raise errors.ObjectNotLocked(self)
869
self._versioned_dirs = set()
870
# TODO(jelmer): Browse over all indexes
871
for p, i in self._recurse_index_entries():
872
self._ensure_versioned_dir(posixpath.dirname(p))
874
def _ensure_versioned_dir(self, dirname):
875
if not isinstance(dirname, bytes):
876
raise TypeError(dirname)
877
if dirname in self._versioned_dirs:
880
self._ensure_versioned_dir(posixpath.dirname(dirname))
881
self._versioned_dirs.add(dirname)
883
def path2id(self, path):
884
with self.lock_read():
885
path = path.rstrip('/')
886
if self.is_versioned(path.rstrip('/')):
887
return self._fileid_map.lookup_file_id(osutils.safe_unicode(path))
890
def has_id(self, file_id):
892
self.id2path(file_id)
893
except errors.NoSuchId:
898
def id2path(self, file_id):
901
if type(file_id) is not bytes:
902
raise TypeError(file_id)
903
with self.lock_read():
905
path = self._fileid_map.lookup_path(file_id)
907
raise errors.NoSuchId(self, file_id)
908
if self.is_versioned(path):
910
raise errors.NoSuchId(self, file_id)
912
def _set_root_id(self, file_id):
913
self._fileid_map.set_file_id("", file_id)
915
def get_root_id(self):
916
return self.path2id(u"")
918
def _add(self, files, ids, kinds):
919
for (path, file_id, kind) in zip(files, ids, kinds):
920
if file_id is not None:
921
raise workingtree.SettingFileIdUnsupported()
922
path, can_access = osutils.normalized_filename(path)
924
raise errors.InvalidNormalization(path)
925
self._index_add_entry(path, kind)
927
def _read_submodule_head(self, path):
928
raise NotImplementedError(self._read_submodule_head)
930
def _lookup_index(self, encoded_path):
931
if not isinstance(encoded_path, bytes):
932
raise TypeError(encoded_path)
933
# TODO(jelmer): Look in other indexes
934
return self.index, encoded_path
936
def _index_del_entry(self, index, path):
938
# TODO(jelmer): Keep track of dirty per index
939
self._index_dirty = True
941
def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
942
if kind == "directory":
943
# Git indexes don't contain directories
948
file, stat_val = self.get_file_with_stat(path)
949
except (errors.NoSuchFile, IOError):
950
# TODO: Rather than come up with something here, use the old index
952
stat_val = os.stat_result(
953
(stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
955
blob.set_raw_string(file.read())
956
# Add object to the repository if it didn't exist yet
957
if not blob.id in self.store:
958
self.store.add_object(blob)
960
elif kind == "symlink":
963
stat_val = self._lstat(path)
964
except EnvironmentError:
965
# TODO: Rather than come up with something here, use the
967
stat_val = os.stat_result(
968
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
970
self.get_symlink_target(path).encode("utf-8"))
971
# Add object to the repository if it didn't exist yet
972
if not blob.id in self.store:
973
self.store.add_object(blob)
975
elif kind == "tree-reference":
976
if reference_revision is not None:
977
hexsha = self.branch.lookup_bzr_revision_id(reference_revision)[0]
979
hexsha = self._read_submodule_head(path)
981
raise errors.NoCommits(path)
983
stat_val = self._lstat(path)
984
except EnvironmentError:
985
stat_val = os.stat_result(
986
(S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
987
stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
989
raise AssertionError("unknown kind '%s'" % kind)
990
# Add an entry to the index or update the existing entry
991
ensure_normalized_path(path)
992
encoded_path = path.encode("utf-8")
993
if b'\r' in encoded_path or b'\n' in encoded_path:
994
# TODO(jelmer): Why do we need to do this?
995
trace.mutter('ignoring path with invalid newline in it: %r', path)
997
(index, index_path) = self._lookup_index(encoded_path)
998
index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
999
self._index_dirty = True
1000
if self._versioned_dirs is not None:
1001
self._ensure_versioned_dir(index_path)
1003
def _recurse_index_entries(self, index=None, basepath=b""):
1004
# Iterate over all index entries
1005
with self.lock_read():
1008
for path, value in index.items():
1009
yield (posixpath.join(basepath, path), value)
1010
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1011
if S_ISGITLINK(mode):
1012
pass # TODO(jelmer): dive into submodule
1015
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
1017
raise NotImplementedError(self.iter_entries_by_dir)
1018
with self.lock_read():
1019
if specific_files is not None:
1020
specific_files = set(specific_files)
1022
specific_files = None
1023
root_ie = self._get_dir_ie(u"", None)
1025
if specific_files is None or u"" in specific_files:
1026
ret[(u"", u"")] = root_ie
1027
dir_ids = {u"": root_ie.file_id}
1028
for path, value in self._recurse_index_entries():
1029
if self.mapping.is_special_file(path):
1031
path = path.decode("utf-8")
1032
if specific_files is not None and not path in specific_files:
1034
(parent, name) = posixpath.split(path)
1036
file_ie = self._get_file_ie(name, path, value, None)
1037
except errors.NoSuchFile:
1039
if yield_parents or specific_files is None:
1040
for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
1042
ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
1043
file_ie.parent_id = self.path2id(parent)
1044
ret[(posixpath.dirname(path), path)] = file_ie
1045
return ((path, ie) for ((_, path), ie) in sorted(viewitems(ret)))
1047
def iter_references(self):
1048
# TODO(jelmer): Implement a more efficient version of this
1049
for path, entry in self.iter_entries_by_dir():
1050
if entry.kind == 'tree-reference':
1051
yield path, self.mapping.generate_file_id(b'')
1053
def _get_dir_ie(self, path, parent_id):
1054
file_id = self.path2id(path)
1055
return GitTreeDirectory(file_id,
1056
posixpath.basename(path).strip("/"), parent_id)
1058
def _get_file_ie(self, name, path, value, parent_id):
1059
if not isinstance(name, text_type):
1060
raise TypeError(name)
1061
if not isinstance(path, text_type):
1062
raise TypeError(path)
1063
if not isinstance(value, tuple) or len(value) != 10:
1064
raise TypeError(value)
1065
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1066
file_id = self.path2id(path)
1067
if not isinstance(file_id, bytes):
1068
raise TypeError(file_id)
1069
kind = mode_kind(mode)
1070
ie = entry_factory[kind](file_id, name, parent_id)
1071
if kind == 'symlink':
1072
ie.symlink_target = self.get_symlink_target(path, file_id)
1073
elif kind == 'tree-reference':
1074
ie.reference_revision = self.get_reference_revision(path, file_id)
1077
data = self.get_file_text(path, file_id)
1078
except errors.NoSuchFile:
1080
except IOError as e:
1081
if e.errno != errno.ENOENT:
1085
data = self.branch.repository._git.object_store[sha].data
1086
ie.text_sha1 = osutils.sha_string(data)
1087
ie.text_size = len(data)
1088
ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1091
def _add_missing_parent_ids(self, path, dir_ids):
1094
parent = posixpath.dirname(path).strip("/")
1095
ret = self._add_missing_parent_ids(parent, dir_ids)
1096
parent_id = dir_ids[parent]
1097
ie = self._get_dir_ie(path, parent_id)
1098
dir_ids[path] = ie.file_id
1099
ret.append((path, ie))
1102
def _comparison_data(self, entry, path):
1104
return None, False, None
1105
return entry.kind, entry.executable, None
1107
def _unversion_path(self, path):
1108
if self._lock_mode is None:
1109
raise errors.ObjectNotLocked(self)
1110
encoded_path = path.encode("utf-8")
1112
(index, subpath) = self._lookup_index(encoded_path)
1114
self._index_del_entry(index, encoded_path)
1116
# A directory, perhaps?
1117
# TODO(jelmer): Deletes that involve submodules?
1118
for p in list(index):
1119
if p.startswith(subpath+b"/"):
1121
self._index_del_entry(index, p)
1124
self._versioned_dirs = None
1127
def unversion(self, paths, file_ids=None):
1128
with self.lock_tree_write():
1130
if self._unversion_path(path) == 0:
1131
raise errors.NoSuchFile(path)
1132
self._versioned_dirs = None
1138
def update_basis_by_delta(self, revid, delta):
1139
# TODO(jelmer): This shouldn't be called, it's inventory specific.
1140
for (old_path, new_path, file_id, ie) in delta:
1141
if old_path is not None:
1142
(index, old_subpath) = self._lookup_index(old_path.encode('utf-8'))
1143
if old_subpath in index:
1144
self._index_del_entry(index, old_subpath)
1145
self._versioned_dirs = None
1146
if new_path is not None and ie.kind != 'directory':
1147
self._index_add_entry(new_path, ie.kind)
1149
self._set_merges_from_parent_ids([])
1151
def move(self, from_paths, to_dir=None, after=None):
1153
with self.lock_tree_write():
1154
to_abs = self.abspath(to_dir)
1155
if not os.path.isdir(to_abs):
1156
raise errors.BzrMoveFailedError('', to_dir,
1157
errors.NotADirectory(to_abs))
1159
for from_rel in from_paths:
1160
from_tail = os.path.split(from_rel)[-1]
1161
to_rel = os.path.join(to_dir, from_tail)
1162
self.rename_one(from_rel, to_rel, after=after)
1163
rename_tuples.append((from_rel, to_rel))
1165
return rename_tuples
1167
def rename_one(self, from_rel, to_rel, after=None):
1168
from_path = from_rel.encode("utf-8")
1169
to_rel, can_access = osutils.normalized_filename(to_rel)
1171
raise errors.InvalidNormalization(to_rel)
1172
to_path = to_rel.encode("utf-8")
1173
with self.lock_tree_write():
1175
# Perhaps it's already moved?
1177
not self.has_filename(from_rel) and
1178
self.has_filename(to_rel) and
1179
not self.is_versioned(to_rel))
1181
if not self.has_filename(to_rel):
1182
raise errors.BzrMoveFailedError(from_rel, to_rel,
1183
errors.NoSuchFile(to_rel))
1184
if self.basis_tree().is_versioned(to_rel):
1185
raise errors.BzrMoveFailedError(from_rel, to_rel,
1186
errors.AlreadyVersionedError(to_rel))
1188
kind = self.kind(to_rel)
1191
to_kind = self.kind(to_rel)
1192
except errors.NoSuchFile:
1193
exc_type = errors.BzrRenameFailedError
1196
exc_type = errors.BzrMoveFailedError
1197
if self.is_versioned(to_rel):
1198
raise exc_type(from_rel, to_rel,
1199
errors.AlreadyVersionedError(to_rel))
1200
if not self.has_filename(from_rel):
1201
raise errors.BzrMoveFailedError(from_rel, to_rel,
1202
errors.NoSuchFile(from_rel))
1203
kind = self.kind(from_rel)
1204
if not self.is_versioned(from_rel) and kind != 'directory':
1205
raise exc_type(from_rel, to_rel,
1206
errors.NotVersionedError(from_rel))
1207
if self.has_filename(to_rel):
1208
raise errors.RenameFailedFilesExist(
1209
from_rel, to_rel, errors.FileExists(to_rel))
1211
kind = self.kind(from_rel)
1213
if not after and kind != 'directory':
1214
(index, from_subpath) = self._lookup_index(from_path)
1215
if from_subpath not in index:
1217
raise errors.BzrMoveFailedError(from_rel, to_rel,
1218
errors.NotVersionedError(path=from_rel))
1222
self._rename_one(from_rel, to_rel)
1223
except OSError as e:
1224
if e.errno == errno.ENOENT:
1225
raise errors.BzrMoveFailedError(from_rel, to_rel,
1226
errors.NoSuchFile(to_rel))
1228
if kind != 'directory':
1229
(index, from_index_path) = self._lookup_index(from_path)
1231
self._index_del_entry(index, from_path)
1234
self._index_add_entry(to_rel, kind)
1236
todo = [(p, i) for (p, i) in self._recurse_index_entries() if p.startswith(from_path+b'/')]
1237
for child_path, child_value in todo:
1238
(child_to_index, child_to_index_path) = self._lookup_index(
1239
posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
1240
child_to_index[child_to_index_path] = child_value
1241
# TODO(jelmer): Mark individual index as dirty
1242
self._index_dirty = True
1243
(child_from_index, child_from_index_path) = self._lookup_index(child_path)
1244
self._index_del_entry(child_from_index, child_from_index_path)
1246
self._versioned_dirs = None
1249
def find_related_paths_across_trees(self, paths, trees=[],
1250
require_versioned=True):
1254
if require_versioned:
1255
trees = [self] + (trees if trees is not None else [])
1259
if t.is_versioned(p):
1264
raise errors.PathsNotVersionedError(unversioned)
1266
return filter(self.is_versioned, paths)
1268
def path_content_summary(self, path):
1269
"""See Tree.path_content_summary."""
1271
stat_result = self._lstat(path)
1272
except OSError as e:
1273
if getattr(e, 'errno', None) == errno.ENOENT:
1275
return ('missing', None, None, None)
1276
# propagate other errors
1278
kind = mode_kind(stat_result.st_mode)
1280
return self._file_content_summary(path, stat_result)
1281
elif kind == 'directory':
1282
# perhaps it looks like a plain directory, but it's really a
1284
if self._directory_is_tree_reference(path):
1285
kind = 'tree-reference'
1286
return kind, None, None, None
1287
elif kind == 'symlink':
1288
target = osutils.readlink(self.abspath(path))
1289
return ('symlink', None, None, target)
1291
return (kind, None, None, None)
1293
def kind(self, relpath, file_id=None):
1294
kind = osutils.file_kind(self.abspath(relpath))
1295
if kind == 'directory':
1296
(index, index_path) = self._lookup_index(relpath.encode('utf-8'))
1300
mode = index[index_path].mode
1304
if S_ISGITLINK(mode):
1305
return 'tree-reference'
1310
def _live_entry(self, relpath):
1311
raise NotImplementedError(self._live_entry)
1314
class InterIndexGitTree(InterGitTrees):
1315
"""InterTree that works between a Git revision tree and an index."""
1317
def __init__(self, source, target):
1318
super(InterIndexGitTree, self).__init__(source, target)
1319
self._index = target.index
1322
def is_compatible(cls, source, target):
1323
return (isinstance(source, GitRevisionTree) and
1324
isinstance(target, MutableGitIndexTree))
1326
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1327
require_versioned=False, extra_trees=None,
1328
want_unversioned=False):
1329
trees = [self.source]
1330
if extra_trees is not None:
1331
trees.extend(extra_trees)
1332
if specific_files is not None:
1333
specific_files = self.target.find_related_paths_across_trees(
1334
specific_files, trees,
1335
require_versioned=require_versioned)
1336
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1337
with self.lock_read():
1338
return changes_between_git_tree_and_working_copy(
1339
self.source.store, self.source.tree,
1340
self.target, want_unchanged=want_unchanged,
1341
want_unversioned=want_unversioned)
1344
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
1347
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1348
want_unchanged=False, want_unversioned=False):
1349
"""Determine the changes between a git tree and a working tree with index.
1354
# Report dirified directories to commit_tree first, so that they can be
1355
# replaced with non-empty directories if they have contents.
1357
for path, index_entry in target._recurse_index_entries():
1359
live_entry = target._live_entry(path)
1360
except EnvironmentError as e:
1361
if e.errno == errno.ENOENT:
1362
# Entry was removed; keep it listed, but mark it as gone.
1363
blobs[path] = (ZERO_SHA, 0)
1364
elif e.errno == errno.EISDIR:
1365
# Entry was turned into a directory
1366
dirified.append((path, Tree().id, stat.S_IFDIR))
1367
store.add_object(Tree())
1371
blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1372
if want_unversioned:
1373
for e in target.extras():
1374
st = target._lstat(e)
1376
np, accessible = osutils.normalized_filename(e)
1377
except UnicodeDecodeError:
1378
raise errors.BadFilenameEncoding(
1380
if stat.S_ISDIR(st.st_mode):
1383
blob = blob_from_path_and_stat(target.abspath(e).encode(osutils._fs_enc), st)
1384
store.add_object(blob)
1385
np = np.encode('utf-8')
1386
blobs[np] = (blob.id, cleanup_mode(st.st_mode))
1388
to_tree_sha = commit_tree(store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
1389
return store.tree_changes(
1390
from_tree_sha, to_tree_sha, include_trees=True,
1391
want_unchanged=want_unchanged, change_type_same=True), extras