1
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
from __future__ import absolute_import
22
from collections import deque
24
from io import BytesIO
27
from dulwich.config import (
29
ConfigFile as GitConfigFile,
31
from dulwich.diff_tree import tree_changes
32
from dulwich.errors import NotTreeError
33
from dulwich.index import (
34
blob_from_path_and_stat,
37
index_entry_from_stat,
40
from dulwich.object_store import (
44
from dulwich.objects import (
55
controldir as _mod_controldir,
65
from ..revision import (
69
from ..sixish import (
74
from .mapping import (
79
from .transportgit import (
85
class GitTreeDirectory(_mod_tree.TreeDirectory):
87
__slots__ = ['file_id', 'name', 'parent_id', 'children']
89
def __init__(self, file_id, name, parent_id):
90
self.file_id = file_id
92
self.parent_id = parent_id
101
def executable(self):
105
return self.__class__(
106
self.file_id, self.name, self.parent_id)
109
return "%s(file_id=%r, name=%r, parent_id=%r)" % (
110
self.__class__.__name__, self.file_id, self.name,
113
def __eq__(self, other):
114
return (self.kind == other.kind and
115
self.file_id == other.file_id and
116
self.name == other.name and
117
self.parent_id == other.parent_id)
120
class GitTreeFile(_mod_tree.TreeFile):
122
__slots__ = ['file_id', 'name', 'parent_id', 'text_size', 'text_sha1',
125
def __init__(self, file_id, name, parent_id, text_size=None,
126
text_sha1=None, executable=None):
127
self.file_id = file_id
129
self.parent_id = parent_id
130
self.text_size = text_size
131
self.text_sha1 = text_sha1
132
self.executable = executable
138
def __eq__(self, other):
139
return (self.kind == other.kind and
140
self.file_id == other.file_id and
141
self.name == other.name and
142
self.parent_id == other.parent_id and
143
self.text_sha1 == other.text_sha1 and
144
self.text_size == other.text_size and
145
self.executable == other.executable)
148
return ("%s(file_id=%r, name=%r, parent_id=%r, text_size=%r, "
149
"text_sha1=%r, executable=%r)") % (
150
type(self).__name__, self.file_id, self.name, self.parent_id,
151
self.text_size, self.text_sha1, self.executable)
154
ret = self.__class__(
155
self.file_id, self.name, self.parent_id)
156
ret.text_sha1 = self.text_sha1
157
ret.text_size = self.text_size
158
ret.executable = self.executable
162
class GitTreeSymlink(_mod_tree.TreeLink):
164
__slots__ = ['file_id', 'name', 'parent_id', 'symlink_target']
166
def __init__(self, file_id, name, parent_id,
167
symlink_target=None):
168
self.file_id = file_id
170
self.parent_id = parent_id
171
self.symlink_target = symlink_target
178
def executable(self):
186
return "%s(file_id=%r, name=%r, parent_id=%r, symlink_target=%r)" % (
187
type(self).__name__, self.file_id, self.name, self.parent_id,
190
def __eq__(self, other):
191
return (self.kind == other.kind and
192
self.file_id == other.file_id and
193
self.name == other.name and
194
self.parent_id == other.parent_id and
195
self.symlink_target == other.symlink_target)
198
return self.__class__(
199
self.file_id, self.name, self.parent_id,
203
class GitTreeSubmodule(_mod_tree.TreeReference):
205
__slots__ = ['file_id', 'name', 'parent_id', 'reference_revision']
207
def __init__(self, file_id, name, parent_id, reference_revision=None):
208
self.file_id = file_id
210
self.parent_id = parent_id
211
self.reference_revision = reference_revision
215
return 'tree-reference'
218
return ("%s(file_id=%r, name=%r, parent_id=%r, "
219
"reference_revision=%r)") % (
220
type(self).__name__, self.file_id, self.name, self.parent_id,
221
self.reference_revision)
223
def __eq__(self, other):
224
return (self.kind == other.kind and
225
self.file_id == other.file_id and
226
self.name == other.name and
227
self.parent_id == other.parent_id and
228
self.reference_revision == other.reference_revision)
231
return self.__class__(
232
self.file_id, self.name, self.parent_id,
233
self.reference_revision)
237
'directory': GitTreeDirectory,
239
'symlink': GitTreeSymlink,
240
'tree-reference': GitTreeSubmodule,
244
def ensure_normalized_path(path):
245
"""Check whether path is normalized.
247
:raises InvalidNormalization: When path is not normalized, and cannot be
248
accessed on this platform by the normalized path.
249
:return: The NFC normalised version of path.
251
norm_path, can_access = osutils.normalized_filename(path)
252
if norm_path != path:
256
raise errors.InvalidNormalization(path)
260
class GitRevisionTree(revisiontree.RevisionTree):
261
"""Revision tree implementation based on Git objects."""
263
def __init__(self, repository, revision_id):
264
self._revision_id = revision_id
265
self._repository = repository
266
self._submodules = None
267
self.store = repository._git.object_store
268
if not isinstance(revision_id, bytes):
269
raise TypeError(revision_id)
270
self.commit_id, self.mapping = repository.lookup_bzr_revision_id(
272
if revision_id == NULL_REVISION:
274
self.mapping = default_mapping
277
commit = self.store[self.commit_id]
279
raise errors.NoSuchRevision(repository, revision_id)
280
self.tree = commit.tree
282
def _submodule_info(self):
283
if self._submodules is None:
285
with self.get_file('.gitmodules') as f:
286
config = GitConfigFile.from_file(f)
289
for path, url, section in parse_submodules(config)}
290
except errors.NoSuchFile:
291
self._submodules = {}
292
return self._submodules
294
def _get_submodule_repository(self, relpath):
295
if not isinstance(relpath, bytes):
296
raise TypeError(relpath)
298
info = self._submodule_info()[relpath]
300
nested_repo_transport = self._repository.controldir.control_transport.clone(
301
relpath.decode('utf-8'))
303
nested_repo_transport = self._repository.controldir.control_transport.clone(
304
posixpath.join('modules', info[1]))
305
nested_controldir = _mod_controldir.ControlDir.open_from_transport(
306
nested_repo_transport)
307
return nested_controldir.find_repository()
309
def _get_submodule_store(self, relpath):
310
return self._get_submodule_repository(relpath)._git.object_store
312
def get_nested_tree(self, path):
313
encoded_path = path.encode('utf-8')
314
nested_repo = self._get_submodule_repository(encoded_path)
315
ref_rev = self.get_reference_revision(path)
316
return nested_repo.revision_tree(ref_rev)
318
def supports_rename_tracking(self):
321
def get_file_revision(self, path):
322
change_scanner = self._repository._file_change_scanner
323
if self.commit_id == ZERO_SHA:
325
(unused_path, commit_id) = change_scanner.find_last_change_revision(
326
path.encode('utf-8'), self.commit_id)
327
return self._repository.lookup_foreign_revision_id(
328
commit_id, self.mapping)
330
def get_file_mtime(self, path):
332
revid = self.get_file_revision(path)
334
raise errors.NoSuchFile(path)
336
rev = self._repository.get_revision(revid)
337
except errors.NoSuchRevision:
338
raise _mod_tree.FileTimestampUnavailable(path)
341
def id2path(self, file_id):
343
path = self.mapping.parse_file_id(file_id)
345
raise errors.NoSuchId(self, file_id)
346
if self.is_versioned(path):
348
raise errors.NoSuchId(self, file_id)
350
def is_versioned(self, path):
351
return self.has_filename(path)
353
def path2id(self, path):
354
if self.mapping.is_special_file(path):
356
if not self.is_versioned(path):
358
return self.mapping.generate_file_id(osutils.safe_unicode(path))
360
def all_file_ids(self):
361
raise errors.UnsupportedOperation(self.all_file_ids, self)
363
def all_versioned_paths(self):
365
todo = [(self.store, b'', self.tree)]
367
(store, path, tree_id) = todo.pop()
370
tree = store[tree_id]
371
for name, mode, hexsha in tree.items():
372
subpath = posixpath.join(path, name)
373
ret.add(subpath.decode('utf-8'))
374
if stat.S_ISDIR(mode):
375
todo.append((store, subpath, hexsha))
378
def _lookup_path(self, path):
379
if self.tree is None:
380
raise errors.NoSuchFile(path)
382
encoded_path = path.encode('utf-8')
383
parts = encoded_path.split(b'/')
387
for i, p in enumerate(parts):
391
if not isinstance(obj, Tree):
392
raise NotTreeError(hexsha)
394
mode, hexsha = obj[p]
396
raise errors.NoSuchFile(path)
397
if S_ISGITLINK(mode) and i != len(parts) - 1:
398
store = self._get_submodule_store(b'/'.join(parts[:i + 1]))
399
hexsha = store[hexsha].tree
400
return (store, mode, hexsha)
402
def is_executable(self, path):
403
(store, mode, hexsha) = self._lookup_path(path)
405
# the tree root is a directory
407
return mode_is_executable(mode)
409
def kind(self, path):
410
(store, mode, hexsha) = self._lookup_path(path)
412
# the tree root is a directory
414
return mode_kind(mode)
416
def has_filename(self, path):
418
self._lookup_path(path)
419
except errors.NoSuchFile:
424
def _submodule_info(self):
425
if self._submodules is None:
427
with self.get_file('.gitmodules') as f:
428
config = GitConfigFile.from_file(f)
431
for path, url, section in parse_submodules(config)}
432
except errors.NoSuchFile:
433
self._submodules = {}
434
return self._submodules
436
def list_files(self, include_root=False, from_dir=None, recursive=True,
437
recurse_nested=False):
438
if self.tree is None:
440
if from_dir is None or from_dir == '.':
442
(store, mode, hexsha) = self._lookup_path(from_dir)
443
if mode is None: # Root
444
root_ie = self._get_dir_ie(b"", None)
446
parent_path = posixpath.dirname(from_dir)
447
parent_id = self.mapping.generate_file_id(parent_path)
448
if mode_kind(mode) == 'directory':
449
root_ie = self._get_dir_ie(from_dir.encode("utf-8"), parent_id)
451
root_ie = self._get_file_ie(
452
store, from_dir.encode("utf-8"),
453
posixpath.basename(from_dir), mode, hexsha)
455
yield (from_dir, "V", root_ie.kind, root_ie)
457
if root_ie.kind == 'directory':
458
todo.append((store, from_dir.encode("utf-8"),
459
b"", hexsha, root_ie.file_id))
461
(store, path, relpath, hexsha, parent_id) = todo.pop()
463
for name, mode, hexsha in tree.iteritems():
464
if self.mapping.is_special_file(name):
466
child_path = posixpath.join(path, name)
467
child_relpath = posixpath.join(relpath, name)
468
if S_ISGITLINK(mode) and recurse_nested:
470
store = self._get_submodule_store(child_relpath)
471
hexsha = store[hexsha].tree
472
if stat.S_ISDIR(mode):
473
ie = self._get_dir_ie(child_path, parent_id)
476
(store, child_path, child_relpath, hexsha,
479
ie = self._get_file_ie(
480
store, child_path, name, mode, hexsha, parent_id)
481
yield (child_relpath.decode('utf-8'), "V", ie.kind, ie)
483
def _get_file_ie(self, store, path, name, mode, hexsha, parent_id):
484
if not isinstance(path, bytes):
485
raise TypeError(path)
486
if not isinstance(name, bytes):
487
raise TypeError(name)
488
kind = mode_kind(mode)
489
path = path.decode('utf-8')
490
name = name.decode("utf-8")
491
file_id = self.mapping.generate_file_id(path)
492
ie = entry_factory[kind](file_id, name, parent_id)
493
if kind == 'symlink':
494
ie.symlink_target = store[hexsha].data.decode('utf-8')
495
elif kind == 'tree-reference':
496
ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(
499
data = store[hexsha].data
500
ie.text_sha1 = osutils.sha_string(data)
501
ie.text_size = len(data)
502
ie.executable = mode_is_executable(mode)
505
def _get_dir_ie(self, path, parent_id):
506
path = path.decode('utf-8')
507
file_id = self.mapping.generate_file_id(path)
508
return GitTreeDirectory(file_id, posixpath.basename(path), parent_id)
510
def iter_child_entries(self, path):
511
(store, mode, tree_sha) = self._lookup_path(path)
513
if mode is not None and not stat.S_ISDIR(mode):
516
encoded_path = path.encode('utf-8')
517
file_id = self.path2id(path)
518
tree = store[tree_sha]
519
for name, mode, hexsha in tree.iteritems():
520
if self.mapping.is_special_file(name):
522
child_path = posixpath.join(encoded_path, name)
523
if stat.S_ISDIR(mode):
524
yield self._get_dir_ie(child_path, file_id)
526
yield self._get_file_ie(store, child_path, name, mode, hexsha,
529
def iter_entries_by_dir(self, specific_files=None):
530
if self.tree is None:
532
if specific_files is not None:
533
if specific_files in ([""], []):
534
specific_files = None
536
specific_files = set([p.encode('utf-8')
537
for p in specific_files])
538
todo = deque([(self.store, b"", self.tree, self.path2id(''))])
539
if specific_files is None or u"" in specific_files:
540
yield u"", self._get_dir_ie(b"", None)
542
store, path, tree_sha, parent_id = todo.popleft()
543
tree = store[tree_sha]
545
for name, mode, hexsha in tree.iteritems():
546
if self.mapping.is_special_file(name):
548
child_path = posixpath.join(path, name)
549
child_path_decoded = child_path.decode('utf-8')
550
if stat.S_ISDIR(mode):
551
if (specific_files is None or
552
any([p for p in specific_files if p.startswith(
555
(store, child_path, hexsha,
556
self.path2id(child_path_decoded)))
557
if specific_files is None or child_path in specific_files:
558
if stat.S_ISDIR(mode):
559
yield (child_path_decoded,
560
self._get_dir_ie(child_path, parent_id))
562
yield (child_path_decoded,
563
self._get_file_ie(store, child_path, name, mode,
565
todo.extendleft(reversed(extradirs))
567
def iter_references(self):
568
if self.supports_tree_reference():
569
for path, entry in self.iter_entries_by_dir():
570
if entry.kind == 'tree-reference':
573
def get_revision_id(self):
574
"""See RevisionTree.get_revision_id."""
575
return self._revision_id
577
def get_file_sha1(self, path, stat_value=None):
578
if self.tree is None:
579
raise errors.NoSuchFile(path)
580
return osutils.sha_string(self.get_file_text(path))
582
def get_file_verifier(self, path, stat_value=None):
583
(store, mode, hexsha) = self._lookup_path(path)
584
return ("GIT", hexsha)
586
def get_file_size(self, path):
587
(store, mode, hexsha) = self._lookup_path(path)
588
if stat.S_ISREG(mode):
589
return len(store[hexsha].data)
592
def get_file_text(self, path):
593
"""See RevisionTree.get_file_text."""
594
(store, mode, hexsha) = self._lookup_path(path)
595
if stat.S_ISREG(mode):
596
return store[hexsha].data
600
def get_symlink_target(self, path):
601
"""See RevisionTree.get_symlink_target."""
602
(store, mode, hexsha) = self._lookup_path(path)
603
if stat.S_ISLNK(mode):
604
return store[hexsha].data.decode('utf-8')
608
def get_reference_revision(self, path):
609
"""See RevisionTree.get_symlink_target."""
610
(store, mode, hexsha) = self._lookup_path(path)
611
if S_ISGITLINK(mode):
612
nested_repo = self._get_submodule_repository(path.encode('utf-8'))
613
return nested_repo.lookup_foreign_revision_id(hexsha)
617
def _comparison_data(self, entry, path):
619
return None, False, None
620
return entry.kind, entry.executable, None
622
def path_content_summary(self, path):
623
"""See Tree.path_content_summary."""
625
(store, mode, hexsha) = self._lookup_path(path)
626
except errors.NoSuchFile:
627
return ('missing', None, None, None)
628
kind = mode_kind(mode)
630
executable = mode_is_executable(mode)
631
contents = store[hexsha].data
632
return (kind, len(contents), executable,
633
osutils.sha_string(contents))
634
elif kind == 'symlink':
635
return (kind, None, None, store[hexsha].data.decode('utf-8'))
636
elif kind == 'tree-reference':
637
nested_repo = self._get_submodule_repository(path.encode('utf-8'))
638
return (kind, None, None,
639
nested_repo.lookup_foreign_revision_id(hexsha))
641
return (kind, None, None, None)
643
def find_related_paths_across_trees(self, paths, trees=[],
644
require_versioned=True):
647
if require_versioned:
648
trees = [self] + (trees if trees is not None else [])
652
if t.is_versioned(p):
657
raise errors.PathsNotVersionedError(unversioned)
658
return filter(self.is_versioned, paths)
660
def _iter_tree_contents(self, include_trees=False):
661
if self.tree is None:
663
return self.store.iter_tree_contents(
664
self.tree, include_trees=include_trees)
666
def annotate_iter(self, path, default_revision=CURRENT_REVISION):
667
"""Return an iterator of revision_id, line tuples.
669
For working trees (and mutable trees in general), the special
670
revision_id 'current:' will be used for lines that are new in this
671
tree, e.g. uncommitted changes.
672
:param default_revision: For lines that don't match a basis, mark them
673
with this revision id. Not all implementations will make use of
676
with self.lock_read():
677
# Now we have the parents of this content
678
from breezy.annotate import Annotator
679
from .annotate import AnnotateProvider
680
annotator = Annotator(AnnotateProvider(
681
self._repository._file_change_scanner))
682
this_key = (path, self.get_file_revision(path))
683
annotations = [(key[-1], line)
684
for key, line in annotator.annotate_flat(this_key)]
687
def _get_rules_searcher(self, default_searcher):
688
return default_searcher
690
def walkdirs(self, prefix=u""):
691
(store, mode, hexsha) = self._lookup_path(prefix)
693
[(store, prefix.encode('utf-8'), hexsha, self.path2id(prefix))])
695
store, path, tree_sha, parent_id = todo.popleft()
696
path_decoded = path.decode('utf-8')
697
tree = store[tree_sha]
699
for name, mode, hexsha in tree.iteritems():
700
if self.mapping.is_special_file(name):
702
child_path = posixpath.join(path, name)
703
file_id = self.path2id(child_path.decode('utf-8'))
704
if stat.S_ISDIR(mode):
705
todo.append((store, child_path, hexsha, file_id))
707
(child_path.decode('utf-8'), name.decode('utf-8'),
708
mode_kind(mode), None,
709
file_id, mode_kind(mode)))
710
yield (path_decoded, parent_id), children
713
def tree_delta_from_git_changes(changes, mappings,
715
require_versioned=False, include_root=False,
717
"""Create a TreeDelta from two git trees.
719
source and target are iterators over tuples with:
720
(filename, sha, mode)
722
(old_mapping, new_mapping) = mappings
723
if target_extras is None:
724
target_extras = set()
725
ret = delta.TreeDelta()
727
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
728
if newpath == b'' and not include_root:
730
if oldpath is not None:
731
oldpath_decoded = oldpath.decode('utf-8')
733
oldpath_decoded = None
734
if newpath is not None:
735
newpath_decoded = newpath.decode('utf-8')
737
newpath_decoded = None
738
if not (specific_files is None or
739
(oldpath is not None and
740
osutils.is_inside_or_parent_of_any(
741
specific_files, oldpath_decoded)) or
742
(newpath is not None and
743
osutils.is_inside_or_parent_of_any(
744
specific_files, newpath_decoded))):
747
if oldpath_decoded is None:
748
fileid = new_mapping.generate_file_id(newpath_decoded)
757
oldexe = mode_is_executable(oldmode)
758
oldkind = mode_kind(oldmode)
762
if oldpath_decoded == u'':
766
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
767
oldparent = old_mapping.generate_file_id(oldparentpath)
768
fileid = old_mapping.generate_file_id(oldpath_decoded)
769
if newpath_decoded is None:
776
newversioned = (newpath_decoded not in target_extras)
778
newexe = mode_is_executable(newmode)
779
newkind = mode_kind(newmode)
783
if newpath_decoded == u'':
787
newparentpath, newname = osutils.split(newpath_decoded)
788
newparent = new_mapping.generate_file_id(newparentpath)
789
if old_mapping.is_special_file(oldpath):
791
if new_mapping.is_special_file(newpath):
793
if oldpath is None and newpath is None:
795
change = _mod_tree.TreeChange(
796
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
797
(oldversioned, newversioned),
798
(oldparent, newparent), (oldname, newname),
799
(oldkind, newkind), (oldexe, newexe))
801
added.append((newpath, newkind))
802
elif newpath is None or newmode == 0:
803
ret.removed.append(change)
804
elif oldpath != newpath:
805
ret.renamed.append(change)
806
elif mode_kind(oldmode) != mode_kind(newmode):
807
ret.kind_changed.append(change)
808
elif oldsha != newsha or oldmode != newmode:
809
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
811
ret.modified.append(change)
813
ret.unchanged.append(change)
815
implicit_dirs = {b''}
816
for path, kind in added:
817
if kind == 'directory' or path in target_extras:
819
implicit_dirs.update(osutils.parent_directories(path))
821
for path, kind in added:
822
if kind == 'directory' and path not in implicit_dirs:
824
path_decoded = osutils.normalized_filename(path)[0]
825
parent_path, basename = osutils.split(path_decoded)
826
parent_id = new_mapping.generate_file_id(parent_path)
827
if path in target_extras:
828
ret.unversioned.append(_mod_tree.TreeChange(
829
None, (None, path_decoded),
830
True, (False, False), (None, parent_id),
831
(None, basename), (None, kind), (None, False)))
833
file_id = new_mapping.generate_file_id(path_decoded)
835
_mod_tree.TreeChange(
836
file_id, (None, path_decoded), True,
839
(None, basename), (None, kind), (None, False)))
844
def changes_from_git_changes(changes, mapping, specific_files=None,
845
include_unchanged=False, target_extras=None):
846
"""Create a iter_changes-like generator from a git stream.
848
source and target are iterators over tuples with:
849
(filename, sha, mode)
851
if target_extras is None:
852
target_extras = set()
853
for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
854
if oldpath is not None:
855
oldpath_decoded = oldpath.decode('utf-8')
857
oldpath_decoded = None
858
if newpath is not None:
859
newpath_decoded = newpath.decode('utf-8')
861
newpath_decoded = None
862
if not (specific_files is None or
863
(oldpath_decoded is not None and
864
osutils.is_inside_or_parent_of_any(
865
specific_files, oldpath_decoded)) or
866
(newpath_decoded is not None and
867
osutils.is_inside_or_parent_of_any(
868
specific_files, newpath_decoded))):
870
if oldpath is not None and mapping.is_special_file(oldpath):
872
if newpath is not None and mapping.is_special_file(newpath):
874
if oldpath_decoded is None:
875
fileid = mapping.generate_file_id(newpath_decoded)
884
oldexe = mode_is_executable(oldmode)
885
oldkind = mode_kind(oldmode)
889
if oldpath_decoded == u'':
893
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
894
oldparent = mapping.generate_file_id(oldparentpath)
895
fileid = mapping.generate_file_id(oldpath_decoded)
896
if newpath_decoded is None:
903
newversioned = (newpath_decoded not in target_extras)
905
newexe = mode_is_executable(newmode)
906
newkind = mode_kind(newmode)
910
if newpath_decoded == u'':
914
newparentpath, newname = osutils.split(newpath_decoded)
915
newparent = mapping.generate_file_id(newparentpath)
916
if (not include_unchanged and
917
oldkind == 'directory' and newkind == 'directory' and
918
oldpath_decoded == newpath_decoded):
920
yield _mod_tree.TreeChange(
921
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
922
(oldversioned, newversioned),
923
(oldparent, newparent), (oldname, newname),
924
(oldkind, newkind), (oldexe, newexe))
927
class InterGitTrees(_mod_tree.InterTree):
928
"""InterTree that works between two git trees."""
930
_matching_from_tree_format = None
931
_matching_to_tree_format = None
932
_test_mutable_trees_to_test_trees = None
935
def is_compatible(cls, source, target):
936
return (isinstance(source, GitRevisionTree) and
937
isinstance(target, GitRevisionTree))
939
def compare(self, want_unchanged=False, specific_files=None,
940
extra_trees=None, require_versioned=False, include_root=False,
941
want_unversioned=False):
942
with self.lock_read():
943
changes, target_extras = self._iter_git_changes(
944
want_unchanged=want_unchanged,
945
require_versioned=require_versioned,
946
specific_files=specific_files,
947
extra_trees=extra_trees,
948
want_unversioned=want_unversioned)
949
return tree_delta_from_git_changes(
950
changes, (self.source.mapping, self.target.mapping),
951
specific_files=specific_files,
952
include_root=include_root, target_extras=target_extras)
954
def iter_changes(self, include_unchanged=False, specific_files=None,
955
pb=None, extra_trees=[], require_versioned=True,
956
want_unversioned=False):
957
with self.lock_read():
958
changes, target_extras = self._iter_git_changes(
959
want_unchanged=include_unchanged,
960
require_versioned=require_versioned,
961
specific_files=specific_files,
962
extra_trees=extra_trees,
963
want_unversioned=want_unversioned)
964
return changes_from_git_changes(
965
changes, self.target.mapping,
966
specific_files=specific_files,
967
include_unchanged=include_unchanged,
968
target_extras=target_extras)
970
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
971
require_versioned=False, extra_trees=None,
972
want_unversioned=False):
973
raise NotImplementedError(self._iter_git_changes)
976
class InterGitRevisionTrees(InterGitTrees):
977
"""InterTree that works between two git revision trees."""
979
_matching_from_tree_format = None
980
_matching_to_tree_format = None
981
_test_mutable_trees_to_test_trees = None
984
def is_compatible(cls, source, target):
985
return (isinstance(source, GitRevisionTree) and
986
isinstance(target, GitRevisionTree))
988
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
989
require_versioned=True, extra_trees=None,
990
want_unversioned=False):
991
trees = [self.source]
992
if extra_trees is not None:
993
trees.extend(extra_trees)
994
if specific_files is not None:
995
specific_files = self.target.find_related_paths_across_trees(
996
specific_files, trees,
997
require_versioned=require_versioned)
999
if (self.source._repository._git.object_store !=
1000
self.target._repository._git.object_store):
1001
store = OverlayObjectStore(
1002
[self.source._repository._git.object_store,
1003
self.target._repository._git.object_store])
1005
store = self.source._repository._git.object_store
1006
return store.tree_changes(
1007
self.source.tree, self.target.tree, want_unchanged=want_unchanged,
1008
include_trees=True, change_type_same=True), set()
1011
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
1014
class MutableGitIndexTree(mutabletree.MutableTree):
1017
self._lock_mode = None
1018
self._lock_count = 0
1019
self._versioned_dirs = None
1020
self._index_dirty = False
1021
self._submodules = None
1023
def is_versioned(self, path):
1024
with self.lock_read():
1025
path = path.rstrip('/').encode('utf-8')
1026
(index, subpath) = self._lookup_index(path)
1027
return (subpath in index or self._has_dir(path))
1029
def _has_dir(self, path):
1030
if not isinstance(path, bytes):
1031
raise TypeError(path)
1034
if self._versioned_dirs is None:
1036
return path in self._versioned_dirs
1038
def _load_dirs(self):
1039
if self._lock_mode is None:
1040
raise errors.ObjectNotLocked(self)
1041
self._versioned_dirs = set()
1042
for p, i in self._recurse_index_entries():
1043
self._ensure_versioned_dir(posixpath.dirname(p))
1045
def _ensure_versioned_dir(self, dirname):
1046
if not isinstance(dirname, bytes):
1047
raise TypeError(dirname)
1048
if dirname in self._versioned_dirs:
1051
self._ensure_versioned_dir(posixpath.dirname(dirname))
1052
self._versioned_dirs.add(dirname)
1054
def path2id(self, path):
1055
with self.lock_read():
1056
path = path.rstrip('/')
1057
if self.is_versioned(path.rstrip('/')):
1058
return self.mapping.generate_file_id(
1059
osutils.safe_unicode(path))
1062
def id2path(self, file_id):
1065
if type(file_id) is not bytes:
1066
raise TypeError(file_id)
1067
with self.lock_read():
1069
path = self.mapping.parse_file_id(file_id)
1071
raise errors.NoSuchId(self, file_id)
1072
if self.is_versioned(path):
1074
raise errors.NoSuchId(self, file_id)
1076
def _set_root_id(self, file_id):
1077
raise errors.UnsupportedOperation(self._set_root_id, self)
1079
def _add(self, files, ids, kinds):
1080
for (path, file_id, kind) in zip(files, ids, kinds):
1081
if file_id is not None:
1082
raise workingtree.SettingFileIdUnsupported()
1083
path, can_access = osutils.normalized_filename(path)
1085
raise errors.InvalidNormalization(path)
1086
self._index_add_entry(path, kind)
1088
def _read_submodule_head(self, path):
1089
raise NotImplementedError(self._read_submodule_head)
1091
def _submodule_info(self):
1092
if self._submodules is None:
1094
with self.get_file('.gitmodules') as f:
1095
config = GitConfigFile.from_file(f)
1096
self._submodules = {
1097
path: (url, section)
1098
for path, url, section in parse_submodules(config)}
1099
except errors.NoSuchFile:
1100
self._submodules = {}
1101
return self._submodules
1103
def _lookup_index(self, encoded_path):
1104
if not isinstance(encoded_path, bytes):
1105
raise TypeError(encoded_path)
1107
if encoded_path in self.index:
1108
return self.index, encoded_path
1109
# TODO(jelmer): Perhaps have a cache with paths under which some
1112
remaining_path = encoded_path
1114
parts = remaining_path.split(b'/')
1115
for i in range(1, len(parts)):
1116
basepath = b'/'.join(parts[:i])
1118
(ctime, mtime, dev, ino, mode, uid, gid, size, sha,
1119
flags) = index[basepath]
1123
if S_ISGITLINK(mode):
1124
index = self._get_submodule_index(basepath)
1125
remaining_path = b'/'.join(parts[i:])
1128
return index, remaining_path
1130
return index, remaining_path
1131
return index, remaining_path
1133
def _index_del_entry(self, index, path):
1135
# TODO(jelmer): Keep track of dirty per index
1136
self._index_dirty = True
1138
def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
1139
if kind == "directory":
1140
# Git indexes don't contain directories
1145
file, stat_val = self.get_file_with_stat(path)
1146
except (errors.NoSuchFile, IOError):
1147
# TODO: Rather than come up with something here, use the old
1150
stat_val = os.stat_result(
1151
(stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1153
blob.set_raw_string(file.read())
1154
# Add object to the repository if it didn't exist yet
1155
if blob.id not in self.store:
1156
self.store.add_object(blob)
1158
elif kind == "symlink":
1161
stat_val = self._lstat(path)
1162
except EnvironmentError:
1163
# TODO: Rather than come up with something here, use the
1165
stat_val = os.stat_result(
1166
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1167
blob.set_raw_string(
1168
self.get_symlink_target(path).encode("utf-8"))
1169
# Add object to the repository if it didn't exist yet
1170
if blob.id not in self.store:
1171
self.store.add_object(blob)
1173
elif kind == "tree-reference":
1174
if reference_revision is not None:
1175
hexsha = self.branch.lookup_bzr_revision_id(
1176
reference_revision)[0]
1178
hexsha = self._read_submodule_head(path)
1180
raise errors.NoCommits(path)
1182
stat_val = self._lstat(path)
1183
except EnvironmentError:
1184
stat_val = os.stat_result(
1185
(S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1186
stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
1188
raise AssertionError("unknown kind '%s'" % kind)
1189
# Add an entry to the index or update the existing entry
1190
ensure_normalized_path(path)
1191
encoded_path = path.encode("utf-8")
1192
if b'\r' in encoded_path or b'\n' in encoded_path:
1193
# TODO(jelmer): Why do we need to do this?
1194
trace.mutter('ignoring path with invalid newline in it: %r', path)
1196
(index, index_path) = self._lookup_index(encoded_path)
1197
index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
1198
self._index_dirty = True
1199
if self._versioned_dirs is not None:
1200
self._ensure_versioned_dir(index_path)
1202
def _recurse_index_entries(self, index=None, basepath=b"",
1203
recurse_nested=False):
1204
# Iterate over all index entries
1205
with self.lock_read():
1208
for path, value in index.items():
1209
(ctime, mtime, dev, ino, mode, uid, gid, size, sha,
1211
if S_ISGITLINK(mode) and recurse_nested:
1212
subindex = self._get_submodule_index(path)
1213
for entry in self._recurse_index_entries(
1214
index=subindex, basepath=path,
1215
recurse_nested=recurse_nested):
1218
yield (posixpath.join(basepath, path), value)
1220
def iter_entries_by_dir(self, specific_files=None):
1221
with self.lock_read():
1222
if specific_files is not None:
1223
specific_files = set(specific_files)
1225
specific_files = None
1226
root_ie = self._get_dir_ie(u"", None)
1228
if specific_files is None or u"" in specific_files:
1229
ret[(u"", u"")] = root_ie
1230
dir_ids = {u"": root_ie.file_id}
1231
for path, value in self._recurse_index_entries():
1232
if self.mapping.is_special_file(path):
1234
path = path.decode("utf-8")
1235
if specific_files is not None and path not in specific_files:
1237
(parent, name) = posixpath.split(path)
1239
file_ie = self._get_file_ie(name, path, value, None)
1240
except errors.NoSuchFile:
1242
if specific_files is None:
1243
for (dir_path, dir_ie) in self._add_missing_parent_ids(
1245
ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
1246
file_ie.parent_id = self.path2id(parent)
1247
ret[(posixpath.dirname(path), path)] = file_ie
1248
# Special casing for directories
1250
for path in specific_files:
1251
key = (posixpath.dirname(path), path)
1252
if key not in ret and self.is_versioned(path):
1253
ret[key] = self._get_dir_ie(path, self.path2id(key[0]))
1254
return ((path, ie) for ((_, path), ie) in sorted(viewitems(ret)))
1256
def iter_references(self):
1257
if self.supports_tree_reference():
1258
# TODO(jelmer): Implement a more efficient version of this
1259
for path, entry in self.iter_entries_by_dir():
1260
if entry.kind == 'tree-reference':
1263
def _get_dir_ie(self, path, parent_id):
1264
file_id = self.path2id(path)
1265
return GitTreeDirectory(file_id,
1266
posixpath.basename(path).strip("/"), parent_id)
1268
def _get_file_ie(self, name, path, value, parent_id):
1269
if not isinstance(name, text_type):
1270
raise TypeError(name)
1271
if not isinstance(path, text_type):
1272
raise TypeError(path)
1273
if not isinstance(value, tuple) or len(value) != 10:
1274
raise TypeError(value)
1275
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1276
file_id = self.path2id(path)
1277
if not isinstance(file_id, bytes):
1278
raise TypeError(file_id)
1279
kind = mode_kind(mode)
1280
ie = entry_factory[kind](file_id, name, parent_id)
1281
if kind == 'symlink':
1282
ie.symlink_target = self.get_symlink_target(path)
1283
elif kind == 'tree-reference':
1284
ie.reference_revision = self.get_reference_revision(path)
1287
data = self.get_file_text(path)
1288
except errors.NoSuchFile:
1290
except IOError as e:
1291
if e.errno != errno.ENOENT:
1295
data = self.branch.repository._git.object_store[sha].data
1296
ie.text_sha1 = osutils.sha_string(data)
1297
ie.text_size = len(data)
1298
ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1301
def _add_missing_parent_ids(self, path, dir_ids):
1304
parent = posixpath.dirname(path).strip("/")
1305
ret = self._add_missing_parent_ids(parent, dir_ids)
1306
parent_id = dir_ids[parent]
1307
ie = self._get_dir_ie(path, parent_id)
1308
dir_ids[path] = ie.file_id
1309
ret.append((path, ie))
1312
def _comparison_data(self, entry, path):
1314
return None, False, None
1315
return entry.kind, entry.executable, None
1317
def _unversion_path(self, path):
1318
if self._lock_mode is None:
1319
raise errors.ObjectNotLocked(self)
1320
encoded_path = path.encode("utf-8")
1322
(index, subpath) = self._lookup_index(encoded_path)
1324
self._index_del_entry(index, encoded_path)
1326
# A directory, perhaps?
1327
# TODO(jelmer): Deletes that involve submodules?
1328
for p in list(index):
1329
if p.startswith(subpath + b"/"):
1331
self._index_del_entry(index, p)
1334
self._versioned_dirs = None
1337
def unversion(self, paths):
1338
with self.lock_tree_write():
1340
if self._unversion_path(path) == 0:
1341
raise errors.NoSuchFile(path)
1342
self._versioned_dirs = None
1348
def update_basis_by_delta(self, revid, delta):
1349
# TODO(jelmer): This shouldn't be called, it's inventory specific.
1350
for (old_path, new_path, file_id, ie) in delta:
1351
if old_path is not None:
1352
(index, old_subpath) = self._lookup_index(
1353
old_path.encode('utf-8'))
1354
if old_subpath in index:
1355
self._index_del_entry(index, old_subpath)
1356
self._versioned_dirs = None
1357
if new_path is not None and ie.kind != 'directory':
1358
self._index_add_entry(new_path, ie.kind)
1360
self._set_merges_from_parent_ids([])
1362
def move(self, from_paths, to_dir=None, after=None):
1364
with self.lock_tree_write():
1365
to_abs = self.abspath(to_dir)
1366
if not os.path.isdir(to_abs):
1367
raise errors.BzrMoveFailedError('', to_dir,
1368
errors.NotADirectory(to_abs))
1370
for from_rel in from_paths:
1371
from_tail = os.path.split(from_rel)[-1]
1372
to_rel = os.path.join(to_dir, from_tail)
1373
self.rename_one(from_rel, to_rel, after=after)
1374
rename_tuples.append((from_rel, to_rel))
1376
return rename_tuples
1378
def rename_one(self, from_rel, to_rel, after=None):
1379
from_path = from_rel.encode("utf-8")
1380
to_rel, can_access = osutils.normalized_filename(to_rel)
1382
raise errors.InvalidNormalization(to_rel)
1383
to_path = to_rel.encode("utf-8")
1384
with self.lock_tree_write():
1386
# Perhaps it's already moved?
1388
not self.has_filename(from_rel) and
1389
self.has_filename(to_rel) and
1390
not self.is_versioned(to_rel))
1392
if not self.has_filename(to_rel):
1393
raise errors.BzrMoveFailedError(
1394
from_rel, to_rel, errors.NoSuchFile(to_rel))
1395
if self.basis_tree().is_versioned(to_rel):
1396
raise errors.BzrMoveFailedError(
1397
from_rel, to_rel, errors.AlreadyVersionedError(to_rel))
1399
kind = self.kind(to_rel)
1402
to_kind = self.kind(to_rel)
1403
except errors.NoSuchFile:
1404
exc_type = errors.BzrRenameFailedError
1407
exc_type = errors.BzrMoveFailedError
1408
if self.is_versioned(to_rel):
1409
raise exc_type(from_rel, to_rel,
1410
errors.AlreadyVersionedError(to_rel))
1411
if not self.has_filename(from_rel):
1412
raise errors.BzrMoveFailedError(
1413
from_rel, to_rel, errors.NoSuchFile(from_rel))
1414
kind = self.kind(from_rel)
1415
if not self.is_versioned(from_rel) and kind != 'directory':
1416
raise exc_type(from_rel, to_rel,
1417
errors.NotVersionedError(from_rel))
1418
if self.has_filename(to_rel):
1419
raise errors.RenameFailedFilesExist(
1420
from_rel, to_rel, errors.FileExists(to_rel))
1422
kind = self.kind(from_rel)
1424
if not after and kind != 'directory':
1425
(index, from_subpath) = self._lookup_index(from_path)
1426
if from_subpath not in index:
1428
raise errors.BzrMoveFailedError(
1430
errors.NotVersionedError(path=from_rel))
1434
self._rename_one(from_rel, to_rel)
1435
except OSError as e:
1436
if e.errno == errno.ENOENT:
1437
raise errors.BzrMoveFailedError(
1438
from_rel, to_rel, errors.NoSuchFile(to_rel))
1440
if kind != 'directory':
1441
(index, from_index_path) = self._lookup_index(from_path)
1443
self._index_del_entry(index, from_path)
1446
self._index_add_entry(to_rel, kind)
1448
todo = [(p, i) for (p, i) in self._recurse_index_entries()
1449
if p.startswith(from_path + b'/')]
1450
for child_path, child_value in todo:
1451
(child_to_index, child_to_index_path) = self._lookup_index(
1452
posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
1453
child_to_index[child_to_index_path] = child_value
1454
# TODO(jelmer): Mark individual index as dirty
1455
self._index_dirty = True
1456
(child_from_index, child_from_index_path) = self._lookup_index(
1458
self._index_del_entry(
1459
child_from_index, child_from_index_path)
1461
self._versioned_dirs = None
1464
def find_related_paths_across_trees(self, paths, trees=[],
1465
require_versioned=True):
1469
if require_versioned:
1470
trees = [self] + (trees if trees is not None else [])
1474
if t.is_versioned(p):
1479
raise errors.PathsNotVersionedError(unversioned)
1481
return filter(self.is_versioned, paths)
1483
def path_content_summary(self, path):
1484
"""See Tree.path_content_summary."""
1486
stat_result = self._lstat(path)
1487
except OSError as e:
1488
if getattr(e, 'errno', None) == errno.ENOENT:
1490
return ('missing', None, None, None)
1491
# propagate other errors
1493
kind = mode_kind(stat_result.st_mode)
1495
return self._file_content_summary(path, stat_result)
1496
elif kind == 'directory':
1497
# perhaps it looks like a plain directory, but it's really a
1499
if self._directory_is_tree_reference(path):
1500
kind = 'tree-reference'
1501
return kind, None, None, None
1502
elif kind == 'symlink':
1503
target = osutils.readlink(self.abspath(path))
1504
return ('symlink', None, None, target)
1506
return (kind, None, None, None)
1508
def stored_kind(self, relpath):
1509
(index, index_path) = self._lookup_index(relpath.encode('utf-8'))
1513
mode = index[index_path].mode
1517
if S_ISGITLINK(mode):
1518
return 'tree-reference'
1521
def kind(self, relpath):
1522
kind = osutils.file_kind(self.abspath(relpath))
1523
if kind == 'directory':
1524
if self._directory_is_tree_reference(relpath):
1525
return 'tree-reference'
1530
def _live_entry(self, relpath):
1531
raise NotImplementedError(self._live_entry)
1533
def get_transform(self, pb=None):
1534
from ..transform import TreeTransform
1535
return TreeTransform(self, pb=pb)
1539
class InterIndexGitTree(InterGitTrees):
1540
"""InterTree that works between a Git revision tree and an index."""
1542
def __init__(self, source, target):
1543
super(InterIndexGitTree, self).__init__(source, target)
1544
self._index = target.index
1547
def is_compatible(cls, source, target):
1548
return (isinstance(source, GitRevisionTree) and
1549
isinstance(target, MutableGitIndexTree))
1551
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1552
require_versioned=False, extra_trees=None,
1553
want_unversioned=False):
1554
trees = [self.source]
1555
if extra_trees is not None:
1556
trees.extend(extra_trees)
1557
if specific_files is not None:
1558
specific_files = self.target.find_related_paths_across_trees(
1559
specific_files, trees,
1560
require_versioned=require_versioned)
1561
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1562
with self.lock_read():
1563
return changes_between_git_tree_and_working_copy(
1564
self.source.store, self.source.tree,
1565
self.target, want_unchanged=want_unchanged,
1566
want_unversioned=want_unversioned)
1569
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
1572
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1573
want_unchanged=False,
1574
want_unversioned=False):
1575
"""Determine the changes between a git tree and a working tree with index.
1580
# Report dirified directories to commit_tree first, so that they can be
1581
# replaced with non-empty directories if they have contents.
1583
trust_executable = target._supports_executable()
1584
for path, index_entry in target._recurse_index_entries():
1586
live_entry = target._live_entry(path)
1587
except EnvironmentError as e:
1588
if e.errno == errno.ENOENT:
1589
# Entry was removed; keep it listed, but mark it as gone.
1590
blobs[path] = (ZERO_SHA, 0)
1591
elif e.errno == errno.EISDIR:
1592
# Backwards compatibility with Dulwich < 0.19.12;
1593
# newer versions of Dulwich return either an entry for the
1594
# submodule or None for directories.
1595
if S_ISGITLINK(index_entry.mode):
1596
blobs[path] = (index_entry.sha, index_entry.mode)
1598
# Entry was turned into a directory
1599
dirified.append((path, Tree().id, stat.S_IFDIR))
1600
store.add_object(Tree())
1604
if live_entry is None:
1605
# Entry was turned into a directory
1606
dirified.append((path, Tree().id, stat.S_IFDIR))
1607
store.add_object(Tree())
1609
mode = live_entry.mode
1610
if not trust_executable:
1611
if mode_is_executable(index_entry.mode):
1615
blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1616
if want_unversioned:
1617
for e in target.extras():
1618
st = target._lstat(e)
1620
np, accessible = osutils.normalized_filename(e)
1621
except UnicodeDecodeError:
1622
raise errors.BadFilenameEncoding(
1624
if stat.S_ISDIR(st.st_mode):
1627
blob = blob_from_path_and_stat(
1628
target.abspath(e).encode(osutils._fs_enc), st)
1629
store.add_object(blob)
1630
np = np.encode('utf-8')
1631
blobs[np] = (blob.id, cleanup_mode(st.st_mode))
1633
to_tree_sha = commit_tree(
1634
store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
1635
return store.tree_changes(
1636
from_tree_sha, to_tree_sha, include_trees=True,
1637
want_unchanged=want_unchanged, change_type_same=True), extras