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 (
63
from .mapping import (
71
class GitTreeDirectory(_mod_tree.TreeDirectory):
73
__slots__ = ['file_id', 'name', 'parent_id', 'children']
75
def __init__(self, file_id, name, parent_id):
76
self.file_id = file_id
78
self.parent_id = parent_id
91
return self.__class__(
92
self.file_id, self.name, self.parent_id)
95
return "%s(file_id=%r, name=%r, parent_id=%r)" % (
96
self.__class__.__name__, self.file_id, self.name,
99
def __eq__(self, other):
100
return (self.kind == other.kind and
101
self.file_id == other.file_id and
102
self.name == other.name and
103
self.parent_id == other.parent_id)
106
class GitTreeFile(_mod_tree.TreeFile):
108
__slots__ = ['file_id', 'name', 'parent_id', 'text_size', 'text_sha1',
111
def __init__(self, file_id, name, parent_id, text_size=None,
112
text_sha1=None, executable=None):
113
self.file_id = file_id
115
self.parent_id = parent_id
116
self.text_size = text_size
117
self.text_sha1 = text_sha1
118
self.executable = executable
124
def __eq__(self, other):
125
return (self.kind == other.kind and
126
self.file_id == other.file_id and
127
self.name == other.name and
128
self.parent_id == other.parent_id and
129
self.text_sha1 == other.text_sha1 and
130
self.text_size == other.text_size and
131
self.executable == other.executable)
134
return "%s(file_id=%r, name=%r, parent_id=%r, text_size=%r, text_sha1=%r, executable=%r)" % (
135
type(self).__name__, self.file_id, self.name, self.parent_id,
136
self.text_size, self.text_sha1, self.executable)
139
ret = self.__class__(
140
self.file_id, self.name, self.parent_id)
141
ret.text_sha1 = self.text_sha1
142
ret.text_size = self.text_size
143
ret.executable = self.executable
147
class GitTreeSymlink(_mod_tree.TreeLink):
149
__slots__ = ['file_id', 'name', 'parent_id', 'symlink_target']
151
def __init__(self, file_id, name, parent_id,
152
symlink_target=None):
153
self.file_id = file_id
155
self.parent_id = parent_id
156
self.symlink_target = symlink_target
163
def executable(self):
171
return "%s(file_id=%r, name=%r, parent_id=%r, symlink_target=%r)" % (
172
type(self).__name__, self.file_id, self.name, self.parent_id,
175
def __eq__(self, other):
176
return (self.kind == other.kind and
177
self.file_id == other.file_id and
178
self.name == other.name and
179
self.parent_id == other.parent_id and
180
self.symlink_target == other.symlink_target)
183
return self.__class__(
184
self.file_id, self.name, self.parent_id,
188
class GitTreeSubmodule(_mod_tree.TreeLink):
190
__slots__ = ['file_id', 'name', 'parent_id', 'reference_revision']
192
def __init__(self, file_id, name, parent_id, reference_revision=None):
193
self.file_id = file_id
195
self.parent_id = parent_id
196
self.reference_revision = reference_revision
200
return 'tree-reference'
203
return "%s(file_id=%r, name=%r, parent_id=%r, reference_revision=%r)" % (
204
type(self).__name__, self.file_id, self.name, self.parent_id,
205
self.reference_revision)
207
def __eq__(self, other):
208
return (self.kind == other.kind and
209
self.file_id == other.file_id and
210
self.name == other.name and
211
self.parent_id == other.parent_id and
212
self.reference_revision == other.reference_revision)
215
return self.__class__(
216
self.file_id, self.name, self.parent_id,
217
self.reference_revision)
221
'directory': GitTreeDirectory,
223
'symlink': GitTreeSymlink,
224
'tree-reference': GitTreeSubmodule,
228
def ensure_normalized_path(path):
229
"""Check whether path is normalized.
231
:raises InvalidNormalization: When path is not normalized, and cannot be
232
accessed on this platform by the normalized path.
233
:return: The NFC normalised version of path.
235
norm_path, can_access = osutils.normalized_filename(path)
236
if norm_path != path:
240
raise errors.InvalidNormalization(path)
244
class GitRevisionTree(revisiontree.RevisionTree):
245
"""Revision tree implementation based on Git objects."""
247
def __init__(self, repository, revision_id):
248
self._revision_id = revision_id
249
self._repository = repository
250
self.store = repository._git.object_store
251
if not isinstance(revision_id, bytes):
252
raise TypeError(revision_id)
253
self.commit_id, self.mapping = repository.lookup_bzr_revision_id(revision_id)
254
if revision_id == NULL_REVISION:
256
self.mapping = default_mapping
257
self._fileid_map = GitFileIdMap(
262
commit = self.store[self.commit_id]
264
raise errors.NoSuchRevision(repository, revision_id)
265
self.tree = commit.tree
266
self._fileid_map = self.mapping.get_fileid_map(self.store.__getitem__, self.tree)
268
def _get_nested_repository(self, path):
269
nested_repo_transport = self._repository.user_transport.clone(path)
270
nested_controldir = _mod_controldir.ControlDir.open_from_transport(nested_repo_transport)
271
return nested_controldir.find_repository()
273
def supports_rename_tracking(self):
276
def get_file_revision(self, path, file_id=None):
277
change_scanner = self._repository._file_change_scanner
278
if self.commit_id == ZERO_SHA:
280
(path, commit_id) = change_scanner.find_last_change_revision(
281
path.encode('utf-8'), self.commit_id)
282
return self._repository.lookup_foreign_revision_id(commit_id, self.mapping)
284
def get_file_mtime(self, path, file_id=None):
286
revid = self.get_file_revision(path, file_id)
288
raise _mod_tree.FileTimestampUnavailable(path)
290
rev = self._repository.get_revision(revid)
291
except errors.NoSuchRevision:
292
raise _mod_tree.FileTimestampUnavailable(path)
295
def id2path(self, file_id):
297
path = self._fileid_map.lookup_path(file_id)
299
raise errors.NoSuchId(self, file_id)
300
path = path.decode('utf-8')
301
if self.is_versioned(path):
303
raise errors.NoSuchId(self, file_id)
305
def is_versioned(self, path):
306
return self.has_filename(path)
308
def path2id(self, path):
309
if self.mapping.is_special_file(path):
311
return self._fileid_map.lookup_file_id(path.encode('utf-8'))
313
def all_file_ids(self):
314
return set(self._fileid_map.all_file_ids())
316
def all_versioned_paths(self):
318
todo = set([(store, '', self.tree)])
320
(store, path, tree_id) = todo.pop()
323
tree = store[tree_id]
324
for name, mode, hexsha in tree.items():
325
subpath = posixpath.join(path, name)
326
if stat.S_ISDIR(mode):
327
todo.add((store, subpath, hexsha))
332
def get_root_id(self):
333
if self.tree is None:
335
return self.path2id("")
337
def has_or_had_id(self, file_id):
339
path = self.id2path(file_id)
340
except errors.NoSuchId:
344
def has_id(self, file_id):
346
path = self.id2path(file_id)
347
except errors.NoSuchId:
349
return self.has_filename(path)
351
def _lookup_path(self, path):
352
if self.tree is None:
353
raise errors.NoSuchFile(path)
355
(mode, hexsha) = tree_lookup_path(self.store.__getitem__, self.tree,
356
path.encode('utf-8'))
358
raise errors.NoSuchFile(self, path)
360
return (self.store, mode, hexsha)
362
def is_executable(self, path, file_id=None):
363
(store, mode, hexsha) = self._lookup_path(path)
365
# the tree root is a directory
367
return mode_is_executable(mode)
369
def kind(self, path, file_id=None):
370
(store, mode, hexsha) = self._lookup_path(path)
372
# the tree root is a directory
374
return mode_kind(mode)
376
def has_filename(self, path):
378
self._lookup_path(path)
379
except errors.NoSuchFile:
384
def list_files(self, include_root=False, from_dir=None, recursive=True):
385
if self.tree is None:
389
(store, mode, hexsha) = self._lookup_path(from_dir)
390
if mode is None: # Root
391
root_ie = self._get_dir_ie(b"", None)
393
parent_path = posixpath.dirname(from_dir.encode("utf-8"))
394
parent_id = self._fileid_map.lookup_file_id(parent_path)
395
if mode_kind(mode) == 'directory':
396
root_ie = self._get_dir_ie(from_dir.encode("utf-8"), parent_id)
398
root_ie = self._get_file_ie(store, from_dir.encode("utf-8"),
399
posixpath.basename(from_dir), mode, hexsha)
400
if from_dir != "" or include_root:
401
yield (from_dir, "V", root_ie.kind, root_ie.file_id, root_ie)
403
if root_ie.kind == 'directory':
404
todo.add((store, from_dir.encode("utf-8"), hexsha, root_ie.file_id))
406
(store, path, hexsha, parent_id) = todo.pop()
408
for name, mode, hexsha in tree.iteritems():
409
if self.mapping.is_special_file(name):
411
child_path = posixpath.join(path, name)
412
if stat.S_ISDIR(mode):
413
ie = self._get_dir_ie(child_path, parent_id)
415
todo.add((store, child_path, hexsha, ie.file_id))
417
ie = self._get_file_ie(store, child_path, name, mode, hexsha, parent_id)
418
yield child_path.decode('utf-8'), "V", ie.kind, ie.file_id, ie
420
def _get_file_ie(self, store, path, name, mode, hexsha, parent_id):
421
if type(path) is not bytes:
422
raise TypeError(path)
423
if type(name) is not bytes:
424
raise TypeError(name)
425
kind = mode_kind(mode)
426
file_id = self._fileid_map.lookup_file_id(path)
427
ie = entry_factory[kind](file_id, name.decode("utf-8"), parent_id)
428
if kind == 'symlink':
429
ie.symlink_target = store[hexsha].data.decode('utf-8')
430
elif kind == 'tree-reference':
431
ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(hexsha)
433
data = store[hexsha].data
434
ie.text_sha1 = osutils.sha_string(data)
435
ie.text_size = len(data)
436
ie.executable = mode_is_executable(mode)
439
def _get_dir_ie(self, path, parent_id):
440
file_id = self._fileid_map.lookup_file_id(path)
441
return GitTreeDirectory(file_id,
442
posixpath.basename(path).decode("utf-8"), parent_id)
444
def iter_child_entries(self, path, file_id=None):
445
(store, mode, tree_sha) = self._lookup_path(path)
447
if not stat.S_ISDIR(mode):
450
encoded_path = path.encode('utf-8')
451
file_id = self.path2id(path)
452
tree = store[tree_sha]
453
for name, mode, hexsha in tree.iteritems():
454
if self.mapping.is_special_file(name):
456
child_path = posixpath.join(encoded_path, name)
457
if stat.S_ISDIR(mode):
458
yield self._get_dir_ie(child_path, file_id)
460
yield self._get_file_ie(store, child_path, name, mode, hexsha,
463
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
464
if self.tree is None:
467
# TODO(jelmer): Support yield parents
468
raise NotImplementedError
469
if specific_files is not None:
470
if specific_files in ([""], []):
471
specific_files = None
473
specific_files = set([p.encode('utf-8') for p in specific_files])
474
todo = set([(self.store, "", self.tree, None)])
476
store, path, tree_sha, parent_id = todo.pop()
477
ie = self._get_dir_ie(path, parent_id)
478
if specific_files is None or path in specific_files:
479
yield path.decode("utf-8"), ie
480
tree = store[tree_sha]
481
for name, mode, hexsha in tree.iteritems():
482
if self.mapping.is_special_file(name):
484
child_path = posixpath.join(path, name)
485
if stat.S_ISDIR(mode):
486
if (specific_files is None or
487
any(filter(lambda p: p.startswith(child_path), specific_files))):
488
todo.add((store, child_path, hexsha, ie.file_id))
489
elif specific_files is None or child_path in specific_files:
490
yield (child_path.decode("utf-8"),
491
self._get_file_ie(store, child_path, name, mode, hexsha,
494
def get_revision_id(self):
495
"""See RevisionTree.get_revision_id."""
496
return self._revision_id
498
def get_file_sha1(self, path, file_id=None, stat_value=None):
499
if self.tree is None:
500
raise errors.NoSuchFile(path)
501
return osutils.sha_string(self.get_file_text(path, file_id))
503
def get_file_verifier(self, path, file_id=None, stat_value=None):
504
(store, mode, hexsha) = self._lookup_path(path)
505
return ("GIT", hexsha)
507
def get_file_text(self, path, file_id=None):
508
"""See RevisionTree.get_file_text."""
509
(store, mode, hexsha) = self._lookup_path(path)
510
if stat.S_ISREG(mode):
511
return store[hexsha].data
515
def get_symlink_target(self, path, file_id=None):
516
"""See RevisionTree.get_symlink_target."""
517
(store, mode, hexsha) = self._lookup_path(path)
518
if stat.S_ISLNK(mode):
519
return store[hexsha].data.decode('utf-8')
523
def get_reference_revision(self, path, file_id=None):
524
"""See RevisionTree.get_symlink_target."""
525
(store, mode, hexsha) = self._lookup_path(path)
526
if S_ISGITLINK(mode):
527
nested_repo = self._get_nested_repository(path)
528
return nested_repo.lookup_foreign_revision_id(hexsha)
532
def _comparison_data(self, entry, path):
534
return None, False, None
535
return entry.kind, entry.executable, None
537
def path_content_summary(self, path):
538
"""See Tree.path_content_summary."""
540
(store, mode, hexsha) = self._lookup_path(path)
541
except errors.NoSuchFile:
542
return ('missing', None, None, None)
543
kind = mode_kind(mode)
545
executable = mode_is_executable(mode)
546
contents = store[hexsha].data
547
return (kind, len(contents), executable, osutils.sha_string(contents))
548
elif kind == 'symlink':
549
return (kind, None, None, store[hexsha].data)
550
elif kind == 'tree-reference':
551
nested_repo = self._get_nested_repository(path)
552
return (kind, None, None,
553
nested_repo.lookup_foreign_revision_id(hexsha))
555
return (kind, None, None, None)
557
def find_related_paths_across_trees(self, paths, trees=[],
558
require_versioned=True):
561
if require_versioned:
562
trees = [self] + (trees if trees is not None else [])
566
if t.is_versioned(p):
571
raise errors.PathsNotVersionedError(unversioned)
572
return filter(self.is_versioned, paths)
574
def _iter_tree_contents(self, include_trees=False):
575
if self.tree is None:
577
return self.store.iter_tree_contents(
578
self.tree, include_trees=include_trees)
580
def annotate_iter(self, path, file_id=None,
581
default_revision=CURRENT_REVISION):
582
"""Return an iterator of revision_id, line tuples.
584
For working trees (and mutable trees in general), the special
585
revision_id 'current:' will be used for lines that are new in this
586
tree, e.g. uncommitted changes.
587
:param file_id: The file to produce an annotated version from
588
:param default_revision: For lines that don't match a basis, mark them
589
with this revision id. Not all implementations will make use of
592
with self.lock_read():
593
# Now we have the parents of this content
594
from breezy.annotate import Annotator
595
from .annotate import AnnotateProvider
596
annotator = Annotator(AnnotateProvider(
597
self._repository._file_change_scanner))
598
this_key = (path, self.get_file_revision(path))
599
annotations = [(key[-1], line)
600
for key, line in annotator.annotate_flat(this_key)]
604
def tree_delta_from_git_changes(changes, mapping,
605
fileid_maps, specific_files=None,
606
require_versioned=False, include_root=False,
608
"""Create a TreeDelta from two git trees.
610
source and target are iterators over tuples with:
611
(filename, sha, mode)
613
(old_fileid_map, new_fileid_map) = fileid_maps
614
if target_extras is None:
615
target_extras = set()
616
ret = delta.TreeDelta()
617
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
618
if newpath == u'' and not include_root:
620
if not (specific_files is None or
621
(oldpath is not None and osutils.is_inside_or_parent_of_any(specific_files, oldpath)) or
622
(newpath is not None and osutils.is_inside_or_parent_of_any(specific_files, newpath))):
624
if mapping.is_special_file(oldpath):
626
if mapping.is_special_file(newpath):
628
if oldpath is None and newpath is None:
631
if newpath in target_extras:
632
ret.unversioned.append(
633
(osutils.normalized_filename(newpath)[0], None, mode_kind(newmode)))
635
file_id = new_fileid_map.lookup_file_id(newpath)
636
ret.added.append((newpath.decode('utf-8'), file_id, mode_kind(newmode)))
637
elif newpath is None or newmode == 0:
638
file_id = old_fileid_map.lookup_file_id(oldpath)
639
ret.removed.append((oldpath.decode('utf-8'), file_id, mode_kind(oldmode)))
640
elif oldpath != newpath:
641
file_id = old_fileid_map.lookup_file_id(oldpath)
643
(oldpath.decode('utf-8'), newpath.decode('utf-8'), file_id,
644
mode_kind(newmode), (oldsha != newsha),
645
(oldmode != newmode)))
646
elif mode_kind(oldmode) != mode_kind(newmode):
647
file_id = new_fileid_map.lookup_file_id(newpath)
648
ret.kind_changed.append(
649
(newpath.decode('utf-8'), file_id, mode_kind(oldmode),
651
elif oldsha != newsha or oldmode != newmode:
652
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
654
file_id = new_fileid_map.lookup_file_id(newpath)
656
(newpath.decode('utf-8'), file_id, mode_kind(newmode),
657
(oldsha != newsha), (oldmode != newmode)))
659
file_id = new_fileid_map.lookup_file_id(newpath)
660
ret.unchanged.append((newpath.decode('utf-8'), file_id, mode_kind(newmode)))
665
def changes_from_git_changes(changes, mapping, specific_files=None, include_unchanged=False,
667
"""Create a iter_changes-like generator from a git stream.
669
source and target are iterators over tuples with:
670
(filename, sha, mode)
672
if target_extras is None:
673
target_extras = set()
674
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
675
if not (specific_files is None or
676
(oldpath is not None and osutils.is_inside_or_parent_of_any(specific_files, oldpath)) or
677
(newpath is not None and osutils.is_inside_or_parent_of_any(specific_files, newpath))):
679
path = (oldpath, newpath)
680
if oldpath is not None and mapping.is_special_file(oldpath):
682
if newpath is not None and mapping.is_special_file(newpath):
685
fileid = mapping.generate_file_id(newpath)
693
oldpath = oldpath.decode("utf-8")
695
oldexe = mode_is_executable(oldmode)
696
oldkind = mode_kind(oldmode)
704
(oldparentpath, oldname) = osutils.split(oldpath)
705
oldparent = mapping.generate_file_id(oldparentpath)
706
fileid = mapping.generate_file_id(oldpath)
714
newversioned = (newpath not in target_extras)
716
newexe = mode_is_executable(newmode)
717
newkind = mode_kind(newmode)
721
newpath = newpath.decode("utf-8")
726
newparentpath, newname = osutils.split(newpath)
727
newparent = mapping.generate_file_id(newparentpath)
728
if (not include_unchanged and
729
oldkind == 'directory' and newkind == 'directory' and
732
yield (fileid, (oldpath, newpath), (oldsha != newsha),
733
(oldversioned, newversioned),
734
(oldparent, newparent), (oldname, newname),
735
(oldkind, newkind), (oldexe, newexe))
738
class InterGitTrees(_mod_tree.InterTree):
739
"""InterTree that works between two git trees."""
741
_matching_from_tree_format = None
742
_matching_to_tree_format = None
743
_test_mutable_trees_to_test_trees = None
746
def is_compatible(cls, source, target):
747
return (isinstance(source, GitRevisionTree) and
748
isinstance(target, GitRevisionTree))
750
def compare(self, want_unchanged=False, specific_files=None,
751
extra_trees=None, require_versioned=False, include_root=False,
752
want_unversioned=False):
753
with self.lock_read():
754
changes, target_extras = self._iter_git_changes(
755
want_unchanged=want_unchanged,
756
require_versioned=require_versioned,
757
specific_files=specific_files,
758
extra_trees=extra_trees,
759
want_unversioned=want_unversioned)
760
source_fileid_map = self.source._fileid_map
761
target_fileid_map = self.target._fileid_map
762
return tree_delta_from_git_changes(changes, self.target.mapping,
763
(source_fileid_map, target_fileid_map),
764
specific_files=specific_files, include_root=include_root,
765
target_extras=target_extras)
767
def iter_changes(self, include_unchanged=False, specific_files=None,
768
pb=None, extra_trees=[], require_versioned=True,
769
want_unversioned=False):
770
with self.lock_read():
771
changes, target_extras = self._iter_git_changes(
772
want_unchanged=include_unchanged,
773
require_versioned=require_versioned,
774
specific_files=specific_files,
775
extra_trees=extra_trees,
776
want_unversioned=want_unversioned)
777
return changes_from_git_changes(
778
changes, self.target.mapping,
779
specific_files=specific_files,
780
include_unchanged=include_unchanged,
781
target_extras=target_extras)
783
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
784
require_versioned=False, extra_trees=None,
785
want_unversioned=False):
786
raise NotImplementedError(self._iter_git_changes)
789
class InterGitRevisionTrees(InterGitTrees):
790
"""InterTree that works between two git revision trees."""
792
_matching_from_tree_format = None
793
_matching_to_tree_format = None
794
_test_mutable_trees_to_test_trees = None
797
def is_compatible(cls, source, target):
798
return (isinstance(source, GitRevisionTree) and
799
isinstance(target, GitRevisionTree))
801
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
802
require_versioned=True, extra_trees=None,
803
want_unversioned=False):
804
trees = [self.source]
805
if extra_trees is not None:
806
trees.extend(extra_trees)
807
if specific_files is not None:
808
specific_files = self.target.find_related_paths_across_trees(
809
specific_files, trees,
810
require_versioned=require_versioned)
812
if self.source._repository._git.object_store != self.target._repository._git.object_store:
813
store = OverlayObjectStore([self.source._repository._git.object_store,
814
self.target._repository._git.object_store])
816
store = self.source._repository._git.object_store
817
return self.source._repository._git.object_store.tree_changes(
818
self.source.tree, self.target.tree, want_unchanged=want_unchanged,
819
include_trees=True, change_type_same=True), set()
822
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
825
class MutableGitIndexTree(mutabletree.MutableTree):
828
self._lock_mode = None
830
self._versioned_dirs = None
831
self._index_dirty = False
833
def is_versioned(self, path):
834
with self.lock_read():
835
path = path.rstrip('/').encode('utf-8')
836
(index, subpath) = self._lookup_index(path)
837
return (subpath in index or self._has_dir(path))
839
def _has_dir(self, path):
842
if self._versioned_dirs is None:
844
return path in self._versioned_dirs
846
def _load_dirs(self):
847
if self._lock_mode is None:
848
raise errors.ObjectNotLocked(self)
849
self._versioned_dirs = set()
850
# TODO(jelmer): Browse over all indexes
851
for p, i in self._recurse_index_entries():
852
self._ensure_versioned_dir(posixpath.dirname(p))
854
def _ensure_versioned_dir(self, dirname):
855
if dirname in self._versioned_dirs:
858
self._ensure_versioned_dir(posixpath.dirname(dirname))
859
self._versioned_dirs.add(dirname)
861
def path2id(self, path):
862
with self.lock_read():
863
path = path.rstrip('/')
864
if self.is_versioned(path.rstrip('/')):
865
return self._fileid_map.lookup_file_id(path.encode("utf-8"))
868
def has_id(self, file_id):
870
self.id2path(file_id)
871
except errors.NoSuchId:
876
def id2path(self, file_id):
879
if type(file_id) is not bytes:
880
raise TypeError(file_id)
881
with self.lock_read():
883
path = self._fileid_map.lookup_path(file_id)
885
raise errors.NoSuchId(self, file_id)
886
path = path.decode('utf-8')
887
if self.is_versioned(path):
889
raise errors.NoSuchId(self, file_id)
891
def _set_root_id(self, file_id):
892
self._fileid_map.set_file_id("", file_id)
894
def get_root_id(self):
895
return self.path2id("")
897
def _add(self, files, ids, kinds):
898
for (path, file_id, kind) in zip(files, ids, kinds):
899
if file_id is not None:
900
raise workingtree.SettingFileIdUnsupported()
901
path, can_access = osutils.normalized_filename(path)
903
raise errors.InvalidNormalization(path)
904
self._index_add_entry(path, kind)
906
def _read_submodule_head(self, path):
907
raise NotImplementedError(self._read_submodule_head)
909
def _lookup_index(self, encoded_path):
910
if not isinstance(encoded_path, bytes):
911
raise TypeError(encoded_path)
912
# TODO(jelmer): Look in other indexes
913
return self.index, encoded_path
915
def _index_del_entry(self, index, path):
917
# TODO(jelmer): Keep track of dirty per index
918
self._index_dirty = True
920
def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
921
if kind == "directory":
922
# Git indexes don't contain directories
927
file, stat_val = self.get_file_with_stat(path)
928
except (errors.NoSuchFile, IOError):
929
# TODO: Rather than come up with something here, use the old index
931
stat_val = os.stat_result(
932
(stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
933
blob.set_raw_string(file.read())
934
# Add object to the repository if it didn't exist yet
935
if not blob.id in self.store:
936
self.store.add_object(blob)
938
elif kind == "symlink":
941
stat_val = self._lstat(path)
942
except EnvironmentError:
943
# TODO: Rather than come up with something here, use the
945
stat_val = os.stat_result(
946
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
948
self.get_symlink_target(path).encode("utf-8"))
949
# Add object to the repository if it didn't exist yet
950
if not blob.id in self.store:
951
self.store.add_object(blob)
953
elif kind == "tree-reference":
954
if reference_revision is not None:
955
hexsha = self.branch.lookup_bzr_revision_id(reference_revision)[0]
957
hexsha = self._read_submodule_head(path)
959
raise errors.NoCommits(path)
961
stat_val = self._lstat(path)
962
except EnvironmentError:
963
stat_val = os.stat_result(
964
(S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
965
stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
967
raise AssertionError("unknown kind '%s'" % kind)
968
# Add an entry to the index or update the existing entry
969
ensure_normalized_path(path)
970
encoded_path = path.encode("utf-8")
971
if b'\r' in encoded_path or b'\n' in encoded_path:
972
# TODO(jelmer): Why do we need to do this?
973
trace.mutter('ignoring path with invalid newline in it: %r', path)
975
(index, index_path) = self._lookup_index(encoded_path)
976
index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
977
self._index_dirty = True
978
if self._versioned_dirs is not None:
979
self._ensure_versioned_dir(index_path)
981
def _recurse_index_entries(self, index=None, basepath=""):
982
# Iterate over all index entries
983
with self.lock_read():
986
for path, value in index.iteritems():
987
yield (posixpath.join(basepath, path), value)
988
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
989
if S_ISGITLINK(mode):
990
pass # TODO(jelmer): dive into submodule
993
def iter_entries_by_dir(self, specific_files=None, yield_parents=False):
995
raise NotImplementedError(self.iter_entries_by_dir)
996
with self.lock_read():
997
if specific_files is not None:
998
specific_files = set(specific_files)
1000
specific_files = None
1001
root_ie = self._get_dir_ie(u"", None)
1003
if specific_files is None or u"" in specific_files:
1004
ret[(None, u"")] = root_ie
1005
dir_ids = {u"": root_ie.file_id}
1006
for path, value in self._recurse_index_entries():
1007
if self.mapping.is_special_file(path):
1009
path = path.decode("utf-8")
1010
if specific_files is not None and not path in specific_files:
1012
(parent, name) = posixpath.split(path)
1014
file_ie = self._get_file_ie(name, path, value, None)
1015
except errors.NoSuchFile:
1017
if yield_parents or specific_files is None:
1018
for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
1020
ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
1021
file_ie.parent_id = self.path2id(parent)
1022
ret[(posixpath.dirname(path), path)] = file_ie
1023
return ((path, ie) for ((_, path), ie) in sorted(ret.items()))
1025
def iter_references(self):
1026
# TODO(jelmer): Implement a more efficient version of this
1027
for path, entry in self.iter_entries_by_dir():
1028
if entry.kind == 'tree-reference':
1029
yield path, self.mapping.generate_file_id(b'')
1031
def _get_dir_ie(self, path, parent_id):
1032
file_id = self.path2id(path)
1033
return GitTreeDirectory(file_id,
1034
posixpath.basename(path).strip("/"), parent_id)
1036
def _get_file_ie(self, name, path, value, parent_id):
1037
if type(name) is not unicode:
1038
raise TypeError(name)
1039
if type(path) is not unicode:
1040
raise TypeError(path)
1041
if not isinstance(value, tuple) or len(value) != 10:
1042
raise TypeError(value)
1043
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1044
file_id = self.path2id(path)
1045
if type(file_id) != str:
1046
raise AssertionError
1047
kind = mode_kind(mode)
1048
ie = entry_factory[kind](file_id, name, parent_id)
1049
if kind == 'symlink':
1050
ie.symlink_target = self.get_symlink_target(path, file_id)
1051
elif kind == 'tree-reference':
1052
ie.reference_revision = self.get_reference_revision(path, file_id)
1055
data = self.get_file_text(path, file_id)
1056
except errors.NoSuchFile:
1058
except IOError as e:
1059
if e.errno != errno.ENOENT:
1063
data = self.branch.repository._git.object_store[sha].data
1064
ie.text_sha1 = osutils.sha_string(data)
1065
ie.text_size = len(data)
1066
ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1069
def _add_missing_parent_ids(self, path, dir_ids):
1072
parent = posixpath.dirname(path).strip("/")
1073
ret = self._add_missing_parent_ids(parent, dir_ids)
1074
parent_id = dir_ids[parent]
1075
ie = self._get_dir_ie(path, parent_id)
1076
dir_ids[path] = ie.file_id
1077
ret.append((path, ie))
1080
def _comparison_data(self, entry, path):
1082
return None, False, None
1083
return entry.kind, entry.executable, None
1085
def _unversion_path(self, path):
1086
if self._lock_mode is None:
1087
raise errors.ObjectNotLocked(self)
1088
encoded_path = path.encode("utf-8")
1090
(index, subpath) = self._lookup_index(encoded_path)
1092
self._index_del_entry(index, encoded_path)
1094
# A directory, perhaps?
1095
# TODO(jelmer): Deletes that involve submodules?
1096
for p in list(index):
1097
if p.startswith(subpath+b"/"):
1099
self._index_del_entry(index, p)
1102
self._versioned_dirs = None
1105
def unversion(self, paths, file_ids=None):
1106
with self.lock_tree_write():
1108
if self._unversion_path(path) == 0:
1109
raise errors.NoSuchFile(path)
1110
self._versioned_dirs = None
1116
def update_basis_by_delta(self, revid, delta):
1117
# TODO(jelmer): This shouldn't be called, it's inventory specific.
1118
for (old_path, new_path, file_id, ie) in delta:
1119
if old_path is not None:
1120
(index, old_subpath) = self._lookup_index(old_path.encode('utf-8'))
1121
if old_subpath in index:
1122
self._index_del_entry(index, old_subpath)
1123
self._versioned_dirs = None
1124
if new_path is not None and ie.kind != 'directory':
1125
self._index_add_entry(new_path, ie.kind)
1127
self._set_merges_from_parent_ids([])
1129
def move(self, from_paths, to_dir=None, after=None):
1131
with self.lock_tree_write():
1132
to_abs = self.abspath(to_dir)
1133
if not os.path.isdir(to_abs):
1134
raise errors.BzrMoveFailedError('', to_dir,
1135
errors.NotADirectory(to_abs))
1137
for from_rel in from_paths:
1138
from_tail = os.path.split(from_rel)[-1]
1139
to_rel = os.path.join(to_dir, from_tail)
1140
self.rename_one(from_rel, to_rel, after=after)
1141
rename_tuples.append((from_rel, to_rel))
1143
return rename_tuples
1145
def rename_one(self, from_rel, to_rel, after=None):
1146
from_path = from_rel.encode("utf-8")
1147
to_rel, can_access = osutils.normalized_filename(to_rel)
1149
raise errors.InvalidNormalization(to_rel)
1150
to_path = to_rel.encode("utf-8")
1151
with self.lock_tree_write():
1153
# Perhaps it's already moved?
1155
not self.has_filename(from_rel) and
1156
self.has_filename(to_rel) and
1157
not self.is_versioned(to_rel))
1159
if not self.has_filename(to_rel):
1160
raise errors.BzrMoveFailedError(from_rel, to_rel,
1161
errors.NoSuchFile(to_rel))
1162
if self.basis_tree().is_versioned(to_rel):
1163
raise errors.BzrMoveFailedError(from_rel, to_rel,
1164
errors.AlreadyVersionedError(to_rel))
1166
kind = self.kind(to_rel)
1169
to_kind = self.kind(to_rel)
1170
except errors.NoSuchFile:
1171
exc_type = errors.BzrRenameFailedError
1174
exc_type = errors.BzrMoveFailedError
1175
if self.is_versioned(to_rel):
1176
raise exc_type(from_rel, to_rel,
1177
errors.AlreadyVersionedError(to_rel))
1178
if not self.has_filename(from_rel):
1179
raise errors.BzrMoveFailedError(from_rel, to_rel,
1180
errors.NoSuchFile(from_rel))
1181
kind = self.kind(from_rel)
1182
if not self.is_versioned(from_rel) and kind != 'directory':
1183
raise exc_type(from_rel, to_rel,
1184
errors.NotVersionedError(from_rel))
1185
if self.has_filename(to_rel):
1186
raise errors.RenameFailedFilesExist(
1187
from_rel, to_rel, errors.FileExists(to_rel))
1189
kind = self.kind(from_rel)
1191
if not after and kind != 'directory':
1192
(index, from_subpath) = self._lookup_index(from_path)
1193
if from_subpath not in index:
1195
raise errors.BzrMoveFailedError(from_rel, to_rel,
1196
errors.NotVersionedError(path=from_rel))
1200
self._rename_one(from_rel, to_rel)
1201
except OSError as e:
1202
if e.errno == errno.ENOENT:
1203
raise errors.BzrMoveFailedError(from_rel, to_rel,
1204
errors.NoSuchFile(to_rel))
1206
if kind != 'directory':
1207
(index, from_index_path) = self._lookup_index(from_path)
1209
self._index_del_entry(index, from_path)
1212
self._index_add_entry(to_rel, kind)
1214
todo = [(p, i) for (p, i) in self._recurse_index_entries() if p.startswith(from_path+'/')]
1215
for child_path, child_value in todo:
1216
(child_to_index, child_to_index_path) = self._lookup_index(
1217
posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
1218
child_to_index[child_to_index_path] = child_value
1219
# TODO(jelmer): Mark individual index as dirty
1220
self._index_dirty = True
1221
(child_from_index, child_from_index_path) = self._lookup_index(child_path)
1222
self._index_del_entry(child_from_index, child_from_index_path)
1224
self._versioned_dirs = None
1227
def find_related_paths_across_trees(self, paths, trees=[],
1228
require_versioned=True):
1232
if require_versioned:
1233
trees = [self] + (trees if trees is not None else [])
1237
if t.is_versioned(p):
1242
raise errors.PathsNotVersionedError(unversioned)
1244
return filter(self.is_versioned, paths)
1246
def path_content_summary(self, path):
1247
"""See Tree.path_content_summary."""
1249
stat_result = self._lstat(path)
1250
except OSError as e:
1251
if getattr(e, 'errno', None) == errno.ENOENT:
1253
return ('missing', None, None, None)
1254
# propagate other errors
1256
kind = mode_kind(stat_result.st_mode)
1258
return self._file_content_summary(path, stat_result)
1259
elif kind == 'directory':
1260
# perhaps it looks like a plain directory, but it's really a
1262
if self._directory_is_tree_reference(path):
1263
kind = 'tree-reference'
1264
return kind, None, None, None
1265
elif kind == 'symlink':
1266
target = osutils.readlink(self.abspath(path))
1267
return ('symlink', None, None, target)
1269
return (kind, None, None, None)
1271
def kind(self, relpath, file_id=None):
1272
kind = osutils.file_kind(self.abspath(relpath))
1273
if kind == 'directory':
1274
(index, index_path) = self._lookup_index(relpath.encode('utf-8'))
1276
mode = index[index_path].mode
1280
if S_ISGITLINK(mode):
1281
return 'tree-reference'
1286
def _live_entry(self, relpath):
1287
raise NotImplementedError(self._live_entry)
1290
class InterIndexGitTree(InterGitTrees):
1291
"""InterTree that works between a Git revision tree and an index."""
1293
def __init__(self, source, target):
1294
super(InterIndexGitTree, self).__init__(source, target)
1295
self._index = target.index
1298
def is_compatible(cls, source, target):
1299
return (isinstance(source, GitRevisionTree) and
1300
isinstance(target, MutableGitIndexTree))
1302
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1303
require_versioned=False, extra_trees=None,
1304
want_unversioned=False):
1305
trees = [self.source]
1306
if extra_trees is not None:
1307
trees.extend(extra_trees)
1308
if specific_files is not None:
1309
specific_files = self.target.find_related_paths_across_trees(
1310
specific_files, trees,
1311
require_versioned=require_versioned)
1312
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1313
with self.lock_read():
1314
return changes_between_git_tree_and_working_copy(
1315
self.source.store, self.source.tree,
1316
self.target, want_unchanged=want_unchanged,
1317
want_unversioned=want_unversioned)
1320
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
1323
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1324
want_unchanged=False, want_unversioned=False):
1325
"""Determine the changes between a git tree and a working tree with index.
1330
# Report dirified directories to commit_tree first, so that they can be
1331
# replaced with non-empty directories if they have contents.
1333
for path, index_entry in target._recurse_index_entries():
1335
live_entry = target._live_entry(path)
1336
except EnvironmentError as e:
1337
if e.errno == errno.ENOENT:
1338
# Entry was removed; keep it listed, but mark it as gone.
1339
blobs[path] = (ZERO_SHA, 0)
1340
elif e.errno == errno.EISDIR:
1341
# Entry was turned into a directory
1342
dirified.append((path, Tree().id, stat.S_IFDIR))
1343
store.add_object(Tree())
1347
blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1348
if want_unversioned:
1349
for e in target.extras():
1350
st = target._lstat(e)
1352
np, accessible = osutils.normalized_filename(e)
1353
except UnicodeDecodeError:
1354
raise errors.BadFilenameEncoding(
1356
if stat.S_ISDIR(st.st_mode):
1359
blob = blob_from_path_and_stat(target.abspath(e).encode(osutils._fs_enc), st)
1360
store.add_object(blob)
1361
np = np.encode('utf-8')
1362
blobs[np] = (blob.id, cleanup_mode(st.st_mode))
1364
to_tree_sha = commit_tree(store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
1365
return store.tree_changes(
1366
from_tree_sha, to_tree_sha, include_trees=True,
1367
want_unchanged=want_unchanged, change_type_same=True), extras