/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/git/tree.py

  • Committer: Breezy landing bot
  • Author(s): Jelmer Vernooij
  • Date: 2020-08-23 01:15:41 UTC
  • mfrom: (7520.1.4 merge-3.1)
  • Revision ID: breezy.the.bot@gmail.com-20200823011541-nv0oh7nzaganx2qy
Merge lp:brz/3.1.

Merged from https://code.launchpad.net/~jelmer/brz/merge-3.1/+merge/389690

Show diffs side-by-side

added added

removed removed

Lines of Context:
76
76
    TransportObjectStore,
77
77
    TransportRepo,
78
78
    )
 
79
from ..bzr.inventorytree import InventoryTreeChange
79
80
 
80
81
 
81
82
class GitTreeDirectory(_mod_tree.TreeDirectory):
82
83
 
83
 
    __slots__ = ['file_id', 'name', 'parent_id', 'children']
 
84
    __slots__ = ['file_id', 'name', 'parent_id']
84
85
 
85
86
    def __init__(self, file_id, name, parent_id):
86
87
        self.file_id = file_id
87
88
        self.name = name
88
89
        self.parent_id = parent_id
89
 
        # TODO(jelmer)
90
 
        self.children = {}
91
90
 
92
91
    @property
93
92
    def kind(self):
115
114
 
116
115
class GitTreeFile(_mod_tree.TreeFile):
117
116
 
118
 
    __slots__ = ['file_id', 'name', 'parent_id', 'text_size', 'text_sha1',
119
 
                 'executable']
 
117
    __slots__ = ['file_id', 'name', 'parent_id', 'text_size',
 
118
                 'executable', 'git_sha1']
120
119
 
121
120
    def __init__(self, file_id, name, parent_id, text_size=None,
122
 
                 text_sha1=None, executable=None):
 
121
                 git_sha1=None, executable=None):
123
122
        self.file_id = file_id
124
123
        self.name = name
125
124
        self.parent_id = parent_id
126
125
        self.text_size = text_size
127
 
        self.text_sha1 = text_sha1
 
126
        self.git_sha1 = git_sha1
128
127
        self.executable = executable
129
128
 
130
129
    @property
136
135
                self.file_id == other.file_id and
137
136
                self.name == other.name and
138
137
                self.parent_id == other.parent_id and
139
 
                self.text_sha1 == other.text_sha1 and
 
138
                self.git_sha1 == other.git_sha1 and
140
139
                self.text_size == other.text_size and
141
140
                self.executable == other.executable)
142
141
 
143
142
    def __repr__(self):
144
143
        return ("%s(file_id=%r, name=%r, parent_id=%r, text_size=%r, "
145
 
                "text_sha1=%r, executable=%r)") % (
 
144
                "git_sha1=%r, executable=%r)") % (
146
145
            type(self).__name__, self.file_id, self.name, self.parent_id,
147
 
            self.text_size, self.text_sha1, self.executable)
 
146
            self.text_size, self.git_sha1, self.executable)
148
147
 
149
148
    def copy(self):
150
149
        ret = self.__class__(
151
150
            self.file_id, self.name, self.parent_id)
152
 
        ret.text_sha1 = self.text_sha1
 
151
        ret.git_sha1 = self.git_sha1
153
152
        ret.text_size = self.text_size
154
153
        ret.executable = self.executable
155
154
        return ret
257
256
    return path
258
257
 
259
258
 
260
 
class GitRevisionTree(revisiontree.RevisionTree):
 
259
class GitTree(_mod_tree.Tree):
 
260
 
 
261
    def iter_git_objects(self):
 
262
        """Iterate over all the objects in the tree.
 
263
 
 
264
        :return :Yields tuples with (path, sha, mode)
 
265
        """
 
266
        raise NotImplementedError(self.iter_git_objects)
 
267
 
 
268
    def git_snapshot(self, want_unversioned=False):
 
269
        """Snapshot a tree, and return tree object.
 
270
 
 
271
        :return: Tree sha and set of extras
 
272
        """
 
273
        raise NotImplementedError(self.snapshot)
 
274
 
 
275
    def preview_transform(self, pb=None):
 
276
        from .transform import GitTransformPreview
 
277
        return GitTransformPreview(self, pb=pb)
 
278
 
 
279
    def find_related_paths_across_trees(self, paths, trees=[],
 
280
                                        require_versioned=True):
 
281
        if paths is None:
 
282
            return None
 
283
        if require_versioned:
 
284
            trees = [self] + (trees if trees is not None else [])
 
285
            unversioned = set()
 
286
            for p in paths:
 
287
                for t in trees:
 
288
                    if t.is_versioned(p):
 
289
                        break
 
290
                else:
 
291
                    unversioned.add(p)
 
292
            if unversioned:
 
293
                raise errors.PathsNotVersionedError(unversioned)
 
294
        return filter(self.is_versioned, paths)
 
295
 
 
296
    def _submodule_info(self):
 
297
        if self._submodules is None:
 
298
            try:
 
299
                with self.get_file('.gitmodules') as f:
 
300
                    config = GitConfigFile.from_file(f)
 
301
                    self._submodules = {
 
302
                        path: (url, section)
 
303
                        for path, url, section in parse_submodules(config)}
 
304
            except errors.NoSuchFile:
 
305
                self._submodules = {}
 
306
        return self._submodules
 
307
 
 
308
 
 
309
class GitRevisionTree(revisiontree.RevisionTree, GitTree):
261
310
    """Revision tree implementation based on Git objects."""
262
311
 
263
312
    def __init__(self, repository, revision_id):
279
328
                raise errors.NoSuchRevision(repository, revision_id)
280
329
            self.tree = commit.tree
281
330
 
282
 
    def _submodule_info(self):
283
 
        if self._submodules is None:
284
 
            try:
285
 
                with self.get_file('.gitmodules') as f:
286
 
                    config = GitConfigFile.from_file(f)
287
 
                    self._submodules = {
288
 
                        path: (url, section)
289
 
                        for path, url, section in parse_submodules(config)}
290
 
            except errors.NoSuchFile:
291
 
                self._submodules = {}
292
 
        return self._submodules
 
331
    def git_snapshot(self, want_unversioned=False):
 
332
        return self.tree, set()
293
333
 
294
334
    def _get_submodule_repository(self, relpath):
295
335
        if not isinstance(relpath, bytes):
421
461
        else:
422
462
            return True
423
463
 
424
 
    def _submodule_info(self):
425
 
        if self._submodules is None:
426
 
            try:
427
 
                with self.get_file('.gitmodules') as f:
428
 
                    config = GitConfigFile.from_file(f)
429
 
                    self._submodules = {
430
 
                        path: (url, section)
431
 
                        for path, url, section in parse_submodules(config)}
432
 
            except errors.NoSuchFile:
433
 
                self._submodules = {}
434
 
        return self._submodules
435
 
 
436
464
    def list_files(self, include_root=False, from_dir=None, recursive=True,
437
465
                   recurse_nested=False):
438
466
        if self.tree is None:
496
524
            ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(
497
525
                hexsha)
498
526
        else:
499
 
            data = store[hexsha].data
500
 
            ie.text_sha1 = osutils.sha_string(data)
501
 
            ie.text_size = len(data)
 
527
            ie.git_sha1 = hexsha
 
528
            ie.text_size = None
502
529
            ie.executable = mode_is_executable(mode)
503
530
        return ie
504
531
 
649
676
        else:
650
677
            return (kind, None, None, None)
651
678
 
652
 
    def find_related_paths_across_trees(self, paths, trees=[],
653
 
                                        require_versioned=True):
654
 
        if paths is None:
655
 
            return None
656
 
        if require_versioned:
657
 
            trees = [self] + (trees if trees is not None else [])
658
 
            unversioned = set()
659
 
            for p in paths:
660
 
                for t in trees:
661
 
                    if t.is_versioned(p):
662
 
                        break
663
 
                else:
664
 
                    unversioned.add(p)
665
 
            if unversioned:
666
 
                raise errors.PathsNotVersionedError(unversioned)
667
 
        return filter(self.is_versioned, paths)
668
 
 
669
679
    def _iter_tree_contents(self, include_trees=False):
670
680
        if self.tree is None:
671
681
            return iter([])
699
709
    def walkdirs(self, prefix=u""):
700
710
        (store, mode, hexsha) = self._lookup_path(prefix)
701
711
        todo = deque(
702
 
            [(store, encode_git_path(prefix), hexsha, self.path2id(prefix))])
 
712
            [(store, encode_git_path(prefix), hexsha)])
703
713
        while todo:
704
 
            store, path, tree_sha, parent_id = todo.popleft()
 
714
            store, path, tree_sha = todo.popleft()
705
715
            path_decoded = decode_git_path(path)
706
716
            tree = store[tree_sha]
707
717
            children = []
709
719
                if self.mapping.is_special_file(name):
710
720
                    continue
711
721
                child_path = posixpath.join(path, name)
712
 
                file_id = self.path2id(decode_git_path(child_path))
713
722
                if stat.S_ISDIR(mode):
714
 
                    todo.append((store, child_path, hexsha, file_id))
 
723
                    todo.append((store, child_path, hexsha))
715
724
                children.append(
716
725
                    (decode_git_path(child_path), decode_git_path(name),
717
726
                        mode_kind(mode), None,
718
 
                        file_id, mode_kind(mode)))
719
 
            yield (path_decoded, parent_id), children
720
 
 
721
 
    def preview_transform(self, pb=None):
722
 
        from .transform import GitTransformPreview
723
 
        return GitTransformPreview(self, pb=pb)
 
727
                        mode_kind(mode)))
 
728
            yield path_decoded, children
724
729
 
725
730
 
726
731
def tree_delta_from_git_changes(changes, mappings,
814
819
            newpath = None
815
820
        if oldpath is None and newpath is None:
816
821
            continue
817
 
        change = _mod_tree.TreeChange(
 
822
        change = InventoryTreeChange(
818
823
            fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
819
824
            (oldversioned, newversioned),
820
825
            (oldparent, newparent), (oldname, newname),
860
865
        parent_id = new_mapping.generate_file_id(parent_path)
861
866
        file_id = new_mapping.generate_file_id(path_decoded)
862
867
        ret.added.append(
863
 
            _mod_tree.TreeChange(
 
868
            InventoryTreeChange(
864
869
                file_id, (None, path_decoded), True,
865
870
                (False, True),
866
871
                (None, parent_id),
956
961
            fileid = mapping.generate_file_id(newpath_decoded)
957
962
        else:
958
963
            fileid = None
959
 
        yield _mod_tree.TreeChange(
960
 
            fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
 
964
        if oldkind == 'directory' and newkind == 'directory':
 
965
            modified = False
 
966
        else:
 
967
            modified = (oldsha != newsha) or (oldmode != newmode)
 
968
        yield InventoryTreeChange(
 
969
            fileid, (oldpath_decoded, newpath_decoded),
 
970
            modified,
961
971
            (oldversioned, newversioned),
962
972
            (oldparent, newparent), (oldname, newname),
963
973
            (oldkind, newkind), (oldexe, newexe),
971
981
    _matching_to_tree_format = None
972
982
    _test_mutable_trees_to_test_trees = None
973
983
 
 
984
    def __init__(self, source, target):
 
985
        super(InterGitTrees, self).__init__(source, target)
 
986
        if self.source.store == self.target.store:
 
987
            self.store = self.source.store
 
988
        else:
 
989
            self.store = OverlayObjectStore(
 
990
                [self.source.store, self.target.store])
 
991
        self.rename_detector = RenameDetector(self.store)
 
992
 
974
993
    @classmethod
975
994
    def is_compatible(cls, source, target):
976
 
        return (isinstance(source, GitRevisionTree) and
977
 
                isinstance(target, GitRevisionTree))
 
995
        return isinstance(source, GitTree) and isinstance(target, GitTree)
978
996
 
979
997
    def compare(self, want_unchanged=False, specific_files=None,
980
998
                extra_trees=None, require_versioned=False, include_root=False,
1012
1030
    def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1013
1031
                          require_versioned=False, extra_trees=None,
1014
1032
                          want_unversioned=False, include_trees=True):
1015
 
        raise NotImplementedError(self._iter_git_changes)
 
1033
        trees = [self.source]
 
1034
        if extra_trees is not None:
 
1035
            trees.extend(extra_trees)
 
1036
        if specific_files is not None:
 
1037
            specific_files = self.target.find_related_paths_across_trees(
 
1038
                specific_files, trees,
 
1039
                require_versioned=require_versioned)
 
1040
        # TODO(jelmer): Restrict to specific_files, for performance reasons.
 
1041
        with self.lock_read():
 
1042
            from_tree_sha, from_extras = self.source.git_snapshot(
 
1043
                want_unversioned=want_unversioned)
 
1044
            to_tree_sha, to_extras = self.target.git_snapshot(
 
1045
                want_unversioned=want_unversioned)
 
1046
            changes = tree_changes(
 
1047
                self.store, from_tree_sha, to_tree_sha,
 
1048
                include_trees=include_trees,
 
1049
                rename_detector=self.rename_detector,
 
1050
                want_unchanged=want_unchanged, change_type_same=True)
 
1051
            return changes, from_extras, to_extras
1016
1052
 
1017
1053
    def find_target_path(self, path, recurse='none'):
1018
1054
        ret = self.find_target_paths([path], recurse=recurse)
1067
1103
        return ret
1068
1104
 
1069
1105
 
1070
 
class InterGitRevisionTrees(InterGitTrees):
1071
 
    """InterTree that works between two git revision trees."""
1072
 
 
1073
 
    _matching_from_tree_format = None
1074
 
    _matching_to_tree_format = None
1075
 
    _test_mutable_trees_to_test_trees = None
1076
 
 
1077
 
    @classmethod
1078
 
    def is_compatible(cls, source, target):
1079
 
        return (isinstance(source, GitRevisionTree) and
1080
 
                isinstance(target, GitRevisionTree))
1081
 
 
1082
 
    def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1083
 
                          require_versioned=True, extra_trees=None,
1084
 
                          want_unversioned=False, include_trees=True):
1085
 
        trees = [self.source]
1086
 
        if extra_trees is not None:
1087
 
            trees.extend(extra_trees)
1088
 
        if specific_files is not None:
1089
 
            specific_files = self.target.find_related_paths_across_trees(
1090
 
                specific_files, trees,
1091
 
                require_versioned=require_versioned)
1092
 
 
1093
 
        if (self.source._repository._git.object_store !=
1094
 
                self.target._repository._git.object_store):
1095
 
            store = OverlayObjectStore(
1096
 
                [self.source._repository._git.object_store,
1097
 
                    self.target._repository._git.object_store])
1098
 
        else:
1099
 
            store = self.source._repository._git.object_store
1100
 
        rename_detector = RenameDetector(store)
1101
 
        changes = tree_changes(
1102
 
            store, self.source.tree, self.target.tree,
1103
 
            want_unchanged=want_unchanged, include_trees=include_trees,
1104
 
            change_type_same=True, rename_detector=rename_detector)
1105
 
        return changes, set(), set()
1106
 
 
1107
 
 
1108
 
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
1109
 
 
1110
 
 
1111
 
class MutableGitIndexTree(mutabletree.MutableTree):
 
1106
_mod_tree.InterTree.register_optimiser(InterGitTrees)
 
1107
 
 
1108
 
 
1109
class MutableGitIndexTree(mutabletree.MutableTree, GitTree):
1112
1110
 
1113
1111
    def __init__(self):
1114
1112
        self._lock_mode = None
1117
1115
        self._index_dirty = False
1118
1116
        self._submodules = None
1119
1117
 
 
1118
    def git_snapshot(self, want_unversioned=False):
 
1119
        return snapshot_workingtree(self, want_unversioned=want_unversioned)
 
1120
 
1120
1121
    def is_versioned(self, path):
1121
1122
        with self.lock_read():
1122
1123
            path = encode_git_path(path.rstrip('/'))
1136
1137
        if self._lock_mode is None:
1137
1138
            raise errors.ObjectNotLocked(self)
1138
1139
        self._versioned_dirs = set()
1139
 
        for p, i in self._recurse_index_entries():
 
1140
        for p, sha, mode in self.iter_git_objects():
1140
1141
            self._ensure_versioned_dir(posixpath.dirname(p))
1141
1142
 
1142
1143
    def _ensure_versioned_dir(self, dirname):
1185
1186
    def _read_submodule_head(self, path):
1186
1187
        raise NotImplementedError(self._read_submodule_head)
1187
1188
 
1188
 
    def _submodule_info(self):
1189
 
        if self._submodules is None:
1190
 
            try:
1191
 
                with self.get_file('.gitmodules') as f:
1192
 
                    config = GitConfigFile.from_file(f)
1193
 
                    self._submodules = {
1194
 
                        path: (url, section)
1195
 
                        for path, url, section in parse_submodules(config)}
1196
 
            except errors.NoSuchFile:
1197
 
                self._submodules = {}
1198
 
        return self._submodules
1199
 
 
1200
1189
    def _lookup_index(self, encoded_path):
1201
1190
        if not isinstance(encoded_path, bytes):
1202
1191
            raise TypeError(encoded_path)
1232
1221
        # TODO(jelmer): Keep track of dirty per index
1233
1222
        self._index_dirty = True
1234
1223
 
1235
 
    def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
 
1224
    def _apply_index_changes(self, changes):
 
1225
        for (path, kind, executability, reference_revision,
 
1226
             symlink_target) in changes:
 
1227
            if kind is None or kind == 'directory':
 
1228
                (index, subpath) = self._lookup_index(
 
1229
                    encode_git_path(path))
 
1230
                try:
 
1231
                    self._index_del_entry(index, subpath)
 
1232
                except KeyError:
 
1233
                    pass
 
1234
                else:
 
1235
                    self._versioned_dirs = None
 
1236
            else:
 
1237
                self._index_add_entry(
 
1238
                    path, kind,
 
1239
                    reference_revision=reference_revision,
 
1240
                    symlink_target=symlink_target)
 
1241
        self.flush()
 
1242
 
 
1243
    def _index_add_entry(
 
1244
            self, path, kind, flags=0, reference_revision=None,
 
1245
            symlink_target=None):
1236
1246
        if kind == "directory":
1237
1247
            # Git indexes don't contain directories
1238
1248
            return
1239
 
        if kind == "file":
 
1249
        elif kind == "file":
1240
1250
            blob = Blob()
1241
1251
            try:
1242
1252
                file, stat_val = self.get_file_with_stat(path)
1261
1271
                # old index
1262
1272
                stat_val = os.stat_result(
1263
1273
                    (stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
1264
 
            blob.set_raw_string(encode_git_path(self.get_symlink_target(path)))
 
1274
            if symlink_target is None:
 
1275
                symlink_target = self.get_symlink_target(path)
 
1276
            blob.set_raw_string(encode_git_path(symlink_target))
1265
1277
            # Add object to the repository if it didn't exist yet
1266
1278
            if blob.id not in self.store:
1267
1279
                self.store.add_object(blob)
1295
1307
        if self._versioned_dirs is not None:
1296
1308
            self._ensure_versioned_dir(index_path)
1297
1309
 
 
1310
    def iter_git_objects(self):
 
1311
        for p, entry in self._recurse_index_entries():
 
1312
            yield p, entry.sha, entry.mode
 
1313
 
1298
1314
    def _recurse_index_entries(self, index=None, basepath=b"",
1299
1315
                               recurse_nested=False):
1300
1316
        # Iterate over all index entries
1381
1397
        elif kind == 'tree-reference':
1382
1398
            ie.reference_revision = self.get_reference_revision(path)
1383
1399
        else:
1384
 
            try:
1385
 
                data = self.get_file_text(path)
1386
 
            except errors.NoSuchFile:
1387
 
                data = None
1388
 
            except IOError as e:
1389
 
                if e.errno != errno.ENOENT:
1390
 
                    raise
1391
 
                data = None
1392
 
            if data is None:
1393
 
                data = self.branch.repository._git.object_store[sha].data
1394
 
            ie.text_sha1 = osutils.sha_string(data)
1395
 
            ie.text_size = len(data)
 
1400
            ie.git_sha1 = sha
 
1401
            ie.text_size = size
1396
1402
            ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1397
1403
        return ie
1398
1404
 
1559
1565
            self._versioned_dirs = None
1560
1566
            self.flush()
1561
1567
 
1562
 
    def find_related_paths_across_trees(self, paths, trees=[],
1563
 
                                        require_versioned=True):
1564
 
        if paths is None:
1565
 
            return None
1566
 
 
1567
 
        if require_versioned:
1568
 
            trees = [self] + (trees if trees is not None else [])
1569
 
            unversioned = set()
1570
 
            for p in paths:
1571
 
                for t in trees:
1572
 
                    if t.is_versioned(p):
1573
 
                        break
1574
 
                else:
1575
 
                    unversioned.add(p)
1576
 
            if unversioned:
1577
 
                raise errors.PathsNotVersionedError(unversioned)
1578
 
 
1579
 
        return filter(self.is_versioned, paths)
1580
 
 
1581
1568
    def path_content_summary(self, path):
1582
1569
        """See Tree.path_content_summary."""
1583
1570
        try:
1604
1591
            return (kind, None, None, None)
1605
1592
 
1606
1593
    def stored_kind(self, relpath):
 
1594
        if relpath == '':
 
1595
            return 'directory'
1607
1596
        (index, index_path) = self._lookup_index(encode_git_path(relpath))
1608
1597
        if index is None:
1609
 
            return kind
 
1598
            return None
1610
1599
        try:
1611
1600
            mode = index[index_path].mode
1612
1601
        except KeyError:
1613
 
            return kind
 
1602
            for p in index:
 
1603
                if osutils.is_inside(
 
1604
                        decode_git_path(index_path), decode_git_path(p)):
 
1605
                    return 'directory'
 
1606
            return None
1614
1607
        else:
1615
 
            if S_ISGITLINK(mode):
1616
 
                return 'tree-reference'
1617
 
            return 'directory'
 
1608
            return mode_kind(mode)
1618
1609
 
1619
1610
    def kind(self, relpath):
1620
1611
        kind = osutils.file_kind(self.abspath(relpath))
1632
1623
        from .transform import GitTreeTransform
1633
1624
        return GitTreeTransform(self, pb=pb)
1634
1625
 
1635
 
    def preview_transform(self, pb=None):
1636
 
        from .transform import GitTransformPreview
1637
 
        return GitTransformPreview(self, pb=pb)
1638
 
 
1639
 
 
1640
 
class InterToIndexGitTree(InterGitTrees):
1641
 
    """InterTree that works between a Git revision tree and an index."""
1642
 
 
1643
 
    def __init__(self, source, target):
1644
 
        super(InterToIndexGitTree, self).__init__(source, target)
1645
 
        if self.source.store == self.target.store:
1646
 
            self.store = self.source.store
1647
 
        else:
1648
 
            self.store = OverlayObjectStore(
1649
 
                [self.source.store, self.target.store])
1650
 
        self.rename_detector = RenameDetector(self.store)
1651
 
 
1652
 
    @classmethod
1653
 
    def is_compatible(cls, source, target):
1654
 
        return (isinstance(source, GitRevisionTree) and
1655
 
                isinstance(target, MutableGitIndexTree))
1656
 
 
1657
 
    def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1658
 
                          require_versioned=False, extra_trees=None,
1659
 
                          want_unversioned=False, include_trees=True):
1660
 
        trees = [self.source]
1661
 
        if extra_trees is not None:
1662
 
            trees.extend(extra_trees)
1663
 
        if specific_files is not None:
1664
 
            specific_files = self.target.find_related_paths_across_trees(
1665
 
                specific_files, trees,
1666
 
                require_versioned=require_versioned)
1667
 
        # TODO(jelmer): Restrict to specific_files, for performance reasons.
1668
 
        with self.lock_read():
1669
 
            changes, target_extras = changes_between_git_tree_and_working_copy(
1670
 
                self.source.store, self.source.tree,
1671
 
                self.target, want_unchanged=want_unchanged,
1672
 
                want_unversioned=want_unversioned,
1673
 
                rename_detector=self.rename_detector,
1674
 
                include_trees=include_trees)
1675
 
            return changes, set(), target_extras
1676
 
 
1677
 
 
1678
 
_mod_tree.InterTree.register_optimiser(InterToIndexGitTree)
1679
 
 
1680
 
 
1681
 
class InterFromIndexGitTree(InterGitTrees):
1682
 
    """InterTree that works between a Git revision tree and an index."""
1683
 
 
1684
 
    def __init__(self, source, target):
1685
 
        super(InterFromIndexGitTree, self).__init__(source, target)
1686
 
        if self.source.store == self.target.store:
1687
 
            self.store = self.source.store
1688
 
        else:
1689
 
            self.store = OverlayObjectStore(
1690
 
                [self.source.store, self.target.store])
1691
 
        self.rename_detector = RenameDetector(self.store)
1692
 
 
1693
 
    @classmethod
1694
 
    def is_compatible(cls, source, target):
1695
 
        return (isinstance(target, GitRevisionTree) and
1696
 
                isinstance(source, MutableGitIndexTree))
1697
 
 
1698
 
    def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1699
 
                          require_versioned=False, extra_trees=None,
1700
 
                          want_unversioned=False, include_trees=True):
1701
 
        trees = [self.source]
1702
 
        if extra_trees is not None:
1703
 
            trees.extend(extra_trees)
1704
 
        if specific_files is not None:
1705
 
            specific_files = self.target.find_related_paths_across_trees(
1706
 
                specific_files, trees,
1707
 
                require_versioned=require_versioned)
1708
 
        # TODO(jelmer): Restrict to specific_files, for performance reasons.
1709
 
        with self.lock_read():
1710
 
            from_tree_sha, extras = snapshot_workingtree(self.source, want_unversioned=want_unversioned)
1711
 
            return tree_changes(
1712
 
                self.store, from_tree_sha, self.target.tree,
1713
 
                include_trees=include_trees,
1714
 
                rename_detector=self.rename_detector,
1715
 
                want_unchanged=want_unchanged, change_type_same=True), extras
1716
 
 
1717
 
 
1718
 
_mod_tree.InterTree.register_optimiser(InterFromIndexGitTree)
1719
 
 
1720
 
 
1721
 
class InterIndexGitTree(InterGitTrees):
1722
 
    """InterTree that works between a Git revision tree and an index."""
1723
 
 
1724
 
    def __init__(self, source, target):
1725
 
        super(InterIndexGitTree, self).__init__(source, target)
1726
 
        if self.source.store == self.target.store:
1727
 
            self.store = self.source.store
1728
 
        else:
1729
 
            self.store = OverlayObjectStore(
1730
 
                [self.source.store, self.target.store])
1731
 
        self.rename_detector = RenameDetector(self.store)
1732
 
 
1733
 
    @classmethod
1734
 
    def is_compatible(cls, source, target):
1735
 
        return (isinstance(target, MutableGitIndexTree) and
1736
 
                isinstance(source, MutableGitIndexTree))
1737
 
 
1738
 
    def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1739
 
                          require_versioned=False, extra_trees=None,
1740
 
                          want_unversioned=False, include_trees=True):
1741
 
        trees = [self.source]
1742
 
        if extra_trees is not None:
1743
 
            trees.extend(extra_trees)
1744
 
        if specific_files is not None:
1745
 
            specific_files = self.target.find_related_paths_across_trees(
1746
 
                specific_files, trees,
1747
 
                require_versioned=require_versioned)
1748
 
        # TODO(jelmer): Restrict to specific_files, for performance reasons.
1749
 
        with self.lock_read():
1750
 
            from_tree_sha, from_extras = snapshot_workingtree(
1751
 
                self.source, want_unversioned=want_unversioned)
1752
 
            to_tree_sha, to_extras = snapshot_workingtree(
1753
 
                self.target, want_unversioned=want_unversioned)
1754
 
            changes = tree_changes(
1755
 
                self.store, from_tree_sha, to_tree_sha,
1756
 
                include_trees=include_trees,
1757
 
                rename_detector=self.rename_detector,
1758
 
                want_unchanged=want_unchanged, change_type_same=True)
1759
 
            return changes, from_extras, to_extras
1760
 
 
1761
 
 
1762
 
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
 
1626
    def has_changes(self, _from_tree=None):
 
1627
        """Quickly check that the tree contains at least one commitable change.
 
1628
 
 
1629
        :param _from_tree: tree to compare against to find changes (default to
 
1630
            the basis tree and is intended to be used by tests).
 
1631
 
 
1632
        :return: True if a change is found. False otherwise
 
1633
        """
 
1634
        with self.lock_read():
 
1635
            # Check pending merges
 
1636
            if len(self.get_parent_ids()) > 1:
 
1637
                return True
 
1638
            if _from_tree is None:
 
1639
                _from_tree = self.basis_tree()
 
1640
            changes = self.iter_changes(_from_tree)
 
1641
            if self.supports_symlinks():
 
1642
                # Fast path for has_changes.
 
1643
                try:
 
1644
                    change = next(changes)
 
1645
                    if change.path[1] == '':
 
1646
                        next(changes)
 
1647
                    return True
 
1648
                except StopIteration:
 
1649
                    # No changes
 
1650
                    return False
 
1651
            else:
 
1652
                # Slow path for has_changes.
 
1653
                # Handle platforms that do not support symlinks in the
 
1654
                # conditional below. This is slower than the try/except
 
1655
                # approach below that but we don't have a choice as we
 
1656
                # need to be sure that all symlinks are removed from the
 
1657
                # entire changeset. This is because in platforms that
 
1658
                # do not support symlinks, they show up as None in the
 
1659
                # working copy as compared to the repository.
 
1660
                # Also, exclude root as mention in the above fast path.
 
1661
                changes = filter(
 
1662
                    lambda c: c[6][0] != 'symlink' and c[4] != (None, None),
 
1663
                    changes)
 
1664
                try:
 
1665
                    next(iter(changes))
 
1666
                except StopIteration:
 
1667
                    return False
 
1668
                return True
1763
1669
 
1764
1670
 
1765
1671
def snapshot_workingtree(target, want_unversioned=False):
1809
1715
                        target.store.add_object(blob)
1810
1716
                blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
1811
1717
    if want_unversioned:
1812
 
        for e in target._iter_files_recursive(include_dirs=False):
 
1718
        for extra in target._iter_files_recursive(include_dirs=False):
1813
1719
            try:
1814
 
                e, accessible = osutils.normalized_filename(e)
 
1720
                extra, accessible = osutils.normalized_filename(extra)
1815
1721
            except UnicodeDecodeError:
1816
1722
                raise errors.BadFilenameEncoding(
1817
 
                    e, osutils._fs_enc)
1818
 
            np = encode_git_path(e)
 
1723
                    extra, osutils._fs_enc)
 
1724
            np = encode_git_path(extra)
1819
1725
            if np in blobs:
1820
1726
                continue
1821
 
            st = target._lstat(e)
 
1727
            st = target._lstat(extra)
1822
1728
            if stat.S_ISDIR(st.st_mode):
1823
1729
                blob = Tree()
1824
1730
            elif stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode):
1825
1731
                blob = blob_from_path_and_stat(
1826
 
                    target.abspath(e).encode(osutils._fs_enc), st)
 
1732
                    target.abspath(extra).encode(osutils._fs_enc), st)
1827
1733
            else:
1828
1734
                continue
1829
1735
            target.store.add_object(blob)
1831
1737
            extras.add(np)
1832
1738
    return commit_tree(
1833
1739
        target.store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()]), extras
1834
 
 
1835
 
 
1836
 
def changes_between_git_tree_and_working_copy(source_store, from_tree_sha, target,
1837
 
                                              want_unchanged=False,
1838
 
                                              want_unversioned=False,
1839
 
                                              rename_detector=None,
1840
 
                                              include_trees=True):
1841
 
    """Determine the changes between a git tree and a working tree with index.
1842
 
 
1843
 
    """
1844
 
    to_tree_sha, extras = snapshot_workingtree(target, want_unversioned=want_unversioned)
1845
 
    store = OverlayObjectStore([source_store, target.store])
1846
 
    return tree_changes(
1847
 
        store, from_tree_sha, to_tree_sha, include_trees=include_trees,
1848
 
        rename_detector=rename_detector,
1849
 
        want_unchanged=want_unchanged, change_type_same=True), extras