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, RenameDetector
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 (
81
from .transportgit import (
87
class GitTreeDirectory(_mod_tree.TreeDirectory):
89
__slots__ = ['file_id', 'name', 'parent_id', 'children']
91
def __init__(self, file_id, name, parent_id):
92
self.file_id = file_id
94
self.parent_id = parent_id
103
def executable(self):
107
return self.__class__(
108
self.file_id, self.name, self.parent_id)
111
return "%s(file_id=%r, name=%r, parent_id=%r)" % (
112
self.__class__.__name__, self.file_id, self.name,
115
def __eq__(self, other):
116
return (self.kind == other.kind and
117
self.file_id == other.file_id and
118
self.name == other.name and
119
self.parent_id == other.parent_id)
122
class GitTreeFile(_mod_tree.TreeFile):
124
__slots__ = ['file_id', 'name', 'parent_id', 'text_size', 'text_sha1',
127
def __init__(self, file_id, name, parent_id, text_size=None,
128
text_sha1=None, executable=None):
129
self.file_id = file_id
131
self.parent_id = parent_id
132
self.text_size = text_size
133
self.text_sha1 = text_sha1
134
self.executable = executable
140
def __eq__(self, other):
141
return (self.kind == other.kind and
142
self.file_id == other.file_id and
143
self.name == other.name and
144
self.parent_id == other.parent_id and
145
self.text_sha1 == other.text_sha1 and
146
self.text_size == other.text_size and
147
self.executable == other.executable)
150
return ("%s(file_id=%r, name=%r, parent_id=%r, text_size=%r, "
151
"text_sha1=%r, executable=%r)") % (
152
type(self).__name__, self.file_id, self.name, self.parent_id,
153
self.text_size, self.text_sha1, self.executable)
156
ret = self.__class__(
157
self.file_id, self.name, self.parent_id)
158
ret.text_sha1 = self.text_sha1
159
ret.text_size = self.text_size
160
ret.executable = self.executable
164
class GitTreeSymlink(_mod_tree.TreeLink):
166
__slots__ = ['file_id', 'name', 'parent_id', 'symlink_target']
168
def __init__(self, file_id, name, parent_id,
169
symlink_target=None):
170
self.file_id = file_id
172
self.parent_id = parent_id
173
self.symlink_target = symlink_target
180
def executable(self):
188
return "%s(file_id=%r, name=%r, parent_id=%r, symlink_target=%r)" % (
189
type(self).__name__, self.file_id, self.name, self.parent_id,
192
def __eq__(self, other):
193
return (self.kind == other.kind and
194
self.file_id == other.file_id and
195
self.name == other.name and
196
self.parent_id == other.parent_id and
197
self.symlink_target == other.symlink_target)
200
return self.__class__(
201
self.file_id, self.name, self.parent_id,
205
class GitTreeSubmodule(_mod_tree.TreeReference):
207
__slots__ = ['file_id', 'name', 'parent_id', 'reference_revision']
209
def __init__(self, file_id, name, parent_id, reference_revision=None):
210
self.file_id = file_id
212
self.parent_id = parent_id
213
self.reference_revision = reference_revision
216
def executable(self):
221
return 'tree-reference'
224
return ("%s(file_id=%r, name=%r, parent_id=%r, "
225
"reference_revision=%r)") % (
226
type(self).__name__, self.file_id, self.name, self.parent_id,
227
self.reference_revision)
229
def __eq__(self, other):
230
return (self.kind == other.kind and
231
self.file_id == other.file_id and
232
self.name == other.name and
233
self.parent_id == other.parent_id and
234
self.reference_revision == other.reference_revision)
237
return self.__class__(
238
self.file_id, self.name, self.parent_id,
239
self.reference_revision)
243
'directory': GitTreeDirectory,
245
'symlink': GitTreeSymlink,
246
'tree-reference': GitTreeSubmodule,
250
def ensure_normalized_path(path):
251
"""Check whether path is normalized.
253
:raises InvalidNormalization: When path is not normalized, and cannot be
254
accessed on this platform by the normalized path.
255
:return: The NFC normalised version of path.
257
norm_path, can_access = osutils.normalized_filename(path)
258
if norm_path != path:
262
raise errors.InvalidNormalization(path)
266
class GitRevisionTree(revisiontree.RevisionTree):
267
"""Revision tree implementation based on Git objects."""
269
def __init__(self, repository, revision_id):
270
self._revision_id = revision_id
271
self._repository = repository
272
self._submodules = None
273
self.store = repository._git.object_store
274
if not isinstance(revision_id, bytes):
275
raise TypeError(revision_id)
276
self.commit_id, self.mapping = repository.lookup_bzr_revision_id(
278
if revision_id == NULL_REVISION:
280
self.mapping = default_mapping
283
commit = self.store[self.commit_id]
285
raise errors.NoSuchRevision(repository, revision_id)
286
self.tree = commit.tree
288
def _submodule_info(self):
289
if self._submodules is None:
291
with self.get_file('.gitmodules') as f:
292
config = GitConfigFile.from_file(f)
295
for path, url, section in parse_submodules(config)}
296
except errors.NoSuchFile:
297
self._submodules = {}
298
return self._submodules
300
def _get_submodule_repository(self, relpath):
301
if not isinstance(relpath, bytes):
302
raise TypeError(relpath)
304
info = self._submodule_info()[relpath]
306
nested_repo_transport = self._repository.controldir.user_transport.clone(
307
decode_git_path(relpath))
309
nested_repo_transport = self._repository.controldir.control_transport.clone(
310
posixpath.join('modules', decode_git_path(info[1])))
311
nested_controldir = _mod_controldir.ControlDir.open_from_transport(
312
nested_repo_transport)
313
return nested_controldir.find_repository()
315
def _get_submodule_store(self, relpath):
316
return self._get_submodule_repository(relpath)._git.object_store
318
def get_nested_tree(self, path):
319
encoded_path = encode_git_path(path)
320
nested_repo = self._get_submodule_repository(encoded_path)
321
ref_rev = self.get_reference_revision(path)
322
return nested_repo.revision_tree(ref_rev)
324
def supports_rename_tracking(self):
327
def get_file_revision(self, path):
328
change_scanner = self._repository._file_change_scanner
329
if self.commit_id == ZERO_SHA:
331
(unused_path, commit_id) = change_scanner.find_last_change_revision(
332
encode_git_path(path), self.commit_id)
333
return self._repository.lookup_foreign_revision_id(
334
commit_id, self.mapping)
336
def get_file_mtime(self, path):
338
revid = self.get_file_revision(path)
340
raise errors.NoSuchFile(path)
342
rev = self._repository.get_revision(revid)
343
except errors.NoSuchRevision:
344
raise _mod_tree.FileTimestampUnavailable(path)
347
def id2path(self, file_id, recurse='down'):
349
path = self.mapping.parse_file_id(file_id)
351
raise errors.NoSuchId(self, file_id)
352
if self.is_versioned(path):
354
raise errors.NoSuchId(self, file_id)
356
def is_versioned(self, path):
357
return self.has_filename(path)
359
def path2id(self, path):
360
if self.mapping.is_special_file(path):
362
if not self.is_versioned(path):
364
return self.mapping.generate_file_id(osutils.safe_unicode(path))
366
def all_file_ids(self):
367
raise errors.UnsupportedOperation(self.all_file_ids, self)
369
def all_versioned_paths(self):
371
todo = [(self.store, b'', self.tree)]
373
(store, path, tree_id) = todo.pop()
376
tree = store[tree_id]
377
for name, mode, hexsha in tree.items():
378
subpath = posixpath.join(path, name)
379
ret.add(decode_git_path(subpath))
380
if stat.S_ISDIR(mode):
381
todo.append((store, subpath, hexsha))
384
def _lookup_path(self, path):
385
if self.tree is None:
386
raise errors.NoSuchFile(path)
388
encoded_path = encode_git_path(path)
389
parts = encoded_path.split(b'/')
393
for i, p in enumerate(parts):
397
if not isinstance(obj, Tree):
398
raise NotTreeError(hexsha)
400
mode, hexsha = obj[p]
402
raise errors.NoSuchFile(path)
403
if S_ISGITLINK(mode) and i != len(parts) - 1:
404
store = self._get_submodule_store(b'/'.join(parts[:i + 1]))
405
hexsha = store[hexsha].tree
406
return (store, mode, hexsha)
408
def is_executable(self, path):
409
(store, mode, hexsha) = self._lookup_path(path)
411
# the tree root is a directory
413
return mode_is_executable(mode)
415
def kind(self, path):
416
(store, mode, hexsha) = self._lookup_path(path)
418
# the tree root is a directory
420
return mode_kind(mode)
422
def has_filename(self, path):
424
self._lookup_path(path)
425
except errors.NoSuchFile:
430
def _submodule_info(self):
431
if self._submodules is None:
433
with self.get_file('.gitmodules') as f:
434
config = GitConfigFile.from_file(f)
437
for path, url, section in parse_submodules(config)}
438
except errors.NoSuchFile:
439
self._submodules = {}
440
return self._submodules
442
def list_files(self, include_root=False, from_dir=None, recursive=True,
443
recurse_nested=False):
444
if self.tree is None:
446
if from_dir is None or from_dir == '.':
448
(store, mode, hexsha) = self._lookup_path(from_dir)
449
if mode is None: # Root
450
root_ie = self._get_dir_ie(b"", None)
452
parent_path = posixpath.dirname(from_dir)
453
parent_id = self.mapping.generate_file_id(parent_path)
454
if mode_kind(mode) == 'directory':
455
root_ie = self._get_dir_ie(encode_git_path(from_dir), parent_id)
457
root_ie = self._get_file_ie(
458
store, encode_git_path(from_dir),
459
posixpath.basename(from_dir), mode, hexsha)
461
yield (from_dir, "V", root_ie.kind, root_ie)
463
if root_ie.kind == 'directory':
464
todo.append((store, encode_git_path(from_dir),
465
b"", hexsha, root_ie.file_id))
467
(store, path, relpath, hexsha, parent_id) = todo.pop()
469
for name, mode, hexsha in tree.iteritems():
470
if self.mapping.is_special_file(name):
472
child_path = posixpath.join(path, name)
473
child_relpath = posixpath.join(relpath, name)
474
if S_ISGITLINK(mode) and recurse_nested:
476
store = self._get_submodule_store(child_relpath)
477
hexsha = store[hexsha].tree
478
if stat.S_ISDIR(mode):
479
ie = self._get_dir_ie(child_path, parent_id)
482
(store, child_path, child_relpath, hexsha,
485
ie = self._get_file_ie(
486
store, child_path, name, mode, hexsha, parent_id)
487
yield (decode_git_path(child_relpath), "V", ie.kind, ie)
489
def _get_file_ie(self, store, path, name, mode, hexsha, parent_id):
490
if not isinstance(path, bytes):
491
raise TypeError(path)
492
if not isinstance(name, bytes):
493
raise TypeError(name)
494
kind = mode_kind(mode)
495
path = decode_git_path(path)
496
name = decode_git_path(name)
497
file_id = self.mapping.generate_file_id(path)
498
ie = entry_factory[kind](file_id, name, parent_id)
499
if kind == 'symlink':
500
ie.symlink_target = decode_git_path(store[hexsha].data)
501
elif kind == 'tree-reference':
502
ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(
505
data = store[hexsha].data
506
ie.text_sha1 = osutils.sha_string(data)
507
ie.text_size = len(data)
508
ie.executable = mode_is_executable(mode)
511
def _get_dir_ie(self, path, parent_id):
512
path = decode_git_path(path)
513
file_id = self.mapping.generate_file_id(path)
514
return GitTreeDirectory(file_id, posixpath.basename(path), parent_id)
516
def iter_child_entries(self, path):
517
(store, mode, tree_sha) = self._lookup_path(path)
519
if mode is not None and not stat.S_ISDIR(mode):
522
encoded_path = encode_git_path(path)
523
file_id = self.path2id(path)
524
tree = store[tree_sha]
525
for name, mode, hexsha in tree.iteritems():
526
if self.mapping.is_special_file(name):
528
child_path = posixpath.join(encoded_path, name)
529
if stat.S_ISDIR(mode):
530
yield self._get_dir_ie(child_path, file_id)
532
yield self._get_file_ie(store, child_path, name, mode, hexsha,
535
def iter_entries_by_dir(self, specific_files=None,
536
recurse_nested=False):
537
if self.tree is None:
539
if specific_files is not None:
540
if specific_files in ([""], []):
541
specific_files = None
543
specific_files = set([encode_git_path(p)
544
for p in specific_files])
545
todo = deque([(self.store, b"", self.tree, self.path2id(''))])
546
if specific_files is None or u"" in specific_files:
547
yield u"", self._get_dir_ie(b"", None)
549
store, path, tree_sha, parent_id = todo.popleft()
550
tree = store[tree_sha]
552
for name, mode, hexsha in tree.iteritems():
553
if self.mapping.is_special_file(name):
555
child_path = posixpath.join(path, name)
556
child_path_decoded = decode_git_path(child_path)
557
if recurse_nested and S_ISGITLINK(mode):
559
store = self._get_submodule_store(child_path)
560
hexsha = store[hexsha].tree
561
if stat.S_ISDIR(mode):
562
if (specific_files is None or
563
any([p for p in specific_files if p.startswith(
566
(store, child_path, hexsha,
567
self.path2id(child_path_decoded)))
568
if specific_files is None or child_path in specific_files:
569
if stat.S_ISDIR(mode):
570
yield (child_path_decoded,
571
self._get_dir_ie(child_path, parent_id))
573
yield (child_path_decoded,
574
self._get_file_ie(store, child_path, name, mode,
576
todo.extendleft(reversed(extradirs))
578
def iter_references(self):
579
if self.supports_tree_reference():
580
for path, entry in self.iter_entries_by_dir():
581
if entry.kind == 'tree-reference':
584
def get_revision_id(self):
585
"""See RevisionTree.get_revision_id."""
586
return self._revision_id
588
def get_file_sha1(self, path, stat_value=None):
589
if self.tree is None:
590
raise errors.NoSuchFile(path)
591
return osutils.sha_string(self.get_file_text(path))
593
def get_file_verifier(self, path, stat_value=None):
594
(store, mode, hexsha) = self._lookup_path(path)
595
return ("GIT", hexsha)
597
def get_file_size(self, path):
598
(store, mode, hexsha) = self._lookup_path(path)
599
if stat.S_ISREG(mode):
600
return len(store[hexsha].data)
603
def get_file_text(self, path):
604
"""See RevisionTree.get_file_text."""
605
(store, mode, hexsha) = self._lookup_path(path)
606
if stat.S_ISREG(mode):
607
return store[hexsha].data
611
def get_symlink_target(self, path):
612
"""See RevisionTree.get_symlink_target."""
613
(store, mode, hexsha) = self._lookup_path(path)
614
if stat.S_ISLNK(mode):
615
return decode_git_path(store[hexsha].data)
619
def get_reference_revision(self, path):
620
"""See RevisionTree.get_symlink_target."""
621
(store, mode, hexsha) = self._lookup_path(path)
622
if S_ISGITLINK(mode):
624
nested_repo = self._get_submodule_repository(encode_git_path(path))
625
except errors.NotBranchError:
626
return self.mapping.revision_id_foreign_to_bzr(hexsha)
628
return nested_repo.lookup_foreign_revision_id(hexsha)
632
def _comparison_data(self, entry, path):
634
return None, False, None
635
return entry.kind, entry.executable, None
637
def path_content_summary(self, path):
638
"""See Tree.path_content_summary."""
640
(store, mode, hexsha) = self._lookup_path(path)
641
except errors.NoSuchFile:
642
return ('missing', None, None, None)
643
kind = mode_kind(mode)
645
executable = mode_is_executable(mode)
646
contents = store[hexsha].data
647
return (kind, len(contents), executable,
648
osutils.sha_string(contents))
649
elif kind == 'symlink':
650
return (kind, None, None, decode_git_path(store[hexsha].data))
651
elif kind == 'tree-reference':
652
nested_repo = self._get_submodule_repository(encode_git_path(path))
653
return (kind, None, None,
654
nested_repo.lookup_foreign_revision_id(hexsha))
656
return (kind, None, None, None)
658
def find_related_paths_across_trees(self, paths, trees=[],
659
require_versioned=True):
662
if require_versioned:
663
trees = [self] + (trees if trees is not None else [])
667
if t.is_versioned(p):
672
raise errors.PathsNotVersionedError(unversioned)
673
return filter(self.is_versioned, paths)
675
def _iter_tree_contents(self, include_trees=False):
676
if self.tree is None:
678
return self.store.iter_tree_contents(
679
self.tree, include_trees=include_trees)
681
def annotate_iter(self, path, default_revision=CURRENT_REVISION):
682
"""Return an iterator of revision_id, line tuples.
684
For working trees (and mutable trees in general), the special
685
revision_id 'current:' will be used for lines that are new in this
686
tree, e.g. uncommitted changes.
687
:param default_revision: For lines that don't match a basis, mark them
688
with this revision id. Not all implementations will make use of
691
with self.lock_read():
692
# Now we have the parents of this content
693
from breezy.annotate import Annotator
694
from .annotate import AnnotateProvider
695
annotator = Annotator(AnnotateProvider(
696
self._repository._file_change_scanner))
697
this_key = (path, self.get_file_revision(path))
698
annotations = [(key[-1], line)
699
for key, line in annotator.annotate_flat(this_key)]
702
def _get_rules_searcher(self, default_searcher):
703
return default_searcher
705
def walkdirs(self, prefix=u""):
706
(store, mode, hexsha) = self._lookup_path(prefix)
708
[(store, encode_git_path(prefix), hexsha, self.path2id(prefix))])
710
store, path, tree_sha, parent_id = todo.popleft()
711
path_decoded = decode_git_path(path)
712
tree = store[tree_sha]
714
for name, mode, hexsha in tree.iteritems():
715
if self.mapping.is_special_file(name):
717
child_path = posixpath.join(path, name)
718
file_id = self.path2id(decode_git_path(child_path))
719
if stat.S_ISDIR(mode):
720
todo.append((store, child_path, hexsha, file_id))
722
(decode_git_path(child_path), decode_git_path(name),
723
mode_kind(mode), None,
724
file_id, mode_kind(mode)))
725
yield (path_decoded, parent_id), children
727
def preview_transform(self, pb=None):
728
from .transform import GitTransformPreview
729
return GitTransformPreview(self, pb=pb)
732
def tree_delta_from_git_changes(changes, mappings,
734
require_versioned=False, include_root=False,
735
source_extras=None, target_extras=None):
736
"""Create a TreeDelta from two git trees.
738
source and target are iterators over tuples with:
739
(filename, sha, mode)
741
(old_mapping, new_mapping) = mappings
742
if target_extras is None:
743
target_extras = set()
744
if source_extras is None:
745
source_extras = set()
746
ret = delta.TreeDelta()
748
for (change_type, old, new) in changes:
749
(oldpath, oldmode, oldsha) = old
750
(newpath, newmode, newsha) = new
751
if newpath == b'' and not include_root:
753
copied = (change_type == 'copy')
754
if oldpath is not None:
755
oldpath_decoded = decode_git_path(oldpath)
757
oldpath_decoded = None
758
if newpath is not None:
759
newpath_decoded = decode_git_path(newpath)
761
newpath_decoded = None
762
if not (specific_files is None or
763
(oldpath is not None and
764
osutils.is_inside_or_parent_of_any(
765
specific_files, oldpath_decoded)) or
766
(newpath is not None and
767
osutils.is_inside_or_parent_of_any(
768
specific_files, newpath_decoded))):
778
oldversioned = (oldpath not in source_extras)
780
oldexe = mode_is_executable(oldmode)
781
oldkind = mode_kind(oldmode)
789
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
790
oldparent = old_mapping.generate_file_id(oldparentpath)
798
newversioned = (newpath not in target_extras)
800
newexe = mode_is_executable(newmode)
801
newkind = mode_kind(newmode)
805
if newpath_decoded == u'':
809
newparentpath, newname = osutils.split(newpath_decoded)
810
newparent = new_mapping.generate_file_id(newparentpath)
811
if oldversioned and not copied:
812
fileid = old_mapping.generate_file_id(oldpath_decoded)
814
fileid = new_mapping.generate_file_id(newpath_decoded)
817
if old_mapping.is_special_file(oldpath):
819
if new_mapping.is_special_file(newpath):
821
if oldpath is None and newpath is None:
823
change = _mod_tree.TreeChange(
824
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
825
(oldversioned, newversioned),
826
(oldparent, newparent), (oldname, newname),
827
(oldkind, newkind), (oldexe, newexe),
829
if newpath is not None and not newversioned and newkind != 'directory':
830
change.file_id = None
831
ret.unversioned.append(change)
832
elif change_type == 'add':
833
added.append((newpath, newkind))
834
elif newpath is None or newmode == 0:
835
ret.removed.append(change)
836
elif change_type == 'delete':
837
ret.removed.append(change)
838
elif change_type == 'copy':
839
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
841
ret.copied.append(change)
842
elif change_type == 'rename':
843
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
845
ret.renamed.append(change)
846
elif mode_kind(oldmode) != mode_kind(newmode):
847
ret.kind_changed.append(change)
848
elif oldsha != newsha or oldmode != newmode:
849
if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
851
ret.modified.append(change)
853
ret.unchanged.append(change)
855
implicit_dirs = {b''}
856
for path, kind in added:
857
if kind == 'directory' or path in target_extras:
859
implicit_dirs.update(osutils.parent_directories(path))
861
for path, kind in added:
862
if kind == 'directory' and path not in implicit_dirs:
864
path_decoded = decode_git_path(path)
865
parent_path, basename = osutils.split(path_decoded)
866
parent_id = new_mapping.generate_file_id(parent_path)
867
file_id = new_mapping.generate_file_id(path_decoded)
869
_mod_tree.TreeChange(
870
file_id, (None, path_decoded), True,
873
(None, basename), (None, kind), (None, False)))
878
def changes_from_git_changes(changes, mapping, specific_files=None,
879
include_unchanged=False, source_extras=None,
881
"""Create a iter_changes-like generator from a git stream.
883
source and target are iterators over tuples with:
884
(filename, sha, mode)
886
if target_extras is None:
887
target_extras = set()
888
if source_extras is None:
889
source_extras = set()
890
for (change_type, old, new) in changes:
891
if change_type == 'unchanged' and not include_unchanged:
893
(oldpath, oldmode, oldsha) = old
894
(newpath, newmode, newsha) = new
895
if oldpath is not None:
896
oldpath_decoded = decode_git_path(oldpath)
898
oldpath_decoded = None
899
if newpath is not None:
900
newpath_decoded = decode_git_path(newpath)
902
newpath_decoded = None
903
if not (specific_files is None or
904
(oldpath_decoded is not None and
905
osutils.is_inside_or_parent_of_any(
906
specific_files, oldpath_decoded)) or
907
(newpath_decoded is not None and
908
osutils.is_inside_or_parent_of_any(
909
specific_files, newpath_decoded))):
911
if oldpath is not None and mapping.is_special_file(oldpath):
913
if newpath is not None and mapping.is_special_file(newpath):
922
oldversioned = (oldpath not in source_extras)
924
oldexe = mode_is_executable(oldmode)
925
oldkind = mode_kind(oldmode)
929
if oldpath_decoded == u'':
933
(oldparentpath, oldname) = osutils.split(oldpath_decoded)
934
oldparent = mapping.generate_file_id(oldparentpath)
942
newversioned = (newpath not in target_extras)
944
newexe = mode_is_executable(newmode)
945
newkind = mode_kind(newmode)
949
if newpath_decoded == u'':
953
newparentpath, newname = osutils.split(newpath_decoded)
954
newparent = mapping.generate_file_id(newparentpath)
955
if (not include_unchanged and
956
oldkind == 'directory' and newkind == 'directory' and
957
oldpath_decoded == newpath_decoded):
959
if oldversioned and change_type != 'copy':
960
fileid = mapping.generate_file_id(oldpath_decoded)
962
fileid = mapping.generate_file_id(newpath_decoded)
965
yield _mod_tree.TreeChange(
966
fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
967
(oldversioned, newversioned),
968
(oldparent, newparent), (oldname, newname),
969
(oldkind, newkind), (oldexe, newexe),
970
copied=(change_type == 'copy'))
973
class InterGitTrees(_mod_tree.InterTree):
974
"""InterTree that works between two git trees."""
976
_matching_from_tree_format = None
977
_matching_to_tree_format = None
978
_test_mutable_trees_to_test_trees = None
981
def is_compatible(cls, source, target):
982
return (isinstance(source, GitRevisionTree) and
983
isinstance(target, GitRevisionTree))
985
def compare(self, want_unchanged=False, specific_files=None,
986
extra_trees=None, require_versioned=False, include_root=False,
987
want_unversioned=False):
988
with self.lock_read():
989
changes, source_extras, target_extras = self._iter_git_changes(
990
want_unchanged=want_unchanged,
991
require_versioned=require_versioned,
992
specific_files=specific_files,
993
extra_trees=extra_trees,
994
want_unversioned=want_unversioned)
995
return tree_delta_from_git_changes(
996
changes, (self.source.mapping, self.target.mapping),
997
specific_files=specific_files,
998
include_root=include_root,
999
source_extras=source_extras, target_extras=target_extras)
1001
def iter_changes(self, include_unchanged=False, specific_files=None,
1002
pb=None, extra_trees=[], require_versioned=True,
1003
want_unversioned=False):
1004
with self.lock_read():
1005
changes, source_extras, target_extras = self._iter_git_changes(
1006
want_unchanged=include_unchanged,
1007
require_versioned=require_versioned,
1008
specific_files=specific_files,
1009
extra_trees=extra_trees,
1010
want_unversioned=want_unversioned)
1011
return changes_from_git_changes(
1012
changes, self.target.mapping,
1013
specific_files=specific_files,
1014
include_unchanged=include_unchanged,
1015
source_extras=source_extras,
1016
target_extras=target_extras)
1018
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1019
require_versioned=False, extra_trees=None,
1020
want_unversioned=False, include_trees=True):
1021
raise NotImplementedError(self._iter_git_changes)
1023
def find_target_path(self, path, recurse='none'):
1024
ret = self.find_target_paths([path], recurse=recurse)
1027
def find_source_path(self, path, recurse='none'):
1028
ret = self.find_source_paths([path], recurse=recurse)
1031
def find_target_paths(self, paths, recurse='none'):
1034
changes = self._iter_git_changes(
1035
specific_files=paths, include_trees=False)[0]
1036
for (change_type, old, new) in changes:
1039
oldpath = decode_git_path(old[0])
1040
if oldpath in paths:
1041
ret[oldpath] = decode_git_path(new[0]) if new[0] else None
1044
if self.source.has_filename(path):
1045
if self.target.has_filename(path):
1050
raise errors.NoSuchFile(path)
1053
def find_source_paths(self, paths, recurse='none'):
1056
changes = self._iter_git_changes(
1057
specific_files=paths, include_trees=False)[0]
1058
for (change_type, old, new) in changes:
1061
newpath = decode_git_path(new[0])
1062
if newpath in paths:
1063
ret[newpath] = decode_git_path(old[0]) if old[0] else None
1066
if self.target.has_filename(path):
1067
if self.source.has_filename(path):
1072
raise errors.NoSuchFile(path)
1076
class InterGitRevisionTrees(InterGitTrees):
1077
"""InterTree that works between two git revision trees."""
1079
_matching_from_tree_format = None
1080
_matching_to_tree_format = None
1081
_test_mutable_trees_to_test_trees = None
1084
def is_compatible(cls, source, target):
1085
return (isinstance(source, GitRevisionTree) and
1086
isinstance(target, GitRevisionTree))
1088
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1089
require_versioned=True, extra_trees=None,
1090
want_unversioned=False, include_trees=True):
1091
trees = [self.source]
1092
if extra_trees is not None:
1093
trees.extend(extra_trees)
1094
if specific_files is not None:
1095
specific_files = self.target.find_related_paths_across_trees(
1096
specific_files, trees,
1097
require_versioned=require_versioned)
1099
if (self.source._repository._git.object_store !=
1100
self.target._repository._git.object_store):
1101
store = OverlayObjectStore(
1102
[self.source._repository._git.object_store,
1103
self.target._repository._git.object_store])
1105
store = self.source._repository._git.object_store
1106
rename_detector = RenameDetector(store)
1107
changes = tree_changes(
1108
store, self.source.tree, self.target.tree,
1109
want_unchanged=want_unchanged, include_trees=include_trees,
1110
change_type_same=True, rename_detector=rename_detector)
1111
return changes, set(), set()
1114
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
1117
class MutableGitIndexTree(mutabletree.MutableTree):
1120
self._lock_mode = None
1121
self._lock_count = 0
1122
self._versioned_dirs = None
1123
self._index_dirty = False
1124
self._submodules = None
1126
def is_versioned(self, path):
1127
with self.lock_read():
1128
path = encode_git_path(path.rstrip('/'))
1129
(index, subpath) = self._lookup_index(path)
1130
return (subpath in index or self._has_dir(path))
1132
def _has_dir(self, path):
1133
if not isinstance(path, bytes):
1134
raise TypeError(path)
1137
if self._versioned_dirs is None:
1139
return path in self._versioned_dirs
1141
def _load_dirs(self):
1142
if self._lock_mode is None:
1143
raise errors.ObjectNotLocked(self)
1144
self._versioned_dirs = set()
1145
for p, i in self._recurse_index_entries():
1146
self._ensure_versioned_dir(posixpath.dirname(p))
1148
def _ensure_versioned_dir(self, dirname):
1149
if not isinstance(dirname, bytes):
1150
raise TypeError(dirname)
1151
if dirname in self._versioned_dirs:
1154
self._ensure_versioned_dir(posixpath.dirname(dirname))
1155
self._versioned_dirs.add(dirname)
1157
def path2id(self, path):
1158
with self.lock_read():
1159
path = path.rstrip('/')
1160
if self.is_versioned(path.rstrip('/')):
1161
return self.mapping.generate_file_id(
1162
osutils.safe_unicode(path))
1165
def id2path(self, file_id, recurse='down'):
1168
if type(file_id) is not bytes:
1169
raise TypeError(file_id)
1170
with self.lock_read():
1172
path = self.mapping.parse_file_id(file_id)
1174
raise errors.NoSuchId(self, file_id)
1175
if self.is_versioned(path):
1177
raise errors.NoSuchId(self, file_id)
1179
def _set_root_id(self, file_id):
1180
raise errors.UnsupportedOperation(self._set_root_id, self)
1182
def _add(self, files, ids, kinds):
1183
for (path, file_id, kind) in zip(files, ids, kinds):
1184
if file_id is not None:
1185
raise workingtree.SettingFileIdUnsupported()
1186
path, can_access = osutils.normalized_filename(path)
1188
raise errors.InvalidNormalization(path)
1189
self._index_add_entry(path, kind)
1191
def _read_submodule_head(self, path):
1192
raise NotImplementedError(self._read_submodule_head)
1194
def _submodule_info(self):
1195
if self._submodules is None:
1197
with self.get_file('.gitmodules') as f:
1198
config = GitConfigFile.from_file(f)
1199
self._submodules = {
1200
path: (url, section)
1201
for path, url, section in parse_submodules(config)}
1202
except errors.NoSuchFile:
1203
self._submodules = {}
1204
return self._submodules
1206
def _lookup_index(self, encoded_path):
1207
if not isinstance(encoded_path, bytes):
1208
raise TypeError(encoded_path)
1210
if encoded_path in self.index:
1211
return self.index, encoded_path
1212
# TODO(jelmer): Perhaps have a cache with paths under which some
1215
remaining_path = encoded_path
1217
parts = remaining_path.split(b'/')
1218
for i in range(1, len(parts)):
1219
basepath = b'/'.join(parts[:i])
1221
(ctime, mtime, dev, ino, mode, uid, gid, size, sha,
1222
flags) = index[basepath]
1226
if S_ISGITLINK(mode):
1227
index = self._get_submodule_index(basepath)
1228
remaining_path = b'/'.join(parts[i:])
1231
return index, remaining_path
1233
return index, remaining_path
1234
return index, remaining_path
1236
def _index_del_entry(self, index, path):
1238
# TODO(jelmer): Keep track of dirty per index
1239
self._index_dirty = True
1241
def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
1242
if kind == "directory":
1243
# Git indexes don't contain directories
1248
file, stat_val = self.get_file_with_stat(path)
1249
except (errors.NoSuchFile, IOError):
1250
# TODO: Rather than come up with something here, use the old
1253
stat_val = os.stat_result(
1254
(stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1256
blob.set_raw_string(file.read())
1257
# Add object to the repository if it didn't exist yet
1258
if blob.id not in self.store:
1259
self.store.add_object(blob)
1261
elif kind == "symlink":
1264
stat_val = self._lstat(path)
1265
except EnvironmentError:
1266
# TODO: Rather than come up with something here, use the
1268
stat_val = os.stat_result(
1269
(stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1270
blob.set_raw_string(encode_git_path(self.get_symlink_target(path)))
1271
# Add object to the repository if it didn't exist yet
1272
if blob.id not in self.store:
1273
self.store.add_object(blob)
1275
elif kind == "tree-reference":
1276
if reference_revision is not None:
1277
hexsha = self.branch.lookup_bzr_revision_id(
1278
reference_revision)[0]
1280
hexsha = self._read_submodule_head(path)
1282
raise errors.NoCommits(path)
1284
stat_val = self._lstat(path)
1285
except EnvironmentError:
1286
stat_val = os.stat_result(
1287
(S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1288
stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
1290
raise AssertionError("unknown kind '%s'" % kind)
1291
# Add an entry to the index or update the existing entry
1292
ensure_normalized_path(path)
1293
encoded_path = encode_git_path(path)
1294
if b'\r' in encoded_path or b'\n' in encoded_path:
1295
# TODO(jelmer): Why do we need to do this?
1296
trace.mutter('ignoring path with invalid newline in it: %r', path)
1298
(index, index_path) = self._lookup_index(encoded_path)
1299
index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
1300
self._index_dirty = True
1301
if self._versioned_dirs is not None:
1302
self._ensure_versioned_dir(index_path)
1304
def _recurse_index_entries(self, index=None, basepath=b"",
1305
recurse_nested=False):
1306
# Iterate over all index entries
1307
with self.lock_read():
1310
for path, value in index.items():
1311
(ctime, mtime, dev, ino, mode, uid, gid, size, sha,
1313
if S_ISGITLINK(mode) and recurse_nested:
1314
subindex = self._get_submodule_index(path)
1315
for entry in self._recurse_index_entries(
1316
index=subindex, basepath=path,
1317
recurse_nested=recurse_nested):
1320
yield (posixpath.join(basepath, path), value)
1322
def iter_entries_by_dir(self, specific_files=None,
1323
recurse_nested=False):
1324
with self.lock_read():
1325
if specific_files is not None:
1326
specific_files = set(specific_files)
1328
specific_files = None
1329
root_ie = self._get_dir_ie(u"", None)
1331
if specific_files is None or u"" in specific_files:
1332
ret[(u"", u"")] = root_ie
1333
dir_ids = {u"": root_ie.file_id}
1334
for path, value in self._recurse_index_entries(
1335
recurse_nested=recurse_nested):
1336
if self.mapping.is_special_file(path):
1338
path = decode_git_path(path)
1339
if specific_files is not None and path not in specific_files:
1341
(parent, name) = posixpath.split(path)
1343
file_ie = self._get_file_ie(name, path, value, None)
1344
except errors.NoSuchFile:
1346
if specific_files is None:
1347
for (dir_path, dir_ie) in self._add_missing_parent_ids(
1349
ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
1350
file_ie.parent_id = self.path2id(parent)
1351
ret[(posixpath.dirname(path), path)] = file_ie
1352
# Special casing for directories
1354
for path in specific_files:
1355
key = (posixpath.dirname(path), path)
1356
if key not in ret and self.is_versioned(path):
1357
ret[key] = self._get_dir_ie(path, self.path2id(key[0]))
1358
return ((path, ie) for ((_, path), ie) in sorted(viewitems(ret)))
1360
def iter_references(self):
1361
if self.supports_tree_reference():
1362
# TODO(jelmer): Implement a more efficient version of this
1363
for path, entry in self.iter_entries_by_dir():
1364
if entry.kind == 'tree-reference':
1367
def _get_dir_ie(self, path, parent_id):
1368
file_id = self.path2id(path)
1369
return GitTreeDirectory(file_id,
1370
posixpath.basename(path).strip("/"), parent_id)
1372
def _get_file_ie(self, name, path, value, parent_id):
1373
if not isinstance(name, text_type):
1374
raise TypeError(name)
1375
if not isinstance(path, text_type):
1376
raise TypeError(path)
1377
if not isinstance(value, tuple) or len(value) != 10:
1378
raise TypeError(value)
1379
(ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
1380
file_id = self.path2id(path)
1381
if not isinstance(file_id, bytes):
1382
raise TypeError(file_id)
1383
kind = mode_kind(mode)
1384
ie = entry_factory[kind](file_id, name, parent_id)
1385
if kind == 'symlink':
1386
ie.symlink_target = self.get_symlink_target(path)
1387
elif kind == 'tree-reference':
1388
ie.reference_revision = self.get_reference_revision(path)
1391
data = self.get_file_text(path)
1392
except errors.NoSuchFile:
1394
except IOError as e:
1395
if e.errno != errno.ENOENT:
1399
data = self.branch.repository._git.object_store[sha].data
1400
ie.text_sha1 = osutils.sha_string(data)
1401
ie.text_size = len(data)
1402
ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1405
def _add_missing_parent_ids(self, path, dir_ids):
1408
parent = posixpath.dirname(path).strip("/")
1409
ret = self._add_missing_parent_ids(parent, dir_ids)
1410
parent_id = dir_ids[parent]
1411
ie = self._get_dir_ie(path, parent_id)
1412
dir_ids[path] = ie.file_id
1413
ret.append((path, ie))
1416
def _comparison_data(self, entry, path):
1418
return None, False, None
1419
return entry.kind, entry.executable, None
1421
def _unversion_path(self, path):
1422
if self._lock_mode is None:
1423
raise errors.ObjectNotLocked(self)
1424
encoded_path = encode_git_path(path)
1426
(index, subpath) = self._lookup_index(encoded_path)
1428
self._index_del_entry(index, encoded_path)
1430
# A directory, perhaps?
1431
# TODO(jelmer): Deletes that involve submodules?
1432
for p in list(index):
1433
if p.startswith(subpath + b"/"):
1435
self._index_del_entry(index, p)
1438
self._versioned_dirs = None
1441
def unversion(self, paths):
1442
with self.lock_tree_write():
1444
if self._unversion_path(path) == 0:
1445
raise errors.NoSuchFile(path)
1446
self._versioned_dirs = None
1452
def update_basis_by_delta(self, revid, delta):
1453
# TODO(jelmer): This shouldn't be called, it's inventory specific.
1454
for (old_path, new_path, file_id, ie) in delta:
1455
if old_path is not None:
1456
(index, old_subpath) = self._lookup_index(
1457
encode_git_path(old_path))
1458
if old_subpath in index:
1459
self._index_del_entry(index, old_subpath)
1460
self._versioned_dirs = None
1461
if new_path is not None and ie.kind != 'directory':
1462
self._index_add_entry(new_path, ie.kind)
1464
self._set_merges_from_parent_ids([])
1466
def move(self, from_paths, to_dir=None, after=None):
1468
with self.lock_tree_write():
1469
to_abs = self.abspath(to_dir)
1470
if not os.path.isdir(to_abs):
1471
raise errors.BzrMoveFailedError('', to_dir,
1472
errors.NotADirectory(to_abs))
1474
for from_rel in from_paths:
1475
from_tail = os.path.split(from_rel)[-1]
1476
to_rel = os.path.join(to_dir, from_tail)
1477
self.rename_one(from_rel, to_rel, after=after)
1478
rename_tuples.append((from_rel, to_rel))
1480
return rename_tuples
1482
def rename_one(self, from_rel, to_rel, after=None):
1483
from_path = encode_git_path(from_rel)
1484
to_rel, can_access = osutils.normalized_filename(to_rel)
1486
raise errors.InvalidNormalization(to_rel)
1487
to_path = encode_git_path(to_rel)
1488
with self.lock_tree_write():
1490
# Perhaps it's already moved?
1492
not self.has_filename(from_rel) and
1493
self.has_filename(to_rel) and
1494
not self.is_versioned(to_rel))
1496
if not self.has_filename(to_rel):
1497
raise errors.BzrMoveFailedError(
1498
from_rel, to_rel, errors.NoSuchFile(to_rel))
1499
if self.basis_tree().is_versioned(to_rel):
1500
raise errors.BzrMoveFailedError(
1501
from_rel, to_rel, errors.AlreadyVersionedError(to_rel))
1503
kind = self.kind(to_rel)
1506
to_kind = self.kind(to_rel)
1507
except errors.NoSuchFile:
1508
exc_type = errors.BzrRenameFailedError
1511
exc_type = errors.BzrMoveFailedError
1512
if self.is_versioned(to_rel):
1513
raise exc_type(from_rel, to_rel,
1514
errors.AlreadyVersionedError(to_rel))
1515
if not self.has_filename(from_rel):
1516
raise errors.BzrMoveFailedError(
1517
from_rel, to_rel, errors.NoSuchFile(from_rel))
1518
kind = self.kind(from_rel)
1519
if not self.is_versioned(from_rel) and kind != 'directory':
1520
raise exc_type(from_rel, to_rel,
1521
errors.NotVersionedError(from_rel))
1522
if self.has_filename(to_rel):
1523
raise errors.RenameFailedFilesExist(
1524
from_rel, to_rel, errors.FileExists(to_rel))
1526
kind = self.kind(from_rel)
1528
if not after and kind != 'directory':
1529
(index, from_subpath) = self._lookup_index(from_path)
1530
if from_subpath not in index:
1532
raise errors.BzrMoveFailedError(
1534
errors.NotVersionedError(path=from_rel))
1538
self._rename_one(from_rel, to_rel)
1539
except OSError as e:
1540
if e.errno == errno.ENOENT:
1541
raise errors.BzrMoveFailedError(
1542
from_rel, to_rel, errors.NoSuchFile(to_rel))
1544
if kind != 'directory':
1545
(index, from_index_path) = self._lookup_index(from_path)
1547
self._index_del_entry(index, from_path)
1550
self._index_add_entry(to_rel, kind)
1552
todo = [(p, i) for (p, i) in self._recurse_index_entries()
1553
if p.startswith(from_path + b'/')]
1554
for child_path, child_value in todo:
1555
(child_to_index, child_to_index_path) = self._lookup_index(
1556
posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
1557
child_to_index[child_to_index_path] = child_value
1558
# TODO(jelmer): Mark individual index as dirty
1559
self._index_dirty = True
1560
(child_from_index, child_from_index_path) = self._lookup_index(
1562
self._index_del_entry(
1563
child_from_index, child_from_index_path)
1565
self._versioned_dirs = None
1568
def find_related_paths_across_trees(self, paths, trees=[],
1569
require_versioned=True):
1573
if require_versioned:
1574
trees = [self] + (trees if trees is not None else [])
1578
if t.is_versioned(p):
1583
raise errors.PathsNotVersionedError(unversioned)
1585
return filter(self.is_versioned, paths)
1587
def path_content_summary(self, path):
1588
"""See Tree.path_content_summary."""
1590
stat_result = self._lstat(path)
1591
except OSError as e:
1592
if getattr(e, 'errno', None) == errno.ENOENT:
1594
return ('missing', None, None, None)
1595
# propagate other errors
1597
kind = mode_kind(stat_result.st_mode)
1599
return self._file_content_summary(path, stat_result)
1600
elif kind == 'directory':
1601
# perhaps it looks like a plain directory, but it's really a
1603
if self._directory_is_tree_reference(path):
1604
kind = 'tree-reference'
1605
return kind, None, None, None
1606
elif kind == 'symlink':
1607
target = osutils.readlink(self.abspath(path))
1608
return ('symlink', None, None, target)
1610
return (kind, None, None, None)
1612
def stored_kind(self, relpath):
1613
(index, index_path) = self._lookup_index(encode_git_path(relpath))
1617
mode = index[index_path].mode
1621
if S_ISGITLINK(mode):
1622
return 'tree-reference'
1625
def kind(self, relpath):
1626
kind = osutils.file_kind(self.abspath(relpath))
1627
if kind == 'directory':
1628
if self._directory_is_tree_reference(relpath):
1629
return 'tree-reference'
1634
def _live_entry(self, relpath):
1635
raise NotImplementedError(self._live_entry)
1637
def transform(self, pb=None):
1638
from .transform import GitTreeTransform
1639
return GitTreeTransform(self, pb=pb)
1641
def preview_transform(self, pb=None):
1642
from .transform import GitTransformPreview
1643
return GitTransformPreview(self, pb=pb)
1646
class InterToIndexGitTree(InterGitTrees):
1647
"""InterTree that works between a Git revision tree and an index."""
1649
def __init__(self, source, target):
1650
super(InterToIndexGitTree, self).__init__(source, target)
1651
if self.source.store == self.target.store:
1652
self.store = self.source.store
1654
self.store = OverlayObjectStore(
1655
[self.source.store, self.target.store])
1656
self.rename_detector = RenameDetector(self.store)
1659
def is_compatible(cls, source, target):
1660
return (isinstance(source, GitRevisionTree) and
1661
isinstance(target, MutableGitIndexTree))
1663
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1664
require_versioned=False, extra_trees=None,
1665
want_unversioned=False, include_trees=True):
1666
trees = [self.source]
1667
if extra_trees is not None:
1668
trees.extend(extra_trees)
1669
if specific_files is not None:
1670
specific_files = self.target.find_related_paths_across_trees(
1671
specific_files, trees,
1672
require_versioned=require_versioned)
1673
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1674
with self.lock_read():
1675
changes, target_extras = changes_between_git_tree_and_working_copy(
1676
self.source.store, self.source.tree,
1677
self.target, want_unchanged=want_unchanged,
1678
want_unversioned=want_unversioned,
1679
rename_detector=self.rename_detector,
1680
include_trees=include_trees)
1681
return changes, set(), target_extras
1684
_mod_tree.InterTree.register_optimiser(InterToIndexGitTree)
1687
class InterFromIndexGitTree(InterGitTrees):
1688
"""InterTree that works between a Git revision tree and an index."""
1690
def __init__(self, source, target):
1691
super(InterFromIndexGitTree, self).__init__(source, target)
1692
if self.source.store == self.target.store:
1693
self.store = self.source.store
1695
self.store = OverlayObjectStore(
1696
[self.source.store, self.target.store])
1697
self.rename_detector = RenameDetector(self.store)
1700
def is_compatible(cls, source, target):
1701
return (isinstance(target, GitRevisionTree) and
1702
isinstance(source, MutableGitIndexTree))
1704
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1705
require_versioned=False, extra_trees=None,
1706
want_unversioned=False, include_trees=True):
1707
trees = [self.source]
1708
if extra_trees is not None:
1709
trees.extend(extra_trees)
1710
if specific_files is not None:
1711
specific_files = self.target.find_related_paths_across_trees(
1712
specific_files, trees,
1713
require_versioned=require_versioned)
1714
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1715
with self.lock_read():
1716
from_tree_sha, extras = snapshot_workingtree(self.source, want_unversioned=want_unversioned)
1717
return tree_changes(
1718
self.store, from_tree_sha, self.target.tree,
1719
include_trees=include_trees,
1720
rename_detector=self.rename_detector,
1721
want_unchanged=want_unchanged, change_type_same=True), extras
1724
_mod_tree.InterTree.register_optimiser(InterFromIndexGitTree)
1727
class InterIndexGitTree(InterGitTrees):
1728
"""InterTree that works between a Git revision tree and an index."""
1730
def __init__(self, source, target):
1731
super(InterIndexGitTree, self).__init__(source, target)
1732
if self.source.store == self.target.store:
1733
self.store = self.source.store
1735
self.store = OverlayObjectStore(
1736
[self.source.store, self.target.store])
1737
self.rename_detector = RenameDetector(self.store)
1740
def is_compatible(cls, source, target):
1741
return (isinstance(target, MutableGitIndexTree) and
1742
isinstance(source, MutableGitIndexTree))
1744
def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1745
require_versioned=False, extra_trees=None,
1746
want_unversioned=False, include_trees=True):
1747
trees = [self.source]
1748
if extra_trees is not None:
1749
trees.extend(extra_trees)
1750
if specific_files is not None:
1751
specific_files = self.target.find_related_paths_across_trees(
1752
specific_files, trees,
1753
require_versioned=require_versioned)
1754
# TODO(jelmer): Restrict to specific_files, for performance reasons.
1755
with self.lock_read():
1756
from_tree_sha, from_extras = snapshot_workingtree(
1757
self.source, want_unversioned=want_unversioned)
1758
to_tree_sha, to_extras = snapshot_workingtree(
1759
self.target, want_unversioned=want_unversioned)
1760
changes = tree_changes(
1761
self.store, from_tree_sha, to_tree_sha,
1762
include_trees=include_trees,
1763
rename_detector=self.rename_detector,
1764
want_unchanged=want_unchanged, change_type_same=True)
1765
return changes, from_extras, to_extras
1768
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
1771
def snapshot_workingtree(target, want_unversioned=False):
1774
# Report dirified directories to commit_tree first, so that they can be
1775
# replaced with non-empty directories if they have contents.
1777
trust_executable = target._supports_executable()
1778
for path, index_entry in target._recurse_index_entries():
1780
live_entry = target._live_entry(path)
1781
except EnvironmentError as e:
1782
if e.errno == errno.ENOENT:
1783
# Entry was removed; keep it listed, but mark it as gone.
1784
blobs[path] = (ZERO_SHA, 0)
1788
if live_entry is None:
1789
# Entry was turned into a directory.
1790
# Maybe it's just a submodule that's not checked out?
1791
if S_ISGITLINK(index_entry.mode):
1792
blobs[path] = (index_entry.sha, index_entry.mode)
1794
dirified.append((path, Tree().id, stat.S_IFDIR))
1795
target.store.add_object(Tree())
1797
mode = live_entry.mode
1798
if not trust_executable:
1799
if mode_is_executable(index_entry.mode):
1803
if live_entry.sha != index_entry.sha:
1804
rp = decode_git_path(path)
1805
if stat.S_ISREG(live_entry.mode):
1807
with target.get_file(rp) as f:
1808
blob.data = f.read()
1809
elif stat.S_ISLNK(live_entry.mode):
1811
blob.data = target.get_symlink_target(rp).encode(osutils._fs_enc)
1814
if blob is not None:
1815
target.store.add_object(blob)
1816
blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1817
if want_unversioned:
1818
for e in target._iter_files_recursive(include_dirs=False):
1820
e, accessible = osutils.normalized_filename(e)
1821
except UnicodeDecodeError:
1822
raise errors.BadFilenameEncoding(
1824
np = encode_git_path(e)
1827
st = target._lstat(e)
1828
if stat.S_ISDIR(st.st_mode):
1830
elif stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode):
1831
blob = blob_from_path_and_stat(
1832
target.abspath(e).encode(osutils._fs_enc), st)
1835
target.store.add_object(blob)
1836
blobs[np] = (blob.id, cleanup_mode(st.st_mode))
1839
target.store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()]), extras
1842
def changes_between_git_tree_and_working_copy(source_store, from_tree_sha, target,
1843
want_unchanged=False,
1844
want_unversioned=False,
1845
rename_detector=None,
1846
include_trees=True):
1847
"""Determine the changes between a git tree and a working tree with index.
1850
to_tree_sha, extras = snapshot_workingtree(target, want_unversioned=want_unversioned)
1851
store = OverlayObjectStore([source_store, target.store])
1852
return tree_changes(
1853
store, from_tree_sha, to_tree_sha, include_trees=include_trees,
1854
rename_detector=rename_detector,
1855
want_unchanged=want_unchanged, change_type_same=True), extras