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 text_type
64
from .mapping import (
72
class GitTreeDirectory(_mod_tree.TreeDirectory):
74
__slots__ = ['file_id', 'name', 'parent_id', 'children']
76
def __init__(self, file_id, name, parent_id):
77
self.file_id = file_id
79
self.parent_id = parent_id
92
return self.__class__(
93
self.file_id, self.name, self.parent_id)
96
return "%s(file_id=%r, name=%r, parent_id=%r)" % (
97
self.__class__.__name__, self.file_id, self.name,
100
def __eq__(self, other):
101
return (self.kind == other.kind and
102
self.file_id == other.file_id and
103
self.name == other.name and
104
self.parent_id == other.parent_id)
107
class GitTreeFile(_mod_tree.TreeFile):
109
__slots__ = ['file_id', 'name', 'parent_id', 'text_size', 'text_sha1',
112
def __init__(self, file_id, name, parent_id, text_size=None,
113
text_sha1=None, executable=None):
114
self.file_id = file_id
116
self.parent_id = parent_id
117
self.text_size = text_size
118
self.text_sha1 = text_sha1
119
self.executable = executable
125
def __eq__(self, other):
126
return (self.kind == other.kind and
127
self.file_id == other.file_id and
128
self.name == other.name and
129
self.parent_id == other.parent_id and
130
self.text_sha1 == other.text_sha1 and
131
self.text_size == other.text_size and
132
self.executable == other.executable)
135
return "%s(file_id=%r, name=%r, parent_id=%r, text_size=%r, text_sha1=%r, executable=%r)" % (
136
type(self).__name__, self.file_id, self.name, self.parent_id,
137
self.text_size, self.text_sha1, self.executable)
140
ret = self.__class__(
141
self.file_id, self.name, self.parent_id)
142
ret.text_sha1 = self.text_sha1
143
ret.text_size = self.text_size
144
ret.executable = self.executable
148
class GitTreeSymlink(_mod_tree.TreeLink):
150
__slots__ = ['file_id', 'name', 'parent_id', 'symlink_target']
152
def __init__(self, file_id, name, parent_id,
153
symlink_target=None):
154
self.file_id = file_id
156
self.parent_id = parent_id
157
self.symlink_target = symlink_target
164
def executable(self):
172
return "%s(file_id=%r, name=%r, parent_id=%r, symlink_target=%r)" % (
173
type(self).__name__, self.file_id, self.name, self.parent_id,
176
def __eq__(self, other):
177
return (self.kind == other.kind and
178
self.file_id == other.file_id and
179
self.name == other.name and
180
self.parent_id == other.parent_id and
181
self.symlink_target == other.symlink_target)
184
return self.__class__(
185
self.file_id, self.name, self.parent_id,
189
class GitTreeSubmodule(_mod_tree.TreeLink):
191
__slots__ = ['file_id', 'name', 'parent_id', 'reference_revision']
193
def __init__(self, file_id, name, parent_id, reference_revision=None):
194
self.file_id = file_id
196
self.parent_id = parent_id
197
self.reference_revision = reference_revision
201
return 'tree-reference'
204
return "%s(file_id=%r, name=%r, parent_id=%r, reference_revision=%r)" % (
205
type(self).__name__, self.file_id, self.name, self.parent_id,
206
self.reference_revision)
208
def __eq__(self, other):
209
return (self.kind == other.kind and
210
self.file_id == other.file_id and
211
self.name == other.name and
212
self.parent_id == other.parent_id and
213
self.reference_revision == other.reference_revision)
216
return self.__class__(
217
self.file_id, self.name, self.parent_id,
218
self.reference_revision)
222
'directory': GitTreeDirectory,
224
'symlink': GitTreeSymlink,
225
'tree-reference': GitTreeSubmodule,
229
def ensure_normalized_path(path):
230
"""Check whether path is normalized.
232
:raises InvalidNormalization: When path is not normalized, and cannot be
233
accessed on this platform by the normalized path.
234
:return: The NFC normalised version of path.
236
norm_path, can_access = osutils.normalized_filename(path)
237
if norm_path != path:
241
raise errors.InvalidNormalization(path)
245
class GitRevisionTree(revisiontree.RevisionTree):
246
"""Revision tree implementation based on Git objects."""
248
def __init__(self, repository, revision_id):
249
self._revision_id = revision_id
250
self._repository = repository
251
self.store = repository._git.object_store
252
if not isinstance(revision_id, bytes):
253
raise TypeError(revision_id)
254
self.commit_id, self.mapping = repository.lookup_bzr_revision_id(revision_id)
255
if revision_id == NULL_REVISION:
257
self.mapping = default_mapping
258
self._fileid_map = GitFileIdMap(
263
commit = self.store[self.commit_id]
265
raise errors.NoSuchRevision(repository, revision_id)
266
self.tree = commit.tree
267
self._fileid_map = self.mapping.get_fileid_map(self.store.__getitem__, self.tree)
269
def _get_nested_repository(self, path):
270
nested_repo_transport = self._repository.user_transport.clone(path)
271
nested_controldir = _mod_controldir.ControlDir.open_from_transport(nested_repo_transport)
272
return nested_controldir.find_repository()
274
def supports_rename_tracking(self):
277
def get_file_revision(self, path, file_id=None):
278
change_scanner = self._repository._file_change_scanner
279
if self.commit_id == ZERO_SHA:
281
(path, commit_id) = change_scanner.find_last_change_revision(
282
path.encode('utf-8'), self.commit_id)
283
return self._repository.lookup_foreign_revision_id(commit_id, self.mapping)
285
def get_file_mtime(self, path, file_id=None):
287
revid = self.get_file_revision(path, file_id)
289
raise _mod_tree.FileTimestampUnavailable(path)
291
rev = self._repository.get_revision(revid)
292
except errors.NoSuchRevision:
293
raise _mod_tree.FileTimestampUnavailable(path)
296
def id2path(self, file_id):
298
path = self._fileid_map.lookup_path(file_id)
300
raise errors.NoSuchId(self, file_id)
301
path = path.decode('utf-8')
302
if self.is_versioned(path):
304
raise errors.NoSuchId(self, file_id)
306
def is_versioned(self, path):
307
return self.has_filename(path)
309
def path2id(self, path):
310
if self.mapping.is_special_file(path):
312
return self._fileid_map.lookup_file_id(path.encode('utf-8'))
314
def all_file_ids(self):
315
return set(self._fileid_map.all_file_ids())
317
def all_versioned_paths(self):
319
todo = {(self.store, '', self.tree)}
321
(store, path, tree_id) = todo.pop()
324
tree = store[tree_id]
325
for name, mode, hexsha in tree.items():
326
subpath = posixpath.join(path, name)
327
if stat.S_ISDIR(mode):
328
todo.add((store, subpath, hexsha))
333
def get_root_id(self):
334
if self.tree is None:
336
return self.path2id("")
338
def has_or_had_id(self, file_id):
340
path = self.id2path(file_id)
341
except errors.NoSuchId:
345
def has_id(self, file_id):
347
path = self.id2path(file_id)
348
except errors.NoSuchId:
350
return self.has_filename(path)
352
def _lookup_path(self, path):
353
if self.tree is None:
354
raise errors.NoSuchFile(path)
356
(mode, hexsha) = tree_lookup_path(self.store.__getitem__, self.tree,
357
path.encode('utf-8'))
359
raise errors.NoSuchFile(self, path)
361
return (self.store, mode, hexsha)
363
def is_executable(self, path, file_id=None):
364
(store, mode, hexsha) = self._lookup_path(path)
366
# the tree root is a directory
368
return mode_is_executable(mode)
370
def kind(self, path, file_id=None):
371
(store, mode, hexsha) = self._lookup_path(path)
373
# the tree root is a directory
375
return mode_kind(mode)
377
def has_filename(self, path):
379
self._lookup_path(path)
380
except errors.NoSuchFile:
385
def list_files(self, include_root=False, from_dir=None, recursive=True):
386
if self.tree is None:
390
(store, mode, hexsha) = self._lookup_path(from_dir)
391
if mode is None: # Root
392
root_ie = self._get_dir_ie(b"", None)
394
parent_path = posixpath.dirname(from_dir.encode("utf-8"))
395
parent_id = self._fileid_map.lookup_file_id(parent_path)
396
if mode_kind(mode) == 'directory':
397
root_ie = self._get_dir_ie(from_dir.encode("utf-8"), parent_id)
399
root_ie = self._get_file_ie(store, from_dir.encode("utf-8"),
400
posixpath.basename(from_dir), mode, hexsha)
401
if from_dir != "" or include_root:
402
yield (from_dir, "V", root_ie.kind, root_ie.file_id, root_ie)
404
if root_ie.kind == 'directory':
405
todo.add((store, from_dir.encode("utf-8"), hexsha, root_ie.file_id))
407
(store, path, hexsha, parent_id) = todo.pop()
409
for name, mode, hexsha in tree.iteritems():
410
if self.mapping.is_special_file(name):
412
child_path = posixpath.join(path, name)
413
if stat.S_ISDIR(mode):
414
ie = self._get_dir_ie(child_path, parent_id)
416
todo.add((store, child_path, hexsha, ie.file_id))
418
ie = self._get_file_ie(store, child_path, name, mode, hexsha, parent_id)
419
yield child_path.decode('utf-8'), "V", ie.kind, ie.file_id, ie
421
def _get_file_ie(self, store, path, name, mode, hexsha, parent_id):
422
if type(path) is not bytes:
423
raise TypeError(path)
424
if type(name) is not bytes:
425
raise TypeError(name)
426
kind = mode_kind(mode)
427
file_id = self._fileid_map.lookup_file_id(path)
428
ie = entry_factory[kind](file_id, name.decode("utf-8"), parent_id)
429
if kind == 'symlink':
430
ie.symlink_target = store[hexsha].data.decode('utf-8')
431
elif kind == 'tree-reference':
432
ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(hexsha)
434
data = store[hexsha].data
435
ie.text_sha1 = osutils.sha_string(data)
436
ie.text_size = len(data)
437
ie.executable = mode_is_executable(mode)
440
def _get_dir_ie(self, path, parent_id):
441
file_id = self._fileid_map.lookup_file_id(path)
442
return GitTreeDirectory(file_id,
443
posixpath.basename(path).decode("utf-8"), parent_id)
445
def iter_child_entries(self, path, file_id=None):
446
(store, mode, tree_sha) = self._lookup_path(path)
448
if not stat.S_ISDIR(mode):
451
encoded_path = path.encode('utf-8')
452
file_id = self.path2id(path)
453
tree = store[tree_sha]
454
for name, mode, hexsha in tree.iteritems():
455
if self.mapping.is_special_file(name):
457
child_path = posixpath.join(encoded_path, name)
458
if stat.S_ISDIR(mode):
459
yield self._get_dir_ie(child_path, file_id)
461
yield self._get_file_ie(store, child_path, name, mode, hexsha,
464
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
465
if self.tree is None:
468
# TODO(jelmer): Support yield parents
469
raise NotImplementedError
470
if specific_files is not None:
471
if specific_files in ([""], []):
472
specific_files = None
474
specific_files = set([p.encode('utf-8') for p in specific_files])
475
todo = set([(self.store, "", self.tree, None)])
477
store, path, tree_sha, parent_id = todo.pop()
478
ie = self._get_dir_ie(path, parent_id)
479
if specific_files is None or path in specific_files:
480
yield path.decode("utf-8"), ie
481
tree = store[tree_sha]
482
for name, mode, hexsha in tree.iteritems():
483
if self.mapping.is_special_file(name):
485
child_path = posixpath.join(path, name)
486
if stat.S_ISDIR(mode):
487
if (specific_files is None or
488
any(filter(lambda p: p.startswith(child_path), specific_files))):
489
todo.add((store, child_path, hexsha, ie.file_id))
490
elif specific_files is None or child_path in specific_files:
491
yield (child_path.decode("utf-8"),
492
self._get_file_ie(store, child_path, name, mode, hexsha,
495
def get_revision_id(self):
496
"""See RevisionTree.get_revision_id."""
497
return self._revision_id
499
def get_file_sha1(self, path, file_id=None, stat_value=None):
500
if self.tree is None:
501
raise errors.NoSuchFile(path)
502
return osutils.sha_string(self.get_file_text(path, file_id))
504
def get_file_verifier(self, path, file_id=None, stat_value=None):
505
(store, mode, hexsha) = self._lookup_path(path)
506
return ("GIT", hexsha)
508
def get_file_text(self, path, file_id=None):
509
"""See RevisionTree.get_file_text."""
510
(store, mode, hexsha) = self._lookup_path(path)
511
if stat.S_ISREG(mode):
512
return store[hexsha].data
516
def get_symlink_target(self, path, file_id=None):
517
"""See RevisionTree.get_symlink_target."""
518
(store, mode, hexsha) = self._lookup_path(path)
519
if stat.S_ISLNK(mode):
520
return store[hexsha].data.decode('utf-8')
524
def get_reference_revision(self, path, file_id=None):
525
"""See RevisionTree.get_symlink_target."""
526
(store, mode, hexsha) = self._lookup_path(path)
527
if S_ISGITLINK(mode):
528
nested_repo = self._get_nested_repository(path)
529
return nested_repo.lookup_foreign_revision_id(hexsha)
533
def _comparison_data(self, entry, path):
535
return None, False, None
536
return entry.kind, entry.executable, None
538
def path_content_summary(self, path):
539
"""See Tree.path_content_summary."""
541
(store, mode, hexsha) = self._lookup_path(path)
542
except errors.NoSuchFile:
543
return ('missing', None, None, None)
544
kind = mode_kind(mode)
546
executable = mode_is_executable(mode)
547
contents = store[hexsha].data
548
return (kind, len(contents), executable, osutils.sha_string(contents))
549
elif kind == 'symlink':
550
return (kind, None, None, store[hexsha].data)
551
elif kind == 'tree-reference':
552
nested_repo = self._get_nested_repository(path)
553
return (kind, None, None,
554
nested_repo.lookup_foreign_revision_id(hexsha))
556
return (kind, None, None, None)
558
def find_related_paths_across_trees(self, paths, trees=[],
559
require_versioned=True):
562
if require_versioned:
563
trees = [self] + (trees if trees is not None else [])
567
if t.is_versioned(p):
572
raise errors.PathsNotVersionedError(unversioned)
573
return filter(self.is_versioned, paths)
575
def _iter_tree_contents(self, include_trees=False):
576
if self.tree is None:
578
return self.store.iter_tree_contents(
579
self.tree, include_trees=include_trees)
581
def annotate_iter(self, path, file_id=None,
582
default_revision=CURRENT_REVISION):
583
"""Return an iterator of revision_id, line tuples.
585
For working trees (and mutable trees in general), the special
586
revision_id 'current:' will be used for lines that are new in this
587
tree, e.g. uncommitted changes.
588
:param file_id: The file to produce an annotated version from
589
:param default_revision: For lines that don't match a basis, mark them
590
with this revision id. Not all implementations will make use of
593
with self.lock_read():
594
# Now we have the parents of this content
595
from breezy.annotate import Annotator
596
from .annotate import AnnotateProvider
597
annotator = Annotator(AnnotateProvider(
598
self._repository._file_change_scanner))
599
this_key = (path, self.get_file_revision(path))
600
annotations = [(key[-1], line)
601
for key, line in annotator.annotate_flat(this_key)]
605
def tree_delta_from_git_changes(changes, mapping,
606
fileid_maps, specific_files=None,
607
require_versioned=False, include_root=False,
609
"""Create a TreeDelta from two git trees.
611
source and target are iterators over tuples with:
612
(filename, sha, mode)
614
(old_fileid_map, new_fileid_map) = fileid_maps
615
if target_extras is None:
616
target_extras = set()
617
ret = delta.TreeDelta()
618
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
619
if newpath == u'' and not include_root:
621
if not (specific_files is None or
622
(oldpath is not None and osutils.is_inside_or_parent_of_any(specific_files, oldpath)) or
623
(newpath is not None and osutils.is_inside_or_parent_of_any(specific_files, newpath))):
625
if mapping.is_special_file(oldpath):
627
if mapping.is_special_file(newpath):
629
if oldpath is None and newpath is None:
632
if newpath in target_extras:
633
ret.unversioned.append(
634
(osutils.normalized_filename(newpath)[0], None, mode_kind(newmode)))
636
file_id = new_fileid_map.lookup_file_id(newpath)
637
ret.added.append((newpath.decode('utf-8'), file_id, mode_kind(newmode)))
638
elif newpath is None or newmode == 0:
639
file_id = old_fileid_map.lookup_file_id(oldpath)
640
ret.removed.append((oldpath.decode('utf-8'), file_id, mode_kind(oldmode)))
641
elif oldpath != newpath:
642
file_id = old_fileid_map.lookup_file_id(oldpath)
644
(oldpath.decode('utf-8'), newpath.decode('utf-8'), file_id,
645
mode_kind(newmode), (oldsha != newsha),
646
(oldmode != newmode)))
647
elif mode_kind(oldmode) != mode_kind(newmode):
648
file_id = new_fileid_map.lookup_file_id(newpath)
649
ret.kind_changed.append(
650
(newpath.decode('utf-8'), file_id, mode_kind(oldmode),
652
elif oldsha != newsha or oldmode != newmode:
653
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
655
file_id = new_fileid_map.lookup_file_id(newpath)
657
(newpath.decode('utf-8'), file_id, mode_kind(newmode),
658
(oldsha != newsha), (oldmode != newmode)))
660
file_id = new_fileid_map.lookup_file_id(newpath)
661
ret.unchanged.append((newpath.decode('utf-8'), file_id, mode_kind(newmode)))
666
def changes_from_git_changes(changes, mapping, specific_files=None, include_unchanged=False,
668
"""Create a iter_changes-like generator from a git stream.
670
source and target are iterators over tuples with:
671
(filename, sha, mode)
673
if target_extras is None:
674
target_extras = set()
675
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
676
if not (specific_files is None or
677
(oldpath is not None and osutils.is_inside_or_parent_of_any(specific_files, oldpath)) or
678
(newpath is not None and osutils.is_inside_or_parent_of_any(specific_files, newpath))):
680
path = (oldpath, newpath)
681
if oldpath is not None and mapping.is_special_file(oldpath):
683
if newpath is not None and mapping.is_special_file(newpath):
686
fileid = mapping.generate_file_id(newpath)
694
oldpath = oldpath.decode("utf-8")
696
oldexe = mode_is_executable(oldmode)
697
oldkind = mode_kind(oldmode)
705
(oldparentpath, oldname) = osutils.split(oldpath)
706
oldparent = mapping.generate_file_id(oldparentpath)
707
fileid = mapping.generate_file_id(oldpath)
715
newversioned = (newpath not in target_extras)
717
newexe = mode_is_executable(newmode)
718
newkind = mode_kind(newmode)
722
newpath = newpath.decode("utf-8")
727
newparentpath, newname = osutils.split(newpath)
728
newparent = mapping.generate_file_id(newparentpath)
729
if (not include_unchanged and
730
oldkind == 'directory' and newkind == 'directory' and
733
yield (fileid, (oldpath, newpath), (oldsha != newsha),
734
(oldversioned, newversioned),
735
(oldparent, newparent), (oldname, newname),
736
(oldkind, newkind), (oldexe, newexe))
739
class InterGitTrees(_mod_tree.InterTree):
740
"""InterTree that works between two git trees."""
742
_matching_from_tree_format = None
743
_matching_to_tree_format = None
744
_test_mutable_trees_to_test_trees = None
747
def is_compatible(cls, source, target):
748
return (isinstance(source, GitRevisionTree) and
749
isinstance(target, GitRevisionTree))
751
def compare(self, want_unchanged=False, specific_files=None,
752
extra_trees=None, require_versioned=False, include_root=False,
753
want_unversioned=False):
754
with self.lock_read():
755
changes, target_extras = self._iter_git_changes(
756
want_unchanged=want_unchanged,
757
require_versioned=require_versioned,
758
specific_files=specific_files,
759
extra_trees=extra_trees,
760
want_unversioned=want_unversioned)
761
source_fileid_map = self.source._fileid_map
762
target_fileid_map = self.target._fileid_map
763
return tree_delta_from_git_changes(changes, self.target.mapping,
764
(source_fileid_map, target_fileid_map),
765
specific_files=specific_files, include_root=include_root,
766
target_extras=target_extras)
768
def iter_changes(self, include_unchanged=False, specific_files=None,
769
pb=None, extra_trees=[], require_versioned=True,
770
want_unversioned=False):
771
with self.lock_read():
772
changes, target_extras = self._iter_git_changes(
773
want_unchanged=include_unchanged,
774
require_versioned=require_versioned,
775
specific_files=specific_files,
776
extra_trees=extra_trees,
777
want_unversioned=want_unversioned)
778
return changes_from_git_changes(
779
changes, self.target.mapping,
780
specific_files=specific_files,
781
include_unchanged=include_unchanged,
782
target_extras=target_extras)
784
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
785
require_versioned=False, extra_trees=None,
786
want_unversioned=False):
787
raise NotImplementedError(self._iter_git_changes)
790
class InterGitRevisionTrees(InterGitTrees):
791
"""InterTree that works between two git revision trees."""
793
_matching_from_tree_format = None
794
_matching_to_tree_format = None
795
_test_mutable_trees_to_test_trees = None
798
def is_compatible(cls, source, target):
799
return (isinstance(source, GitRevisionTree) and
800
isinstance(target, GitRevisionTree))
802
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
803
require_versioned=True, extra_trees=None,
804
want_unversioned=False):
805
trees = [self.source]
806
if extra_trees is not None:
807
trees.extend(extra_trees)
808
if specific_files is not None:
809
specific_files = self.target.find_related_paths_across_trees(
810
specific_files, trees,
811
require_versioned=require_versioned)
813
if self.source._repository._git.object_store != self.target._repository._git.object_store:
814
store = OverlayObjectStore([self.source._repository._git.object_store,
815
self.target._repository._git.object_store])
817
store = self.source._repository._git.object_store
818
return self.source._repository._git.object_store.tree_changes(
819
self.source.tree, self.target.tree, want_unchanged=want_unchanged,
820
include_trees=True, change_type_same=True), set()
823
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
826
class MutableGitIndexTree(mutabletree.MutableTree):
829
self._lock_mode = None
831
self._versioned_dirs = None
832
self._index_dirty = False
834
def is_versioned(self, path):
835
with self.lock_read():
836
path = path.rstrip('/').encode('utf-8')
837
(index, subpath) = self._lookup_index(path)
838
return (subpath in index or self._has_dir(path))
840
def _has_dir(self, path):
843
if self._versioned_dirs is None:
845
return path in self._versioned_dirs
847
def _load_dirs(self):
848
if self._lock_mode is None:
849
raise errors.ObjectNotLocked(self)
850
self._versioned_dirs = set()
851
# TODO(jelmer): Browse over all indexes
852
for p, i in self._recurse_index_entries():
853
self._ensure_versioned_dir(posixpath.dirname(p))
855
def _ensure_versioned_dir(self, dirname):
856
if dirname in self._versioned_dirs:
859
self._ensure_versioned_dir(posixpath.dirname(dirname))
860
self._versioned_dirs.add(dirname)
862
def path2id(self, path):
863
with self.lock_read():
864
path = path.rstrip('/')
865
if self.is_versioned(path.rstrip('/')):
866
return self._fileid_map.lookup_file_id(path.encode("utf-8"))
869
def has_id(self, file_id):
871
self.id2path(file_id)
872
except errors.NoSuchId:
877
def id2path(self, file_id):
880
if type(file_id) is not bytes:
881
raise TypeError(file_id)
882
with self.lock_read():
884
path = self._fileid_map.lookup_path(file_id)
886
raise errors.NoSuchId(self, file_id)
887
path = path.decode('utf-8')
888
if self.is_versioned(path):
890
raise errors.NoSuchId(self, file_id)
892
def _set_root_id(self, file_id):
893
self._fileid_map.set_file_id("", file_id)
895
def get_root_id(self):
896
return self.path2id("")
898
def _add(self, files, ids, kinds):
899
for (path, file_id, kind) in zip(files, ids, kinds):
900
if file_id is not None:
901
raise workingtree.SettingFileIdUnsupported()
902
path, can_access = osutils.normalized_filename(path)
904
raise errors.InvalidNormalization(path)
905
self._index_add_entry(path, kind)
907
def _read_submodule_head(self, path):
908
raise NotImplementedError(self._read_submodule_head)
910
def _lookup_index(self, encoded_path):
911
if not isinstance(encoded_path, bytes):
912
raise TypeError(encoded_path)
913
# TODO(jelmer): Look in other indexes
914
return self.index, encoded_path
916
def _index_del_entry(self, index, path):
918
# TODO(jelmer): Keep track of dirty per index
919
self._index_dirty = True
921
def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
922
if kind == "directory":
923
# Git indexes don't contain directories
928
file, stat_val = self.get_file_with_stat(path)
929
except (errors.NoSuchFile, IOError):
930
# TODO: Rather than come up with something here, use the old index
932
stat_val = os.stat_result(
933
(stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
934
blob.set_raw_string(file.read())
935
# Add object to the repository if it didn't exist yet
936
if not blob.id in self.store:
937
self.store.add_object(blob)
939
elif kind == "symlink":
942
stat_val = self._lstat(path)
943
except EnvironmentError:
944
# TODO: Rather than come up with something here, use the
946
stat_val = os.stat_result(
947
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
949
self.get_symlink_target(path).encode("utf-8"))
950
# Add object to the repository if it didn't exist yet
951
if not blob.id in self.store:
952
self.store.add_object(blob)
954
elif kind == "tree-reference":
955
if reference_revision is not None:
956
hexsha = self.branch.lookup_bzr_revision_id(reference_revision)[0]
958
hexsha = self._read_submodule_head(path)
960
raise errors.NoCommits(path)
962
stat_val = self._lstat(path)
963
except EnvironmentError:
964
stat_val = os.stat_result(
965
(S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
966
stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
968
raise AssertionError("unknown kind '%s'" % kind)
969
# Add an entry to the index or update the existing entry
970
ensure_normalized_path(path)
971
encoded_path = path.encode("utf-8")
972
if b'\r' in encoded_path or b'\n' in encoded_path:
973
# TODO(jelmer): Why do we need to do this?
974
trace.mutter('ignoring path with invalid newline in it: %r', path)
976
(index, index_path) = self._lookup_index(encoded_path)
977
index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
978
self._index_dirty = True
979
if self._versioned_dirs is not None:
980
self._ensure_versioned_dir(index_path)
982
def _recurse_index_entries(self, index=None, basepath=""):
983
# Iterate over all index entries
984
with self.lock_read():
987
for path, value in index.iteritems():
988
yield (posixpath.join(basepath, path), value)
989
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
990
if S_ISGITLINK(mode):
991
pass # TODO(jelmer): dive into submodule
994
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
996
raise NotImplementedError(self.iter_entries_by_dir)
997
with self.lock_read():
998
if specific_files is not None:
999
specific_files = set(specific_files)
1001
specific_files = None
1002
root_ie = self._get_dir_ie(u"", None)
1004
if specific_files is None or u"" in specific_files:
1005
ret[(None, u"")] = root_ie
1006
dir_ids = {u"": root_ie.file_id}
1007
for path, value in self._recurse_index_entries():
1008
if self.mapping.is_special_file(path):
1010
path = path.decode("utf-8")
1011
if specific_files is not None and not path in specific_files:
1013
(parent, name) = posixpath.split(path)
1015
file_ie = self._get_file_ie(name, path, value, None)
1016
except errors.NoSuchFile:
1018
if yield_parents or specific_files is None:
1019
for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
1021
ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
1022
file_ie.parent_id = self.path2id(parent)
1023
ret[(posixpath.dirname(path), path)] = file_ie
1024
return ((path, ie) for ((_, path), ie) in sorted(ret.items()))
1026
def iter_references(self):
1027
# TODO(jelmer): Implement a more efficient version of this
1028
for path, entry in self.iter_entries_by_dir():
1029
if entry.kind == 'tree-reference':
1030
yield path, self.mapping.generate_file_id(b'')
1032
def _get_dir_ie(self, path, parent_id):
1033
file_id = self.path2id(path)
1034
return GitTreeDirectory(file_id,
1035
posixpath.basename(path).strip("/"), parent_id)
1037
def _get_file_ie(self, name, path, value, parent_id):
1038
if not isinstance(name, text_type):
1039
raise TypeError(name)
1040
if not isinstance(path, text_type):
1041
raise TypeError(path)
1042
if not isinstance(value, tuple) or len(value) != 10:
1043
raise TypeError(value)
1044
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1045
file_id = self.path2id(path)
1046
if type(file_id) != str:
1047
raise AssertionError
1048
kind = mode_kind(mode)
1049
ie = entry_factory[kind](file_id, name, parent_id)
1050
if kind == 'symlink':
1051
ie.symlink_target = self.get_symlink_target(path, file_id)
1052
elif kind == 'tree-reference':
1053
ie.reference_revision = self.get_reference_revision(path, file_id)
1056
data = self.get_file_text(path, file_id)
1057
except errors.NoSuchFile:
1059
except IOError as e:
1060
if e.errno != errno.ENOENT:
1064
data = self.branch.repository._git.object_store[sha].data
1065
ie.text_sha1 = osutils.sha_string(data)
1066
ie.text_size = len(data)
1067
ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1070
def _add_missing_parent_ids(self, path, dir_ids):
1073
parent = posixpath.dirname(path).strip("/")
1074
ret = self._add_missing_parent_ids(parent, dir_ids)
1075
parent_id = dir_ids[parent]
1076
ie = self._get_dir_ie(path, parent_id)
1077
dir_ids[path] = ie.file_id
1078
ret.append((path, ie))
1081
def _comparison_data(self, entry, path):
1083
return None, False, None
1084
return entry.kind, entry.executable, None
1086
def _unversion_path(self, path):
1087
if self._lock_mode is None:
1088
raise errors.ObjectNotLocked(self)
1089
encoded_path = path.encode("utf-8")
1091
(index, subpath) = self._lookup_index(encoded_path)
1093
self._index_del_entry(index, encoded_path)
1095
# A directory, perhaps?
1096
# TODO(jelmer): Deletes that involve submodules?
1097
for p in list(index):
1098
if p.startswith(subpath+b"/"):
1100
self._index_del_entry(index, p)
1103
self._versioned_dirs = None
1106
def unversion(self, paths, file_ids=None):
1107
with self.lock_tree_write():
1109
if self._unversion_path(path) == 0:
1110
raise errors.NoSuchFile(path)
1111
self._versioned_dirs = None
1117
def update_basis_by_delta(self, revid, delta):
1118
# TODO(jelmer): This shouldn't be called, it's inventory specific.
1119
for (old_path, new_path, file_id, ie) in delta:
1120
if old_path is not None:
1121
(index, old_subpath) = self._lookup_index(old_path.encode('utf-8'))
1122
if old_subpath in index:
1123
self._index_del_entry(index, old_subpath)
1124
self._versioned_dirs = None
1125
if new_path is not None and ie.kind != 'directory':
1126
self._index_add_entry(new_path, ie.kind)
1128
self._set_merges_from_parent_ids([])
1130
def move(self, from_paths, to_dir=None, after=None):
1132
with self.lock_tree_write():
1133
to_abs = self.abspath(to_dir)
1134
if not os.path.isdir(to_abs):
1135
raise errors.BzrMoveFailedError('', to_dir,
1136
errors.NotADirectory(to_abs))
1138
for from_rel in from_paths:
1139
from_tail = os.path.split(from_rel)[-1]
1140
to_rel = os.path.join(to_dir, from_tail)
1141
self.rename_one(from_rel, to_rel, after=after)
1142
rename_tuples.append((from_rel, to_rel))
1144
return rename_tuples
1146
def rename_one(self, from_rel, to_rel, after=None):
1147
from_path = from_rel.encode("utf-8")
1148
to_rel, can_access = osutils.normalized_filename(to_rel)
1150
raise errors.InvalidNormalization(to_rel)
1151
to_path = to_rel.encode("utf-8")
1152
with self.lock_tree_write():
1154
# Perhaps it's already moved?
1156
not self.has_filename(from_rel) and
1157
self.has_filename(to_rel) and
1158
not self.is_versioned(to_rel))
1160
if not self.has_filename(to_rel):
1161
raise errors.BzrMoveFailedError(from_rel, to_rel,
1162
errors.NoSuchFile(to_rel))
1163
if self.basis_tree().is_versioned(to_rel):
1164
raise errors.BzrMoveFailedError(from_rel, to_rel,
1165
errors.AlreadyVersionedError(to_rel))
1167
kind = self.kind(to_rel)
1170
to_kind = self.kind(to_rel)
1171
except errors.NoSuchFile:
1172
exc_type = errors.BzrRenameFailedError
1175
exc_type = errors.BzrMoveFailedError
1176
if self.is_versioned(to_rel):
1177
raise exc_type(from_rel, to_rel,
1178
errors.AlreadyVersionedError(to_rel))
1179
if not self.has_filename(from_rel):
1180
raise errors.BzrMoveFailedError(from_rel, to_rel,
1181
errors.NoSuchFile(from_rel))
1182
kind = self.kind(from_rel)
1183
if not self.is_versioned(from_rel) and kind != 'directory':
1184
raise exc_type(from_rel, to_rel,
1185
errors.NotVersionedError(from_rel))
1186
if self.has_filename(to_rel):
1187
raise errors.RenameFailedFilesExist(
1188
from_rel, to_rel, errors.FileExists(to_rel))
1190
kind = self.kind(from_rel)
1192
if not after and kind != 'directory':
1193
(index, from_subpath) = self._lookup_index(from_path)
1194
if from_subpath not in index:
1196
raise errors.BzrMoveFailedError(from_rel, to_rel,
1197
errors.NotVersionedError(path=from_rel))
1201
self._rename_one(from_rel, to_rel)
1202
except OSError as e:
1203
if e.errno == errno.ENOENT:
1204
raise errors.BzrMoveFailedError(from_rel, to_rel,
1205
errors.NoSuchFile(to_rel))
1207
if kind != 'directory':
1208
(index, from_index_path) = self._lookup_index(from_path)
1210
self._index_del_entry(index, from_path)
1213
self._index_add_entry(to_rel, kind)
1215
todo = [(p, i) for (p, i) in self._recurse_index_entries() if p.startswith(from_path+'/')]
1216
for child_path, child_value in todo:
1217
(child_to_index, child_to_index_path) = self._lookup_index(
1218
posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
1219
child_to_index[child_to_index_path] = child_value
1220
# TODO(jelmer): Mark individual index as dirty
1221
self._index_dirty = True
1222
(child_from_index, child_from_index_path) = self._lookup_index(child_path)
1223
self._index_del_entry(child_from_index, child_from_index_path)
1225
self._versioned_dirs = None
1228
def find_related_paths_across_trees(self, paths, trees=[],
1229
require_versioned=True):
1233
if require_versioned:
1234
trees = [self] + (trees if trees is not None else [])
1238
if t.is_versioned(p):
1243
raise errors.PathsNotVersionedError(unversioned)
1245
return filter(self.is_versioned, paths)
1247
def path_content_summary(self, path):
1248
"""See Tree.path_content_summary."""
1250
stat_result = self._lstat(path)
1251
except OSError as e:
1252
if getattr(e, 'errno', None) == errno.ENOENT:
1254
return ('missing', None, None, None)
1255
# propagate other errors
1257
kind = mode_kind(stat_result.st_mode)
1259
return self._file_content_summary(path, stat_result)
1260
elif kind == 'directory':
1261
# perhaps it looks like a plain directory, but it's really a
1263
if self._directory_is_tree_reference(path):
1264
kind = 'tree-reference'
1265
return kind, None, None, None
1266
elif kind == 'symlink':
1267
target = osutils.readlink(self.abspath(path))
1268
return ('symlink', None, None, target)
1270
return (kind, None, None, None)
1272
def kind(self, relpath, file_id=None):
1273
kind = osutils.file_kind(self.abspath(relpath))
1274
if kind == 'directory':
1275
(index, index_path) = self._lookup_index(relpath.encode('utf-8'))
1277
mode = index[index_path].mode
1281
if S_ISGITLINK(mode):
1282
return 'tree-reference'
1287
def _live_entry(self, relpath):
1288
raise NotImplementedError(self._live_entry)
1291
class InterIndexGitTree(InterGitTrees):
1292
"""InterTree that works between a Git revision tree and an index."""
1294
def __init__(self, source, target):
1295
super(InterIndexGitTree, self).__init__(source, target)
1296
self._index = target.index
1299
def is_compatible(cls, source, target):
1300
return (isinstance(source, GitRevisionTree) and
1301
isinstance(target, MutableGitIndexTree))
1303
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1304
require_versioned=False, extra_trees=None,
1305
want_unversioned=False):
1306
trees = [self.source]
1307
if extra_trees is not None:
1308
trees.extend(extra_trees)
1309
if specific_files is not None:
1310
specific_files = self.target.find_related_paths_across_trees(
1311
specific_files, trees,
1312
require_versioned=require_versioned)
1313
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1314
with self.lock_read():
1315
return changes_between_git_tree_and_working_copy(
1316
self.source.store, self.source.tree,
1317
self.target, want_unchanged=want_unchanged,
1318
want_unversioned=want_unversioned)
1321
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
1324
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1325
want_unchanged=False, want_unversioned=False):
1326
"""Determine the changes between a git tree and a working tree with index.
1331
# Report dirified directories to commit_tree first, so that they can be
1332
# replaced with non-empty directories if they have contents.
1334
for path, index_entry in target._recurse_index_entries():
1336
live_entry = target._live_entry(path)
1337
except EnvironmentError as e:
1338
if e.errno == errno.ENOENT:
1339
# Entry was removed; keep it listed, but mark it as gone.
1340
blobs[path] = (ZERO_SHA, 0)
1341
elif e.errno == errno.EISDIR:
1342
# Entry was turned into a directory
1343
dirified.append((path, Tree().id, stat.S_IFDIR))
1344
store.add_object(Tree())
1348
blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1349
if want_unversioned:
1350
for e in target.extras():
1351
st = target._lstat(e)
1353
np, accessible = osutils.normalized_filename(e)
1354
except UnicodeDecodeError:
1355
raise errors.BadFilenameEncoding(
1357
if stat.S_ISDIR(st.st_mode):
1360
blob = blob_from_path_and_stat(target.abspath(e).encode(osutils._fs_enc), st)
1361
store.add_object(blob)
1362
np = np.encode('utf-8')
1363
blobs[np] = (blob.id, cleanup_mode(st.st_mode))
1365
to_tree_sha = commit_tree(store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
1366
return store.tree_changes(
1367
from_tree_sha, to_tree_sha, include_trees=True,
1368
want_unchanged=want_unchanged, change_type_same=True), extras