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
(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
path = path.decode('utf-8')
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
return self._fileid_map.lookup_file_id(osutils.safe_unicode(path))
317
def all_file_ids(self):
318
return set(self._fileid_map.all_file_ids())
320
def all_versioned_paths(self):
322
todo = {(self.store, '', self.tree)}
324
(store, path, tree_id) = todo.pop()
327
tree = store[tree_id]
328
for name, mode, hexsha in tree.items():
329
subpath = posixpath.join(path, name)
330
if stat.S_ISDIR(mode):
331
todo.add((store, subpath, hexsha))
336
def get_root_id(self):
337
if self.tree is None:
339
return self.path2id("")
341
def has_or_had_id(self, file_id):
343
path = self.id2path(file_id)
344
except errors.NoSuchId:
348
def has_id(self, file_id):
350
path = self.id2path(file_id)
351
except errors.NoSuchId:
353
return self.has_filename(path)
355
def _lookup_path(self, path):
356
if self.tree is None:
357
raise errors.NoSuchFile(path)
359
(mode, hexsha) = tree_lookup_path(self.store.__getitem__, self.tree,
360
path.encode('utf-8'))
362
raise errors.NoSuchFile(self, path)
364
return (self.store, mode, hexsha)
366
def is_executable(self, path, file_id=None):
367
(store, mode, hexsha) = self._lookup_path(path)
369
# the tree root is a directory
371
return mode_is_executable(mode)
373
def kind(self, path, file_id=None):
374
(store, mode, hexsha) = self._lookup_path(path)
376
# the tree root is a directory
378
return mode_kind(mode)
380
def has_filename(self, path):
382
self._lookup_path(path)
383
except errors.NoSuchFile:
388
def list_files(self, include_root=False, from_dir=None, recursive=True):
389
if self.tree is None:
393
(store, mode, hexsha) = self._lookup_path(from_dir)
394
if mode is None: # Root
395
root_ie = self._get_dir_ie(b"", None)
397
parent_path = posixpath.dirname(from_dir.encode("utf-8"))
398
parent_id = self._fileid_map.lookup_file_id(parent_path)
399
if mode_kind(mode) == 'directory':
400
root_ie = self._get_dir_ie(from_dir.encode("utf-8"), parent_id)
402
root_ie = self._get_file_ie(store, from_dir.encode("utf-8"),
403
posixpath.basename(from_dir), mode, hexsha)
404
if from_dir != "" or include_root:
405
yield (from_dir, "V", root_ie.kind, root_ie.file_id, root_ie)
407
if root_ie.kind == 'directory':
408
todo.append((store, from_dir.encode("utf-8"), hexsha, root_ie.file_id))
410
(store, path, hexsha, parent_id) = todo.pop()
412
for name, mode, hexsha in tree.iteritems():
413
if self.mapping.is_special_file(name):
415
child_path = posixpath.join(path, name)
416
if stat.S_ISDIR(mode):
417
ie = self._get_dir_ie(child_path, parent_id)
419
todo.append((store, child_path, hexsha, ie.file_id))
421
ie = self._get_file_ie(store, child_path, name, mode, hexsha, parent_id)
422
yield child_path.decode('utf-8'), "V", ie.kind, ie.file_id, ie
424
def _get_file_ie(self, store, path, name, mode, hexsha, parent_id):
425
if not isinstance(path, bytes):
426
raise TypeError(path)
427
if not isinstance(name, bytes):
428
raise TypeError(name)
429
kind = mode_kind(mode)
430
path = path.decode('utf-8')
431
name = name.decode("utf-8")
432
file_id = self._fileid_map.lookup_file_id(path)
433
ie = entry_factory[kind](file_id, name, parent_id)
434
if kind == 'symlink':
435
ie.symlink_target = store[hexsha].data.decode('utf-8')
436
elif kind == 'tree-reference':
437
ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(hexsha)
439
data = store[hexsha].data
440
ie.text_sha1 = osutils.sha_string(data)
441
ie.text_size = len(data)
442
ie.executable = mode_is_executable(mode)
445
def _get_dir_ie(self, path, parent_id):
446
path = path.decode('utf-8')
447
file_id = self._fileid_map.lookup_file_id(path)
448
return GitTreeDirectory(file_id, posixpath.basename(path), parent_id)
450
def iter_child_entries(self, path, file_id=None):
451
(store, mode, tree_sha) = self._lookup_path(path)
453
if not stat.S_ISDIR(mode):
456
encoded_path = path.encode('utf-8')
457
file_id = self.path2id(path)
458
tree = store[tree_sha]
459
for name, mode, hexsha in tree.iteritems():
460
if self.mapping.is_special_file(name):
462
child_path = posixpath.join(encoded_path, name)
463
if stat.S_ISDIR(mode):
464
yield self._get_dir_ie(child_path, file_id)
466
yield self._get_file_ie(store, child_path, name, mode, hexsha,
469
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
470
if self.tree is None:
473
# TODO(jelmer): Support yield parents
474
raise NotImplementedError
475
if specific_files is not None:
476
if specific_files in ([""], []):
477
specific_files = None
479
specific_files = set([p.encode('utf-8') for p in specific_files])
480
todo = set([(self.store, "", self.tree, None)])
482
store, path, tree_sha, parent_id = todo.pop()
483
ie = self._get_dir_ie(path, parent_id)
484
if specific_files is None or path in specific_files:
485
yield path.decode("utf-8"), ie
486
tree = store[tree_sha]
487
for name, mode, hexsha in tree.iteritems():
488
if self.mapping.is_special_file(name):
490
child_path = posixpath.join(path, name)
491
if stat.S_ISDIR(mode):
492
if (specific_files is None or
493
any(filter(lambda p: p.startswith(child_path), specific_files))):
494
todo.add((store, child_path, hexsha, ie.file_id))
495
elif specific_files is None or child_path in specific_files:
496
yield (child_path.decode("utf-8"),
497
self._get_file_ie(store, child_path, name, mode, hexsha,
500
def get_revision_id(self):
501
"""See RevisionTree.get_revision_id."""
502
return self._revision_id
504
def get_file_sha1(self, path, file_id=None, stat_value=None):
505
if self.tree is None:
506
raise errors.NoSuchFile(path)
507
return osutils.sha_string(self.get_file_text(path, file_id))
509
def get_file_verifier(self, path, file_id=None, stat_value=None):
510
(store, mode, hexsha) = self._lookup_path(path)
511
return ("GIT", hexsha)
513
def get_file_text(self, path, file_id=None):
514
"""See RevisionTree.get_file_text."""
515
(store, mode, hexsha) = self._lookup_path(path)
516
if stat.S_ISREG(mode):
517
return store[hexsha].data
521
def get_symlink_target(self, path, file_id=None):
522
"""See RevisionTree.get_symlink_target."""
523
(store, mode, hexsha) = self._lookup_path(path)
524
if stat.S_ISLNK(mode):
525
return store[hexsha].data.decode('utf-8')
529
def get_reference_revision(self, path, file_id=None):
530
"""See RevisionTree.get_symlink_target."""
531
(store, mode, hexsha) = self._lookup_path(path)
532
if S_ISGITLINK(mode):
533
nested_repo = self._get_nested_repository(path)
534
return nested_repo.lookup_foreign_revision_id(hexsha)
538
def _comparison_data(self, entry, path):
540
return None, False, None
541
return entry.kind, entry.executable, None
543
def path_content_summary(self, path):
544
"""See Tree.path_content_summary."""
546
(store, mode, hexsha) = self._lookup_path(path)
547
except errors.NoSuchFile:
548
return ('missing', None, None, None)
549
kind = mode_kind(mode)
551
executable = mode_is_executable(mode)
552
contents = store[hexsha].data
553
return (kind, len(contents), executable, osutils.sha_string(contents))
554
elif kind == 'symlink':
555
return (kind, None, None, store[hexsha].data)
556
elif kind == 'tree-reference':
557
nested_repo = self._get_nested_repository(path)
558
return (kind, None, None,
559
nested_repo.lookup_foreign_revision_id(hexsha))
561
return (kind, None, None, None)
563
def find_related_paths_across_trees(self, paths, trees=[],
564
require_versioned=True):
567
if require_versioned:
568
trees = [self] + (trees if trees is not None else [])
572
if t.is_versioned(p):
577
raise errors.PathsNotVersionedError(unversioned)
578
return filter(self.is_versioned, paths)
580
def _iter_tree_contents(self, include_trees=False):
581
if self.tree is None:
583
return self.store.iter_tree_contents(
584
self.tree, include_trees=include_trees)
586
def annotate_iter(self, path, file_id=None,
587
default_revision=CURRENT_REVISION):
588
"""Return an iterator of revision_id, line tuples.
590
For working trees (and mutable trees in general), the special
591
revision_id 'current:' will be used for lines that are new in this
592
tree, e.g. uncommitted changes.
593
:param file_id: The file to produce an annotated version from
594
:param default_revision: For lines that don't match a basis, mark them
595
with this revision id. Not all implementations will make use of
598
with self.lock_read():
599
# Now we have the parents of this content
600
from breezy.annotate import Annotator
601
from .annotate import AnnotateProvider
602
annotator = Annotator(AnnotateProvider(
603
self._repository._file_change_scanner))
604
this_key = (path, self.get_file_revision(path))
605
annotations = [(key[-1], line)
606
for key, line in annotator.annotate_flat(this_key)]
610
def tree_delta_from_git_changes(changes, mapping,
611
fileid_maps, specific_files=None,
612
require_versioned=False, include_root=False,
614
"""Create a TreeDelta from two git trees.
616
source and target are iterators over tuples with:
617
(filename, sha, mode)
619
(old_fileid_map, new_fileid_map) = fileid_maps
620
if target_extras is None:
621
target_extras = set()
622
ret = delta.TreeDelta()
623
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
624
if newpath == b'' and not include_root:
626
if not (specific_files is None or
627
(oldpath is not None and osutils.is_inside_or_parent_of_any(specific_files, oldpath)) or
628
(newpath is not None and osutils.is_inside_or_parent_of_any(specific_files, newpath))):
630
if mapping.is_special_file(oldpath):
632
if mapping.is_special_file(newpath):
634
if oldpath is None and newpath is None:
637
if newpath in target_extras:
638
ret.unversioned.append(
639
(osutils.normalized_filename(newpath)[0], None, mode_kind(newmode)))
641
newpath_decoded = newpath.decode('utf-8')
642
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
643
ret.added.append((newpath_decoded, file_id, mode_kind(newmode)))
644
elif newpath is None or newmode == 0:
645
oldpath_decoded = oldpath.decode('utf-8')
646
file_id = old_fileid_map.lookup_file_id(oldpath_decoded)
647
ret.removed.append((oldpath_decoded, file_id, mode_kind(oldmode)))
648
elif oldpath != newpath:
649
oldpath_decoded = oldpath.decode('utf-8')
650
file_id = old_fileid_map.lookup_file_id(oldpath_decoded)
652
(oldpath_decoded, newpath.decode('utf-8'), file_id,
653
mode_kind(newmode), (oldsha != newsha),
654
(oldmode != newmode)))
655
elif mode_kind(oldmode) != mode_kind(newmode):
656
newpath_decoded = newpath.decode('utf-8')
657
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
658
ret.kind_changed.append(
659
(newpath_decoded, file_id, mode_kind(oldmode),
661
elif oldsha != newsha or oldmode != newmode:
662
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
664
newpath_decoded = newpath.decode('utf-8')
665
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
667
(newpath, file_id, mode_kind(newmode),
668
(oldsha != newsha), (oldmode != newmode)))
670
newpath_decoded = newpath.decode('utf-8')
671
file_id = new_fileid_map.lookup_file_id(newpath_decoded)
672
ret.unchanged.append((newpath, file_id, mode_kind(newmode)))
677
def changes_from_git_changes(changes, mapping, specific_files=None, include_unchanged=False,
679
"""Create a iter_changes-like generator from a git stream.
681
source and target are iterators over tuples with:
682
(filename, sha, mode)
684
if target_extras is None:
685
target_extras = set()
686
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
687
if not (specific_files is None or
688
(oldpath is not None and osutils.is_inside_or_parent_of_any(specific_files, oldpath)) or
689
(newpath is not None and osutils.is_inside_or_parent_of_any(specific_files, newpath))):
691
path = (oldpath, newpath)
692
if oldpath is not None and mapping.is_special_file(oldpath):
694
if newpath is not None and mapping.is_special_file(newpath):
697
fileid = mapping.generate_file_id(newpath)
705
oldpath = oldpath.decode("utf-8")
707
oldexe = mode_is_executable(oldmode)
708
oldkind = mode_kind(oldmode)
716
(oldparentpath, oldname) = osutils.split(oldpath)
717
oldparent = mapping.generate_file_id(oldparentpath)
718
fileid = mapping.generate_file_id(oldpath)
726
newversioned = (newpath not in target_extras)
728
newexe = mode_is_executable(newmode)
729
newkind = mode_kind(newmode)
733
newpath = newpath.decode("utf-8")
738
newparentpath, newname = osutils.split(newpath)
739
newparent = mapping.generate_file_id(newparentpath)
740
if (not include_unchanged and
741
oldkind == 'directory' and newkind == 'directory' and
744
yield (fileid, (oldpath, newpath), (oldsha != newsha),
745
(oldversioned, newversioned),
746
(oldparent, newparent), (oldname, newname),
747
(oldkind, newkind), (oldexe, newexe))
750
class InterGitTrees(_mod_tree.InterTree):
751
"""InterTree that works between two git trees."""
753
_matching_from_tree_format = None
754
_matching_to_tree_format = None
755
_test_mutable_trees_to_test_trees = None
758
def is_compatible(cls, source, target):
759
return (isinstance(source, GitRevisionTree) and
760
isinstance(target, GitRevisionTree))
762
def compare(self, want_unchanged=False, specific_files=None,
763
extra_trees=None, require_versioned=False, include_root=False,
764
want_unversioned=False):
765
with self.lock_read():
766
changes, target_extras = self._iter_git_changes(
767
want_unchanged=want_unchanged,
768
require_versioned=require_versioned,
769
specific_files=specific_files,
770
extra_trees=extra_trees,
771
want_unversioned=want_unversioned)
772
source_fileid_map = self.source._fileid_map
773
target_fileid_map = self.target._fileid_map
774
return tree_delta_from_git_changes(changes, self.target.mapping,
775
(source_fileid_map, target_fileid_map),
776
specific_files=specific_files, include_root=include_root,
777
target_extras=target_extras)
779
def iter_changes(self, include_unchanged=False, specific_files=None,
780
pb=None, extra_trees=[], require_versioned=True,
781
want_unversioned=False):
782
with self.lock_read():
783
changes, target_extras = self._iter_git_changes(
784
want_unchanged=include_unchanged,
785
require_versioned=require_versioned,
786
specific_files=specific_files,
787
extra_trees=extra_trees,
788
want_unversioned=want_unversioned)
789
return changes_from_git_changes(
790
changes, self.target.mapping,
791
specific_files=specific_files,
792
include_unchanged=include_unchanged,
793
target_extras=target_extras)
795
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
796
require_versioned=False, extra_trees=None,
797
want_unversioned=False):
798
raise NotImplementedError(self._iter_git_changes)
801
class InterGitRevisionTrees(InterGitTrees):
802
"""InterTree that works between two git revision trees."""
804
_matching_from_tree_format = None
805
_matching_to_tree_format = None
806
_test_mutable_trees_to_test_trees = None
809
def is_compatible(cls, source, target):
810
return (isinstance(source, GitRevisionTree) and
811
isinstance(target, GitRevisionTree))
813
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
814
require_versioned=True, extra_trees=None,
815
want_unversioned=False):
816
trees = [self.source]
817
if extra_trees is not None:
818
trees.extend(extra_trees)
819
if specific_files is not None:
820
specific_files = self.target.find_related_paths_across_trees(
821
specific_files, trees,
822
require_versioned=require_versioned)
824
if self.source._repository._git.object_store != self.target._repository._git.object_store:
825
store = OverlayObjectStore([self.source._repository._git.object_store,
826
self.target._repository._git.object_store])
828
store = self.source._repository._git.object_store
829
return self.source._repository._git.object_store.tree_changes(
830
self.source.tree, self.target.tree, want_unchanged=want_unchanged,
831
include_trees=True, change_type_same=True), set()
834
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
837
class MutableGitIndexTree(mutabletree.MutableTree):
840
self._lock_mode = None
842
self._versioned_dirs = None
843
self._index_dirty = False
845
def is_versioned(self, path):
846
with self.lock_read():
847
path = path.rstrip('/').encode('utf-8')
848
(index, subpath) = self._lookup_index(path)
849
return (subpath in index or self._has_dir(path))
851
def _has_dir(self, path):
852
if not isinstance(path, bytes):
853
raise TypeError(path)
856
if self._versioned_dirs is None:
858
return path in self._versioned_dirs
860
def _load_dirs(self):
861
if self._lock_mode is None:
862
raise errors.ObjectNotLocked(self)
863
self._versioned_dirs = set()
864
# TODO(jelmer): Browse over all indexes
865
for p, i in self._recurse_index_entries():
866
self._ensure_versioned_dir(posixpath.dirname(p))
868
def _ensure_versioned_dir(self, dirname):
869
if not isinstance(dirname, bytes):
870
raise TypeError(dirname)
871
if dirname in self._versioned_dirs:
874
self._ensure_versioned_dir(posixpath.dirname(dirname))
875
self._versioned_dirs.add(dirname)
877
def path2id(self, path):
878
with self.lock_read():
879
path = path.rstrip('/')
880
if self.is_versioned(path.rstrip('/')):
881
return self._fileid_map.lookup_file_id(osutils.safe_unicode(path))
884
def has_id(self, file_id):
886
self.id2path(file_id)
887
except errors.NoSuchId:
892
def id2path(self, file_id):
895
if type(file_id) is not bytes:
896
raise TypeError(file_id)
897
with self.lock_read():
899
path = self._fileid_map.lookup_path(file_id)
901
raise errors.NoSuchId(self, file_id)
902
path = path.decode('utf-8')
903
if self.is_versioned(path):
905
raise errors.NoSuchId(self, file_id)
907
def _set_root_id(self, file_id):
908
self._fileid_map.set_file_id("", file_id)
910
def get_root_id(self):
911
return self.path2id("")
913
def _add(self, files, ids, kinds):
914
for (path, file_id, kind) in zip(files, ids, kinds):
915
if file_id is not None:
916
raise workingtree.SettingFileIdUnsupported()
917
path, can_access = osutils.normalized_filename(path)
919
raise errors.InvalidNormalization(path)
920
self._index_add_entry(path, kind)
922
def _read_submodule_head(self, path):
923
raise NotImplementedError(self._read_submodule_head)
925
def _lookup_index(self, encoded_path):
926
if not isinstance(encoded_path, bytes):
927
raise TypeError(encoded_path)
928
# TODO(jelmer): Look in other indexes
929
return self.index, encoded_path
931
def _index_del_entry(self, index, path):
933
# TODO(jelmer): Keep track of dirty per index
934
self._index_dirty = True
936
def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
937
if kind == "directory":
938
# Git indexes don't contain directories
943
file, stat_val = self.get_file_with_stat(path)
944
except (errors.NoSuchFile, IOError):
945
# TODO: Rather than come up with something here, use the old index
947
stat_val = os.stat_result(
948
(stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
949
blob.set_raw_string(file.read())
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 == "symlink":
957
stat_val = self._lstat(path)
958
except EnvironmentError:
959
# TODO: Rather than come up with something here, use the
961
stat_val = os.stat_result(
962
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
964
self.get_symlink_target(path).encode("utf-8"))
965
# Add object to the repository if it didn't exist yet
966
if not blob.id in self.store:
967
self.store.add_object(blob)
969
elif kind == "tree-reference":
970
if reference_revision is not None:
971
hexsha = self.branch.lookup_bzr_revision_id(reference_revision)[0]
973
hexsha = self._read_submodule_head(path)
975
raise errors.NoCommits(path)
977
stat_val = self._lstat(path)
978
except EnvironmentError:
979
stat_val = os.stat_result(
980
(S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
981
stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
983
raise AssertionError("unknown kind '%s'" % kind)
984
# Add an entry to the index or update the existing entry
985
ensure_normalized_path(path)
986
encoded_path = path.encode("utf-8")
987
if b'\r' in encoded_path or b'\n' in encoded_path:
988
# TODO(jelmer): Why do we need to do this?
989
trace.mutter('ignoring path with invalid newline in it: %r', path)
991
(index, index_path) = self._lookup_index(encoded_path)
992
index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
993
self._index_dirty = True
994
if self._versioned_dirs is not None:
995
self._ensure_versioned_dir(index_path)
997
def _recurse_index_entries(self, index=None, basepath=b""):
998
# Iterate over all index entries
999
with self.lock_read():
1002
for path, value in index.items():
1003
yield (posixpath.join(basepath, path), value)
1004
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1005
if S_ISGITLINK(mode):
1006
pass # TODO(jelmer): dive into submodule
1009
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
1011
raise NotImplementedError(self.iter_entries_by_dir)
1012
with self.lock_read():
1013
if specific_files is not None:
1014
specific_files = set(specific_files)
1016
specific_files = None
1017
root_ie = self._get_dir_ie(u"", None)
1019
if specific_files is None or u"" in specific_files:
1020
ret[(None, u"")] = root_ie
1021
dir_ids = {u"": root_ie.file_id}
1022
for path, value in self._recurse_index_entries():
1023
if self.mapping.is_special_file(path):
1025
path = path.decode("utf-8")
1026
if specific_files is not None and not path in specific_files:
1028
(parent, name) = posixpath.split(path)
1030
file_ie = self._get_file_ie(name, path, value, None)
1031
except errors.NoSuchFile:
1033
if yield_parents or specific_files is None:
1034
for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
1036
ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
1037
file_ie.parent_id = self.path2id(parent)
1038
ret[(posixpath.dirname(path), path)] = file_ie
1039
return ((path, ie) for ((_, path), ie) in sorted(ret.items()))
1041
def iter_references(self):
1042
# TODO(jelmer): Implement a more efficient version of this
1043
for path, entry in self.iter_entries_by_dir():
1044
if entry.kind == 'tree-reference':
1045
yield path, self.mapping.generate_file_id(b'')
1047
def _get_dir_ie(self, path, parent_id):
1048
file_id = self.path2id(path)
1049
return GitTreeDirectory(file_id,
1050
posixpath.basename(path).strip("/"), parent_id)
1052
def _get_file_ie(self, name, path, value, parent_id):
1053
if not isinstance(name, text_type):
1054
raise TypeError(name)
1055
if not isinstance(path, text_type):
1056
raise TypeError(path)
1057
if not isinstance(value, tuple) or len(value) != 10:
1058
raise TypeError(value)
1059
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1060
file_id = self.path2id(path)
1061
if not isinstance(file_id, bytes):
1062
raise TypeError(file_id)
1063
kind = mode_kind(mode)
1064
ie = entry_factory[kind](file_id, name, parent_id)
1065
if kind == 'symlink':
1066
ie.symlink_target = self.get_symlink_target(path, file_id)
1067
elif kind == 'tree-reference':
1068
ie.reference_revision = self.get_reference_revision(path, file_id)
1071
data = self.get_file_text(path, file_id)
1072
except errors.NoSuchFile:
1074
except IOError as e:
1075
if e.errno != errno.ENOENT:
1079
data = self.branch.repository._git.object_store[sha].data
1080
ie.text_sha1 = osutils.sha_string(data)
1081
ie.text_size = len(data)
1082
ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1085
def _add_missing_parent_ids(self, path, dir_ids):
1088
parent = posixpath.dirname(path).strip("/")
1089
ret = self._add_missing_parent_ids(parent, dir_ids)
1090
parent_id = dir_ids[parent]
1091
ie = self._get_dir_ie(path, parent_id)
1092
dir_ids[path] = ie.file_id
1093
ret.append((path, ie))
1096
def _comparison_data(self, entry, path):
1098
return None, False, None
1099
return entry.kind, entry.executable, None
1101
def _unversion_path(self, path):
1102
if self._lock_mode is None:
1103
raise errors.ObjectNotLocked(self)
1104
encoded_path = path.encode("utf-8")
1106
(index, subpath) = self._lookup_index(encoded_path)
1108
self._index_del_entry(index, encoded_path)
1110
# A directory, perhaps?
1111
# TODO(jelmer): Deletes that involve submodules?
1112
for p in list(index):
1113
if p.startswith(subpath+b"/"):
1115
self._index_del_entry(index, p)
1118
self._versioned_dirs = None
1121
def unversion(self, paths, file_ids=None):
1122
with self.lock_tree_write():
1124
if self._unversion_path(path) == 0:
1125
raise errors.NoSuchFile(path)
1126
self._versioned_dirs = None
1132
def update_basis_by_delta(self, revid, delta):
1133
# TODO(jelmer): This shouldn't be called, it's inventory specific.
1134
for (old_path, new_path, file_id, ie) in delta:
1135
if old_path is not None:
1136
(index, old_subpath) = self._lookup_index(old_path.encode('utf-8'))
1137
if old_subpath in index:
1138
self._index_del_entry(index, old_subpath)
1139
self._versioned_dirs = None
1140
if new_path is not None and ie.kind != 'directory':
1141
self._index_add_entry(new_path, ie.kind)
1143
self._set_merges_from_parent_ids([])
1145
def move(self, from_paths, to_dir=None, after=None):
1147
with self.lock_tree_write():
1148
to_abs = self.abspath(to_dir)
1149
if not os.path.isdir(to_abs):
1150
raise errors.BzrMoveFailedError('', to_dir,
1151
errors.NotADirectory(to_abs))
1153
for from_rel in from_paths:
1154
from_tail = os.path.split(from_rel)[-1]
1155
to_rel = os.path.join(to_dir, from_tail)
1156
self.rename_one(from_rel, to_rel, after=after)
1157
rename_tuples.append((from_rel, to_rel))
1159
return rename_tuples
1161
def rename_one(self, from_rel, to_rel, after=None):
1162
from_path = from_rel.encode("utf-8")
1163
to_rel, can_access = osutils.normalized_filename(to_rel)
1165
raise errors.InvalidNormalization(to_rel)
1166
to_path = to_rel.encode("utf-8")
1167
with self.lock_tree_write():
1169
# Perhaps it's already moved?
1171
not self.has_filename(from_rel) and
1172
self.has_filename(to_rel) and
1173
not self.is_versioned(to_rel))
1175
if not self.has_filename(to_rel):
1176
raise errors.BzrMoveFailedError(from_rel, to_rel,
1177
errors.NoSuchFile(to_rel))
1178
if self.basis_tree().is_versioned(to_rel):
1179
raise errors.BzrMoveFailedError(from_rel, to_rel,
1180
errors.AlreadyVersionedError(to_rel))
1182
kind = self.kind(to_rel)
1185
to_kind = self.kind(to_rel)
1186
except errors.NoSuchFile:
1187
exc_type = errors.BzrRenameFailedError
1190
exc_type = errors.BzrMoveFailedError
1191
if self.is_versioned(to_rel):
1192
raise exc_type(from_rel, to_rel,
1193
errors.AlreadyVersionedError(to_rel))
1194
if not self.has_filename(from_rel):
1195
raise errors.BzrMoveFailedError(from_rel, to_rel,
1196
errors.NoSuchFile(from_rel))
1197
kind = self.kind(from_rel)
1198
if not self.is_versioned(from_rel) and kind != 'directory':
1199
raise exc_type(from_rel, to_rel,
1200
errors.NotVersionedError(from_rel))
1201
if self.has_filename(to_rel):
1202
raise errors.RenameFailedFilesExist(
1203
from_rel, to_rel, errors.FileExists(to_rel))
1205
kind = self.kind(from_rel)
1207
if not after and kind != 'directory':
1208
(index, from_subpath) = self._lookup_index(from_path)
1209
if from_subpath not in index:
1211
raise errors.BzrMoveFailedError(from_rel, to_rel,
1212
errors.NotVersionedError(path=from_rel))
1216
self._rename_one(from_rel, to_rel)
1217
except OSError as e:
1218
if e.errno == errno.ENOENT:
1219
raise errors.BzrMoveFailedError(from_rel, to_rel,
1220
errors.NoSuchFile(to_rel))
1222
if kind != 'directory':
1223
(index, from_index_path) = self._lookup_index(from_path)
1225
self._index_del_entry(index, from_path)
1228
self._index_add_entry(to_rel, kind)
1230
todo = [(p, i) for (p, i) in self._recurse_index_entries() if p.startswith(from_path+'/')]
1231
for child_path, child_value in todo:
1232
(child_to_index, child_to_index_path) = self._lookup_index(
1233
posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
1234
child_to_index[child_to_index_path] = child_value
1235
# TODO(jelmer): Mark individual index as dirty
1236
self._index_dirty = True
1237
(child_from_index, child_from_index_path) = self._lookup_index(child_path)
1238
self._index_del_entry(child_from_index, child_from_index_path)
1240
self._versioned_dirs = None
1243
def find_related_paths_across_trees(self, paths, trees=[],
1244
require_versioned=True):
1248
if require_versioned:
1249
trees = [self] + (trees if trees is not None else [])
1253
if t.is_versioned(p):
1258
raise errors.PathsNotVersionedError(unversioned)
1260
return filter(self.is_versioned, paths)
1262
def path_content_summary(self, path):
1263
"""See Tree.path_content_summary."""
1265
stat_result = self._lstat(path)
1266
except OSError as e:
1267
if getattr(e, 'errno', None) == errno.ENOENT:
1269
return ('missing', None, None, None)
1270
# propagate other errors
1272
kind = mode_kind(stat_result.st_mode)
1274
return self._file_content_summary(path, stat_result)
1275
elif kind == 'directory':
1276
# perhaps it looks like a plain directory, but it's really a
1278
if self._directory_is_tree_reference(path):
1279
kind = 'tree-reference'
1280
return kind, None, None, None
1281
elif kind == 'symlink':
1282
target = osutils.readlink(self.abspath(path))
1283
return ('symlink', None, None, target)
1285
return (kind, None, None, None)
1287
def kind(self, relpath, file_id=None):
1288
kind = osutils.file_kind(self.abspath(relpath))
1289
if kind == 'directory':
1290
(index, index_path) = self._lookup_index(relpath.encode('utf-8'))
1292
mode = index[index_path].mode
1296
if S_ISGITLINK(mode):
1297
return 'tree-reference'
1302
def _live_entry(self, relpath):
1303
raise NotImplementedError(self._live_entry)
1306
class InterIndexGitTree(InterGitTrees):
1307
"""InterTree that works between a Git revision tree and an index."""
1309
def __init__(self, source, target):
1310
super(InterIndexGitTree, self).__init__(source, target)
1311
self._index = target.index
1314
def is_compatible(cls, source, target):
1315
return (isinstance(source, GitRevisionTree) and
1316
isinstance(target, MutableGitIndexTree))
1318
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1319
require_versioned=False, extra_trees=None,
1320
want_unversioned=False):
1321
trees = [self.source]
1322
if extra_trees is not None:
1323
trees.extend(extra_trees)
1324
if specific_files is not None:
1325
specific_files = self.target.find_related_paths_across_trees(
1326
specific_files, trees,
1327
require_versioned=require_versioned)
1328
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1329
with self.lock_read():
1330
return changes_between_git_tree_and_working_copy(
1331
self.source.store, self.source.tree,
1332
self.target, want_unchanged=want_unchanged,
1333
want_unversioned=want_unversioned)
1336
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
1339
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1340
want_unchanged=False, want_unversioned=False):
1341
"""Determine the changes between a git tree and a working tree with index.
1346
# Report dirified directories to commit_tree first, so that they can be
1347
# replaced with non-empty directories if they have contents.
1349
for path, index_entry in target._recurse_index_entries():
1351
live_entry = target._live_entry(path)
1352
except EnvironmentError as e:
1353
if e.errno == errno.ENOENT:
1354
# Entry was removed; keep it listed, but mark it as gone.
1355
blobs[path] = (ZERO_SHA, 0)
1356
elif e.errno == errno.EISDIR:
1357
# Entry was turned into a directory
1358
dirified.append((path, Tree().id, stat.S_IFDIR))
1359
store.add_object(Tree())
1363
blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1364
if want_unversioned:
1365
for e in target.extras():
1366
st = target._lstat(e)
1368
np, accessible = osutils.normalized_filename(e)
1369
except UnicodeDecodeError:
1370
raise errors.BadFilenameEncoding(
1372
if stat.S_ISDIR(st.st_mode):
1375
blob = blob_from_path_and_stat(target.abspath(e).encode(osutils._fs_enc), st)
1376
store.add_object(blob)
1377
np = np.encode('utf-8')
1378
blobs[np] = (blob.id, cleanup_mode(st.st_mode))
1380
to_tree_sha = commit_tree(store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
1381
return store.tree_changes(
1382
from_tree_sha, to_tree_sha, include_trees=True,
1383
want_unchanged=want_unchanged, change_type_same=True), extras