/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: Jelmer Vernooij
  • Date: 2020-07-15 21:51:27 UTC
  • mto: (7490.40.58 work)
  • mto: This revision was merged to the branch mainline in revision 7519.
  • Revision ID: jelmer@jelmer.uk-20200715215127-3hn9ktbg3f1xikjj
More fixes for hg probing.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
 
 
18
"""Git Trees."""
 
19
 
 
20
from __future__ import absolute_import
 
21
 
 
22
from collections import deque
 
23
import errno
 
24
from io import BytesIO
 
25
import os
 
26
 
 
27
from dulwich.config import (
 
28
    parse_submodules,
 
29
    ConfigFile as GitConfigFile,
 
30
    )
 
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,
 
35
    cleanup_mode,
 
36
    commit_tree,
 
37
    index_entry_from_stat,
 
38
    Index,
 
39
    )
 
40
from dulwich.object_store import (
 
41
    tree_lookup_path,
 
42
    OverlayObjectStore,
 
43
    )
 
44
from dulwich.objects import (
 
45
    Blob,
 
46
    Tree,
 
47
    ZERO_SHA,
 
48
    S_IFGITLINK,
 
49
    S_ISGITLINK,
 
50
    )
 
51
import stat
 
52
import posixpath
 
53
 
 
54
from .. import (
 
55
    controldir as _mod_controldir,
 
56
    delta,
 
57
    errors,
 
58
    mutabletree,
 
59
    osutils,
 
60
    revisiontree,
 
61
    trace,
 
62
    tree as _mod_tree,
 
63
    workingtree,
 
64
    )
 
65
from ..revision import (
 
66
    CURRENT_REVISION,
 
67
    NULL_REVISION,
 
68
    )
 
69
from ..sixish import (
 
70
    text_type,
 
71
    viewitems,
 
72
    )
 
73
 
 
74
from .mapping import (
 
75
    encode_git_path,
 
76
    decode_git_path,
 
77
    mode_is_executable,
 
78
    mode_kind,
 
79
    default_mapping,
 
80
    )
 
81
from .transportgit import (
 
82
    TransportObjectStore,
 
83
    TransportRepo,
 
84
    )
 
85
 
 
86
 
 
87
class GitTreeDirectory(_mod_tree.TreeDirectory):
 
88
 
 
89
    __slots__ = ['file_id', 'name', 'parent_id', 'children']
 
90
 
 
91
    def __init__(self, file_id, name, parent_id):
 
92
        self.file_id = file_id
 
93
        self.name = name
 
94
        self.parent_id = parent_id
 
95
        # TODO(jelmer)
 
96
        self.children = {}
 
97
 
 
98
    @property
 
99
    def kind(self):
 
100
        return 'directory'
 
101
 
 
102
    @property
 
103
    def executable(self):
 
104
        return False
 
105
 
 
106
    def copy(self):
 
107
        return self.__class__(
 
108
            self.file_id, self.name, self.parent_id)
 
109
 
 
110
    def __repr__(self):
 
111
        return "%s(file_id=%r, name=%r, parent_id=%r)" % (
 
112
            self.__class__.__name__, self.file_id, self.name,
 
113
            self.parent_id)
 
114
 
 
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)
 
120
 
 
121
 
 
122
class GitTreeFile(_mod_tree.TreeFile):
 
123
 
 
124
    __slots__ = ['file_id', 'name', 'parent_id', 'text_size', 'text_sha1',
 
125
                 'executable']
 
126
 
 
127
    def __init__(self, file_id, name, parent_id, text_size=None,
 
128
                 text_sha1=None, executable=None):
 
129
        self.file_id = file_id
 
130
        self.name = name
 
131
        self.parent_id = parent_id
 
132
        self.text_size = text_size
 
133
        self.text_sha1 = text_sha1
 
134
        self.executable = executable
 
135
 
 
136
    @property
 
137
    def kind(self):
 
138
        return 'file'
 
139
 
 
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)
 
148
 
 
149
    def __repr__(self):
 
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)
 
154
 
 
155
    def copy(self):
 
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
 
161
        return ret
 
162
 
 
163
 
 
164
class GitTreeSymlink(_mod_tree.TreeLink):
 
165
 
 
166
    __slots__ = ['file_id', 'name', 'parent_id', 'symlink_target']
 
167
 
 
168
    def __init__(self, file_id, name, parent_id,
 
169
                 symlink_target=None):
 
170
        self.file_id = file_id
 
171
        self.name = name
 
172
        self.parent_id = parent_id
 
173
        self.symlink_target = symlink_target
 
174
 
 
175
    @property
 
176
    def kind(self):
 
177
        return 'symlink'
 
178
 
 
179
    @property
 
180
    def executable(self):
 
181
        return False
 
182
 
 
183
    @property
 
184
    def text_size(self):
 
185
        return None
 
186
 
 
187
    def __repr__(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,
 
190
            self.symlink_target)
 
191
 
 
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)
 
198
 
 
199
    def copy(self):
 
200
        return self.__class__(
 
201
            self.file_id, self.name, self.parent_id,
 
202
            self.symlink_target)
 
203
 
 
204
 
 
205
class GitTreeSubmodule(_mod_tree.TreeReference):
 
206
 
 
207
    __slots__ = ['file_id', 'name', 'parent_id', 'reference_revision']
 
208
 
 
209
    def __init__(self, file_id, name, parent_id, reference_revision=None):
 
210
        self.file_id = file_id
 
211
        self.name = name
 
212
        self.parent_id = parent_id
 
213
        self.reference_revision = reference_revision
 
214
 
 
215
    @property
 
216
    def executable(self):
 
217
        return False
 
218
 
 
219
    @property
 
220
    def kind(self):
 
221
        return 'tree-reference'
 
222
 
 
223
    def __repr__(self):
 
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)
 
228
 
 
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)
 
235
 
 
236
    def copy(self):
 
237
        return self.__class__(
 
238
            self.file_id, self.name, self.parent_id,
 
239
            self.reference_revision)
 
240
 
 
241
 
 
242
entry_factory = {
 
243
    'directory': GitTreeDirectory,
 
244
    'file': GitTreeFile,
 
245
    'symlink': GitTreeSymlink,
 
246
    'tree-reference': GitTreeSubmodule,
 
247
    }
 
248
 
 
249
 
 
250
def ensure_normalized_path(path):
 
251
    """Check whether path is normalized.
 
252
 
 
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.
 
256
    """
 
257
    norm_path, can_access = osutils.normalized_filename(path)
 
258
    if norm_path != path:
 
259
        if can_access:
 
260
            return norm_path
 
261
        else:
 
262
            raise errors.InvalidNormalization(path)
 
263
    return path
 
264
 
 
265
 
 
266
class GitRevisionTree(revisiontree.RevisionTree):
 
267
    """Revision tree implementation based on Git objects."""
 
268
 
 
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(
 
277
            revision_id)
 
278
        if revision_id == NULL_REVISION:
 
279
            self.tree = None
 
280
            self.mapping = default_mapping
 
281
        else:
 
282
            try:
 
283
                commit = self.store[self.commit_id]
 
284
            except KeyError:
 
285
                raise errors.NoSuchRevision(repository, revision_id)
 
286
            self.tree = commit.tree
 
287
 
 
288
    def _submodule_info(self):
 
289
        if self._submodules is None:
 
290
            try:
 
291
                with self.get_file('.gitmodules') as f:
 
292
                    config = GitConfigFile.from_file(f)
 
293
                    self._submodules = {
 
294
                        path: (url, section)
 
295
                        for path, url, section in parse_submodules(config)}
 
296
            except errors.NoSuchFile:
 
297
                self._submodules = {}
 
298
        return self._submodules
 
299
 
 
300
    def _get_submodule_repository(self, relpath):
 
301
        if not isinstance(relpath, bytes):
 
302
            raise TypeError(relpath)
 
303
        try:
 
304
            info = self._submodule_info()[relpath]
 
305
        except KeyError:
 
306
            nested_repo_transport = self._repository.controldir.user_transport.clone(
 
307
                decode_git_path(relpath))
 
308
        else:
 
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()
 
314
 
 
315
    def _get_submodule_store(self, relpath):
 
316
        return self._get_submodule_repository(relpath)._git.object_store
 
317
 
 
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)
 
323
 
 
324
    def supports_rename_tracking(self):
 
325
        return False
 
326
 
 
327
    def get_file_revision(self, path):
 
328
        change_scanner = self._repository._file_change_scanner
 
329
        if self.commit_id == ZERO_SHA:
 
330
            return NULL_REVISION
 
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)
 
335
 
 
336
    def get_file_mtime(self, path):
 
337
        try:
 
338
            revid = self.get_file_revision(path)
 
339
        except KeyError:
 
340
            raise errors.NoSuchFile(path)
 
341
        try:
 
342
            rev = self._repository.get_revision(revid)
 
343
        except errors.NoSuchRevision:
 
344
            raise _mod_tree.FileTimestampUnavailable(path)
 
345
        return rev.timestamp
 
346
 
 
347
    def id2path(self, file_id, recurse='down'):
 
348
        try:
 
349
            path = self.mapping.parse_file_id(file_id)
 
350
        except ValueError:
 
351
            raise errors.NoSuchId(self, file_id)
 
352
        if self.is_versioned(path):
 
353
            return path
 
354
        raise errors.NoSuchId(self, file_id)
 
355
 
 
356
    def is_versioned(self, path):
 
357
        return self.has_filename(path)
 
358
 
 
359
    def path2id(self, path):
 
360
        if self.mapping.is_special_file(path):
 
361
            return None
 
362
        if not self.is_versioned(path):
 
363
            return None
 
364
        return self.mapping.generate_file_id(osutils.safe_unicode(path))
 
365
 
 
366
    def all_file_ids(self):
 
367
        raise errors.UnsupportedOperation(self.all_file_ids, self)
 
368
 
 
369
    def all_versioned_paths(self):
 
370
        ret = {u''}
 
371
        todo = [(self.store, b'', self.tree)]
 
372
        while todo:
 
373
            (store, path, tree_id) = todo.pop()
 
374
            if tree_id is None:
 
375
                continue
 
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))
 
382
        return ret
 
383
 
 
384
    def _lookup_path(self, path):
 
385
        if self.tree is None:
 
386
            raise errors.NoSuchFile(path)
 
387
 
 
388
        encoded_path = encode_git_path(path)
 
389
        parts = encoded_path.split(b'/')
 
390
        hexsha = self.tree
 
391
        store = self.store
 
392
        mode = None
 
393
        for i, p in enumerate(parts):
 
394
            if not p:
 
395
                continue
 
396
            obj = store[hexsha]
 
397
            if not isinstance(obj, Tree):
 
398
                raise NotTreeError(hexsha)
 
399
            try:
 
400
                mode, hexsha = obj[p]
 
401
            except KeyError:
 
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)
 
407
 
 
408
    def is_executable(self, path):
 
409
        (store, mode, hexsha) = self._lookup_path(path)
 
410
        if mode is None:
 
411
            # the tree root is a directory
 
412
            return False
 
413
        return mode_is_executable(mode)
 
414
 
 
415
    def kind(self, path):
 
416
        (store, mode, hexsha) = self._lookup_path(path)
 
417
        if mode is None:
 
418
            # the tree root is a directory
 
419
            return "directory"
 
420
        return mode_kind(mode)
 
421
 
 
422
    def has_filename(self, path):
 
423
        try:
 
424
            self._lookup_path(path)
 
425
        except errors.NoSuchFile:
 
426
            return False
 
427
        else:
 
428
            return True
 
429
 
 
430
    def _submodule_info(self):
 
431
        if self._submodules is None:
 
432
            try:
 
433
                with self.get_file('.gitmodules') as f:
 
434
                    config = GitConfigFile.from_file(f)
 
435
                    self._submodules = {
 
436
                        path: (url, section)
 
437
                        for path, url, section in parse_submodules(config)}
 
438
            except errors.NoSuchFile:
 
439
                self._submodules = {}
 
440
        return self._submodules
 
441
 
 
442
    def list_files(self, include_root=False, from_dir=None, recursive=True,
 
443
                   recurse_nested=False):
 
444
        if self.tree is None:
 
445
            return
 
446
        if from_dir is None or from_dir == '.':
 
447
            from_dir = u""
 
448
        (store, mode, hexsha) = self._lookup_path(from_dir)
 
449
        if mode is None:  # Root
 
450
            root_ie = self._get_dir_ie(b"", None)
 
451
        else:
 
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)
 
456
            else:
 
457
                root_ie = self._get_file_ie(
 
458
                    store, encode_git_path(from_dir),
 
459
                    posixpath.basename(from_dir), mode, hexsha)
 
460
        if include_root:
 
461
            yield (from_dir, "V", root_ie.kind, root_ie)
 
462
        todo = []
 
463
        if root_ie.kind == 'directory':
 
464
            todo.append((store, encode_git_path(from_dir),
 
465
                         b"", hexsha, root_ie.file_id))
 
466
        while todo:
 
467
            (store, path, relpath, hexsha, parent_id) = todo.pop()
 
468
            tree = store[hexsha]
 
469
            for name, mode, hexsha in tree.iteritems():
 
470
                if self.mapping.is_special_file(name):
 
471
                    continue
 
472
                child_path = posixpath.join(path, name)
 
473
                child_relpath = posixpath.join(relpath, name)
 
474
                if S_ISGITLINK(mode) and recurse_nested:
 
475
                    mode = stat.S_IFDIR
 
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)
 
480
                    if recursive:
 
481
                        todo.append(
 
482
                            (store, child_path, child_relpath, hexsha,
 
483
                             ie.file_id))
 
484
                else:
 
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)
 
488
 
 
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(
 
503
                hexsha)
 
504
        else:
 
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)
 
509
        return ie
 
510
 
 
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)
 
515
 
 
516
    def iter_child_entries(self, path):
 
517
        (store, mode, tree_sha) = self._lookup_path(path)
 
518
 
 
519
        if mode is not None and not stat.S_ISDIR(mode):
 
520
            return
 
521
 
 
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):
 
527
                continue
 
528
            child_path = posixpath.join(encoded_path, name)
 
529
            if stat.S_ISDIR(mode):
 
530
                yield self._get_dir_ie(child_path, file_id)
 
531
            else:
 
532
                yield self._get_file_ie(store, child_path, name, mode, hexsha,
 
533
                                        file_id)
 
534
 
 
535
    def iter_entries_by_dir(self, specific_files=None,
 
536
                            recurse_nested=False):
 
537
        if self.tree is None:
 
538
            return
 
539
        if specific_files is not None:
 
540
            if specific_files in ([""], []):
 
541
                specific_files = None
 
542
            else:
 
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)
 
548
        while todo:
 
549
            store, path, tree_sha, parent_id = todo.popleft()
 
550
            tree = store[tree_sha]
 
551
            extradirs = []
 
552
            for name, mode, hexsha in tree.iteritems():
 
553
                if self.mapping.is_special_file(name):
 
554
                    continue
 
555
                child_path = posixpath.join(path, name)
 
556
                child_path_decoded = decode_git_path(child_path)
 
557
                if recurse_nested and S_ISGITLINK(mode):
 
558
                    mode = stat.S_IFDIR
 
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(
 
564
                                child_path)])):
 
565
                        extradirs.append(
 
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))
 
572
                    else:
 
573
                        yield (child_path_decoded,
 
574
                               self._get_file_ie(store, child_path, name, mode,
 
575
                                                 hexsha, parent_id))
 
576
            todo.extendleft(reversed(extradirs))
 
577
 
 
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':
 
582
                    yield path
 
583
 
 
584
    def get_revision_id(self):
 
585
        """See RevisionTree.get_revision_id."""
 
586
        return self._revision_id
 
587
 
 
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))
 
592
 
 
593
    def get_file_verifier(self, path, stat_value=None):
 
594
        (store, mode, hexsha) = self._lookup_path(path)
 
595
        return ("GIT", hexsha)
 
596
 
 
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)
 
601
        return None
 
602
 
 
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
 
608
        else:
 
609
            return b""
 
610
 
 
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)
 
616
        else:
 
617
            return None
 
618
 
 
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):
 
623
            try:
 
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)
 
627
            else:
 
628
                return nested_repo.lookup_foreign_revision_id(hexsha)
 
629
        else:
 
630
            return None
 
631
 
 
632
    def _comparison_data(self, entry, path):
 
633
        if entry is None:
 
634
            return None, False, None
 
635
        return entry.kind, entry.executable, None
 
636
 
 
637
    def path_content_summary(self, path):
 
638
        """See Tree.path_content_summary."""
 
639
        try:
 
640
            (store, mode, hexsha) = self._lookup_path(path)
 
641
        except errors.NoSuchFile:
 
642
            return ('missing', None, None, None)
 
643
        kind = mode_kind(mode)
 
644
        if kind == 'file':
 
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))
 
655
        else:
 
656
            return (kind, None, None, None)
 
657
 
 
658
    def find_related_paths_across_trees(self, paths, trees=[],
 
659
                                        require_versioned=True):
 
660
        if paths is None:
 
661
            return None
 
662
        if require_versioned:
 
663
            trees = [self] + (trees if trees is not None else [])
 
664
            unversioned = set()
 
665
            for p in paths:
 
666
                for t in trees:
 
667
                    if t.is_versioned(p):
 
668
                        break
 
669
                else:
 
670
                    unversioned.add(p)
 
671
            if unversioned:
 
672
                raise errors.PathsNotVersionedError(unversioned)
 
673
        return filter(self.is_versioned, paths)
 
674
 
 
675
    def _iter_tree_contents(self, include_trees=False):
 
676
        if self.tree is None:
 
677
            return iter([])
 
678
        return self.store.iter_tree_contents(
 
679
            self.tree, include_trees=include_trees)
 
680
 
 
681
    def annotate_iter(self, path, default_revision=CURRENT_REVISION):
 
682
        """Return an iterator of revision_id, line tuples.
 
683
 
 
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
 
689
            this value.
 
690
        """
 
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)]
 
700
            return annotations
 
701
 
 
702
    def _get_rules_searcher(self, default_searcher):
 
703
        return default_searcher
 
704
 
 
705
    def walkdirs(self, prefix=u""):
 
706
        (store, mode, hexsha) = self._lookup_path(prefix)
 
707
        todo = deque(
 
708
            [(store, encode_git_path(prefix), hexsha, self.path2id(prefix))])
 
709
        while todo:
 
710
            store, path, tree_sha, parent_id = todo.popleft()
 
711
            path_decoded = decode_git_path(path)
 
712
            tree = store[tree_sha]
 
713
            children = []
 
714
            for name, mode, hexsha in tree.iteritems():
 
715
                if self.mapping.is_special_file(name):
 
716
                    continue
 
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))
 
721
                children.append(
 
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
 
726
 
 
727
    def preview_transform(self, pb=None):
 
728
        from .transform import GitTransformPreview
 
729
        return GitTransformPreview(self, pb=pb)
 
730
 
 
731
 
 
732
def tree_delta_from_git_changes(changes, mappings,
 
733
                                specific_files=None,
 
734
                                require_versioned=False, include_root=False,
 
735
                                source_extras=None, target_extras=None):
 
736
    """Create a TreeDelta from two git trees.
 
737
 
 
738
    source and target are iterators over tuples with:
 
739
        (filename, sha, mode)
 
740
    """
 
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()
 
747
    added = []
 
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:
 
752
            continue
 
753
        copied = (change_type == 'copy')
 
754
        if oldpath is not None:
 
755
            oldpath_decoded = decode_git_path(oldpath)
 
756
        else:
 
757
            oldpath_decoded = None
 
758
        if newpath is not None:
 
759
            newpath_decoded = decode_git_path(newpath)
 
760
        else:
 
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))):
 
769
            continue
 
770
 
 
771
        if oldpath is None:
 
772
            oldexe = None
 
773
            oldkind = None
 
774
            oldname = None
 
775
            oldparent = None
 
776
            oldversioned = False
 
777
        else:
 
778
            oldversioned = (oldpath not in source_extras)
 
779
            if oldmode:
 
780
                oldexe = mode_is_executable(oldmode)
 
781
                oldkind = mode_kind(oldmode)
 
782
            else:
 
783
                oldexe = False
 
784
                oldkind = None
 
785
            if oldpath == b'':
 
786
                oldparent = None
 
787
                oldname = u''
 
788
            else:
 
789
                (oldparentpath, oldname) = osutils.split(oldpath_decoded)
 
790
                oldparent = old_mapping.generate_file_id(oldparentpath)
 
791
        if newpath is None:
 
792
            newexe = None
 
793
            newkind = None
 
794
            newname = None
 
795
            newparent = None
 
796
            newversioned = False
 
797
        else:
 
798
            newversioned = (newpath not in target_extras)
 
799
            if newmode:
 
800
                newexe = mode_is_executable(newmode)
 
801
                newkind = mode_kind(newmode)
 
802
            else:
 
803
                newexe = False
 
804
                newkind = None
 
805
            if newpath_decoded == u'':
 
806
                newparent = None
 
807
                newname = u''
 
808
            else:
 
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)
 
813
        elif newversioned:
 
814
            fileid = new_mapping.generate_file_id(newpath_decoded)
 
815
        else:
 
816
            fileid = None
 
817
        if old_mapping.is_special_file(oldpath):
 
818
            oldpath = None
 
819
        if new_mapping.is_special_file(newpath):
 
820
            newpath = None
 
821
        if oldpath is None and newpath is None:
 
822
            continue
 
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),
 
828
            copied=copied)
 
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):
 
840
                continue
 
841
            ret.copied.append(change)
 
842
        elif change_type == 'rename':
 
843
            if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
 
844
                continue
 
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):
 
850
                continue
 
851
            ret.modified.append(change)
 
852
        else:
 
853
            ret.unchanged.append(change)
 
854
 
 
855
    implicit_dirs = {b''}
 
856
    for path, kind in added:
 
857
        if kind == 'directory' or path in target_extras:
 
858
            continue
 
859
        implicit_dirs.update(osutils.parent_directories(path))
 
860
 
 
861
    for path, kind in added:
 
862
        if kind == 'directory' and path not in implicit_dirs:
 
863
            continue
 
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)
 
868
        ret.added.append(
 
869
            _mod_tree.TreeChange(
 
870
                file_id, (None, path_decoded), True,
 
871
                (False, True),
 
872
                (None, parent_id),
 
873
                (None, basename), (None, kind), (None, False)))
 
874
 
 
875
    return ret
 
876
 
 
877
 
 
878
def changes_from_git_changes(changes, mapping, specific_files=None,
 
879
                             include_unchanged=False, source_extras=None,
 
880
                             target_extras=None):
 
881
    """Create a iter_changes-like generator from a git stream.
 
882
 
 
883
    source and target are iterators over tuples with:
 
884
        (filename, sha, mode)
 
885
    """
 
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:
 
892
            continue
 
893
        (oldpath, oldmode, oldsha) = old
 
894
        (newpath, newmode, newsha) = new
 
895
        if oldpath is not None:
 
896
            oldpath_decoded = decode_git_path(oldpath)
 
897
        else:
 
898
            oldpath_decoded = None
 
899
        if newpath is not None:
 
900
            newpath_decoded = decode_git_path(newpath)
 
901
        else:
 
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))):
 
910
            continue
 
911
        if oldpath is not None and mapping.is_special_file(oldpath):
 
912
            continue
 
913
        if newpath is not None and mapping.is_special_file(newpath):
 
914
            continue
 
915
        if oldpath is None:
 
916
            oldexe = None
 
917
            oldkind = None
 
918
            oldname = None
 
919
            oldparent = None
 
920
            oldversioned = False
 
921
        else:
 
922
            oldversioned = (oldpath not in source_extras)
 
923
            if oldmode:
 
924
                oldexe = mode_is_executable(oldmode)
 
925
                oldkind = mode_kind(oldmode)
 
926
            else:
 
927
                oldexe = False
 
928
                oldkind = None
 
929
            if oldpath_decoded == u'':
 
930
                oldparent = None
 
931
                oldname = u''
 
932
            else:
 
933
                (oldparentpath, oldname) = osutils.split(oldpath_decoded)
 
934
                oldparent = mapping.generate_file_id(oldparentpath)
 
935
        if newpath is None:
 
936
            newexe = None
 
937
            newkind = None
 
938
            newname = None
 
939
            newparent = None
 
940
            newversioned = False
 
941
        else:
 
942
            newversioned = (newpath not in target_extras)
 
943
            if newmode:
 
944
                newexe = mode_is_executable(newmode)
 
945
                newkind = mode_kind(newmode)
 
946
            else:
 
947
                newexe = False
 
948
                newkind = None
 
949
            if newpath_decoded == u'':
 
950
                newparent = None
 
951
                newname = u''
 
952
            else:
 
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):
 
958
            continue
 
959
        if oldversioned and change_type != 'copy':
 
960
            fileid = mapping.generate_file_id(oldpath_decoded)
 
961
        elif newversioned:
 
962
            fileid = mapping.generate_file_id(newpath_decoded)
 
963
        else:
 
964
            fileid = None
 
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'))
 
971
 
 
972
 
 
973
class InterGitTrees(_mod_tree.InterTree):
 
974
    """InterTree that works between two git trees."""
 
975
 
 
976
    _matching_from_tree_format = None
 
977
    _matching_to_tree_format = None
 
978
    _test_mutable_trees_to_test_trees = None
 
979
 
 
980
    @classmethod
 
981
    def is_compatible(cls, source, target):
 
982
        return (isinstance(source, GitRevisionTree) and
 
983
                isinstance(target, GitRevisionTree))
 
984
 
 
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)
 
1000
 
 
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)
 
1017
 
 
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)
 
1022
 
 
1023
    def find_target_path(self, path, recurse='none'):
 
1024
        ret = self.find_target_paths([path], recurse=recurse)
 
1025
        return ret[path]
 
1026
 
 
1027
    def find_source_path(self, path, recurse='none'):
 
1028
        ret = self.find_source_paths([path], recurse=recurse)
 
1029
        return ret[path]
 
1030
 
 
1031
    def find_target_paths(self, paths, recurse='none'):
 
1032
        paths = set(paths)
 
1033
        ret = {}
 
1034
        changes = self._iter_git_changes(
 
1035
            specific_files=paths, include_trees=False)[0]
 
1036
        for (change_type, old, new) in changes:
 
1037
            if old[0] is None:
 
1038
                continue
 
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
 
1042
        for path in paths:
 
1043
            if path not in ret:
 
1044
                if self.source.has_filename(path):
 
1045
                    if self.target.has_filename(path):
 
1046
                        ret[path] = path
 
1047
                    else:
 
1048
                        ret[path] = None
 
1049
                else:
 
1050
                    raise errors.NoSuchFile(path)
 
1051
        return ret
 
1052
 
 
1053
    def find_source_paths(self, paths, recurse='none'):
 
1054
        paths = set(paths)
 
1055
        ret = {}
 
1056
        changes = self._iter_git_changes(
 
1057
            specific_files=paths, include_trees=False)[0]
 
1058
        for (change_type, old, new) in changes:
 
1059
            if new[0] is None:
 
1060
                continue
 
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
 
1064
        for path in paths:
 
1065
            if path not in ret:
 
1066
                if self.target.has_filename(path):
 
1067
                    if self.source.has_filename(path):
 
1068
                        ret[path] = path
 
1069
                    else:
 
1070
                        ret[path] = None
 
1071
                else:
 
1072
                    raise errors.NoSuchFile(path)
 
1073
        return ret
 
1074
 
 
1075
 
 
1076
class InterGitRevisionTrees(InterGitTrees):
 
1077
    """InterTree that works between two git revision trees."""
 
1078
 
 
1079
    _matching_from_tree_format = None
 
1080
    _matching_to_tree_format = None
 
1081
    _test_mutable_trees_to_test_trees = None
 
1082
 
 
1083
    @classmethod
 
1084
    def is_compatible(cls, source, target):
 
1085
        return (isinstance(source, GitRevisionTree) and
 
1086
                isinstance(target, GitRevisionTree))
 
1087
 
 
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)
 
1098
 
 
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])
 
1104
        else:
 
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()
 
1112
 
 
1113
 
 
1114
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
 
1115
 
 
1116
 
 
1117
class MutableGitIndexTree(mutabletree.MutableTree):
 
1118
 
 
1119
    def __init__(self):
 
1120
        self._lock_mode = None
 
1121
        self._lock_count = 0
 
1122
        self._versioned_dirs = None
 
1123
        self._index_dirty = False
 
1124
        self._submodules = None
 
1125
 
 
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))
 
1131
 
 
1132
    def _has_dir(self, path):
 
1133
        if not isinstance(path, bytes):
 
1134
            raise TypeError(path)
 
1135
        if path == b"":
 
1136
            return True
 
1137
        if self._versioned_dirs is None:
 
1138
            self._load_dirs()
 
1139
        return path in self._versioned_dirs
 
1140
 
 
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))
 
1147
 
 
1148
    def _ensure_versioned_dir(self, dirname):
 
1149
        if not isinstance(dirname, bytes):
 
1150
            raise TypeError(dirname)
 
1151
        if dirname in self._versioned_dirs:
 
1152
            return
 
1153
        if dirname != b"":
 
1154
            self._ensure_versioned_dir(posixpath.dirname(dirname))
 
1155
        self._versioned_dirs.add(dirname)
 
1156
 
 
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))
 
1163
            return None
 
1164
 
 
1165
    def id2path(self, file_id, recurse='down'):
 
1166
        if file_id is None:
 
1167
            return ''
 
1168
        if type(file_id) is not bytes:
 
1169
            raise TypeError(file_id)
 
1170
        with self.lock_read():
 
1171
            try:
 
1172
                path = self.mapping.parse_file_id(file_id)
 
1173
            except ValueError:
 
1174
                raise errors.NoSuchId(self, file_id)
 
1175
            if self.is_versioned(path):
 
1176
                return path
 
1177
            raise errors.NoSuchId(self, file_id)
 
1178
 
 
1179
    def _set_root_id(self, file_id):
 
1180
        raise errors.UnsupportedOperation(self._set_root_id, self)
 
1181
 
 
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)
 
1187
            if not can_access:
 
1188
                raise errors.InvalidNormalization(path)
 
1189
            self._index_add_entry(path, kind)
 
1190
 
 
1191
    def _read_submodule_head(self, path):
 
1192
        raise NotImplementedError(self._read_submodule_head)
 
1193
 
 
1194
    def _submodule_info(self):
 
1195
        if self._submodules is None:
 
1196
            try:
 
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
 
1205
 
 
1206
    def _lookup_index(self, encoded_path):
 
1207
        if not isinstance(encoded_path, bytes):
 
1208
            raise TypeError(encoded_path)
 
1209
        # Common case:
 
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
 
1213
        # submodules exist?
 
1214
        index = self.index
 
1215
        remaining_path = encoded_path
 
1216
        while True:
 
1217
            parts = remaining_path.split(b'/')
 
1218
            for i in range(1, len(parts)):
 
1219
                basepath = b'/'.join(parts[:i])
 
1220
                try:
 
1221
                    (ctime, mtime, dev, ino, mode, uid, gid, size, sha,
 
1222
                     flags) = index[basepath]
 
1223
                except KeyError:
 
1224
                    continue
 
1225
                else:
 
1226
                    if S_ISGITLINK(mode):
 
1227
                        index = self._get_submodule_index(basepath)
 
1228
                        remaining_path = b'/'.join(parts[i:])
 
1229
                        break
 
1230
                    else:
 
1231
                        return index, remaining_path
 
1232
            else:
 
1233
                return index, remaining_path
 
1234
        return index, remaining_path
 
1235
 
 
1236
    def _index_del_entry(self, index, path):
 
1237
        del index[path]
 
1238
        # TODO(jelmer): Keep track of dirty per index
 
1239
        self._index_dirty = True
 
1240
 
 
1241
    def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
 
1242
        if kind == "directory":
 
1243
            # Git indexes don't contain directories
 
1244
            return
 
1245
        if kind == "file":
 
1246
            blob = Blob()
 
1247
            try:
 
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
 
1251
                # index
 
1252
                file = BytesIO()
 
1253
                stat_val = os.stat_result(
 
1254
                    (stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
 
1255
            with file:
 
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)
 
1260
            hexsha = blob.id
 
1261
        elif kind == "symlink":
 
1262
            blob = Blob()
 
1263
            try:
 
1264
                stat_val = self._lstat(path)
 
1265
            except EnvironmentError:
 
1266
                # TODO: Rather than come up with something here, use the
 
1267
                # old index
 
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)
 
1274
            hexsha = blob.id
 
1275
        elif kind == "tree-reference":
 
1276
            if reference_revision is not None:
 
1277
                hexsha = self.branch.lookup_bzr_revision_id(
 
1278
                    reference_revision)[0]
 
1279
            else:
 
1280
                hexsha = self._read_submodule_head(path)
 
1281
                if hexsha is None:
 
1282
                    raise errors.NoCommits(path)
 
1283
            try:
 
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:])
 
1289
        else:
 
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)
 
1297
            return
 
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)
 
1303
 
 
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():
 
1308
            if index is None:
 
1309
                index = self.index
 
1310
            for path, value in index.items():
 
1311
                (ctime, mtime, dev, ino, mode, uid, gid, size, sha,
 
1312
                 flags) = value
 
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):
 
1318
                        yield entry
 
1319
                else:
 
1320
                    yield (posixpath.join(basepath, path), value)
 
1321
 
 
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)
 
1327
            else:
 
1328
                specific_files = None
 
1329
            root_ie = self._get_dir_ie(u"", None)
 
1330
            ret = {}
 
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):
 
1337
                    continue
 
1338
                path = decode_git_path(path)
 
1339
                if specific_files is not None and path not in specific_files:
 
1340
                    continue
 
1341
                (parent, name) = posixpath.split(path)
 
1342
                try:
 
1343
                    file_ie = self._get_file_ie(name, path, value, None)
 
1344
                except errors.NoSuchFile:
 
1345
                    continue
 
1346
                if specific_files is None:
 
1347
                    for (dir_path, dir_ie) in self._add_missing_parent_ids(
 
1348
                            parent, dir_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
 
1353
            if specific_files:
 
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)))
 
1359
 
 
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':
 
1365
                    yield path
 
1366
 
 
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)
 
1371
 
 
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)
 
1389
        else:
 
1390
            try:
 
1391
                data = self.get_file_text(path)
 
1392
            except errors.NoSuchFile:
 
1393
                data = None
 
1394
            except IOError as e:
 
1395
                if e.errno != errno.ENOENT:
 
1396
                    raise
 
1397
                data = None
 
1398
            if data is None:
 
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)
 
1403
        return ie
 
1404
 
 
1405
    def _add_missing_parent_ids(self, path, dir_ids):
 
1406
        if path in dir_ids:
 
1407
            return []
 
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))
 
1414
        return ret
 
1415
 
 
1416
    def _comparison_data(self, entry, path):
 
1417
        if entry is None:
 
1418
            return None, False, None
 
1419
        return entry.kind, entry.executable, None
 
1420
 
 
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)
 
1425
        count = 0
 
1426
        (index, subpath) = self._lookup_index(encoded_path)
 
1427
        try:
 
1428
            self._index_del_entry(index, encoded_path)
 
1429
        except KeyError:
 
1430
            # A directory, perhaps?
 
1431
            # TODO(jelmer): Deletes that involve submodules?
 
1432
            for p in list(index):
 
1433
                if p.startswith(subpath + b"/"):
 
1434
                    count += 1
 
1435
                    self._index_del_entry(index, p)
 
1436
        else:
 
1437
            count = 1
 
1438
        self._versioned_dirs = None
 
1439
        return count
 
1440
 
 
1441
    def unversion(self, paths):
 
1442
        with self.lock_tree_write():
 
1443
            for path in paths:
 
1444
                if self._unversion_path(path) == 0:
 
1445
                    raise errors.NoSuchFile(path)
 
1446
            self._versioned_dirs = None
 
1447
            self.flush()
 
1448
 
 
1449
    def flush(self):
 
1450
        pass
 
1451
 
 
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)
 
1463
        self.flush()
 
1464
        self._set_merges_from_parent_ids([])
 
1465
 
 
1466
    def move(self, from_paths, to_dir=None, after=None):
 
1467
        rename_tuples = []
 
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))
 
1473
 
 
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))
 
1479
            self.flush()
 
1480
            return rename_tuples
 
1481
 
 
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)
 
1485
        if not can_access:
 
1486
            raise errors.InvalidNormalization(to_rel)
 
1487
        to_path = encode_git_path(to_rel)
 
1488
        with self.lock_tree_write():
 
1489
            if not after:
 
1490
                # Perhaps it's already moved?
 
1491
                after = (
 
1492
                    not self.has_filename(from_rel) and
 
1493
                    self.has_filename(to_rel) and
 
1494
                    not self.is_versioned(to_rel))
 
1495
            if after:
 
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))
 
1502
 
 
1503
                kind = self.kind(to_rel)
 
1504
            else:
 
1505
                try:
 
1506
                    to_kind = self.kind(to_rel)
 
1507
                except errors.NoSuchFile:
 
1508
                    exc_type = errors.BzrRenameFailedError
 
1509
                    to_kind = None
 
1510
                else:
 
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))
 
1525
 
 
1526
                kind = self.kind(from_rel)
 
1527
 
 
1528
            if not after and kind != 'directory':
 
1529
                (index, from_subpath) = self._lookup_index(from_path)
 
1530
                if from_subpath not in index:
 
1531
                    # It's not a file
 
1532
                    raise errors.BzrMoveFailedError(
 
1533
                        from_rel, to_rel,
 
1534
                        errors.NotVersionedError(path=from_rel))
 
1535
 
 
1536
            if not after:
 
1537
                try:
 
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))
 
1543
                    raise
 
1544
            if kind != 'directory':
 
1545
                (index, from_index_path) = self._lookup_index(from_path)
 
1546
                try:
 
1547
                    self._index_del_entry(index, from_path)
 
1548
                except KeyError:
 
1549
                    pass
 
1550
                self._index_add_entry(to_rel, kind)
 
1551
            else:
 
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(
 
1561
                        child_path)
 
1562
                    self._index_del_entry(
 
1563
                        child_from_index, child_from_index_path)
 
1564
 
 
1565
            self._versioned_dirs = None
 
1566
            self.flush()
 
1567
 
 
1568
    def find_related_paths_across_trees(self, paths, trees=[],
 
1569
                                        require_versioned=True):
 
1570
        if paths is None:
 
1571
            return None
 
1572
 
 
1573
        if require_versioned:
 
1574
            trees = [self] + (trees if trees is not None else [])
 
1575
            unversioned = set()
 
1576
            for p in paths:
 
1577
                for t in trees:
 
1578
                    if t.is_versioned(p):
 
1579
                        break
 
1580
                else:
 
1581
                    unversioned.add(p)
 
1582
            if unversioned:
 
1583
                raise errors.PathsNotVersionedError(unversioned)
 
1584
 
 
1585
        return filter(self.is_versioned, paths)
 
1586
 
 
1587
    def path_content_summary(self, path):
 
1588
        """See Tree.path_content_summary."""
 
1589
        try:
 
1590
            stat_result = self._lstat(path)
 
1591
        except OSError as e:
 
1592
            if getattr(e, 'errno', None) == errno.ENOENT:
 
1593
                # no file.
 
1594
                return ('missing', None, None, None)
 
1595
            # propagate other errors
 
1596
            raise
 
1597
        kind = mode_kind(stat_result.st_mode)
 
1598
        if kind == 'file':
 
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
 
1602
            # reference.
 
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)
 
1609
        else:
 
1610
            return (kind, None, None, None)
 
1611
 
 
1612
    def stored_kind(self, relpath):
 
1613
        (index, index_path) = self._lookup_index(encode_git_path(relpath))
 
1614
        if index is None:
 
1615
            return kind
 
1616
        try:
 
1617
            mode = index[index_path].mode
 
1618
        except KeyError:
 
1619
            return kind
 
1620
        else:
 
1621
            if S_ISGITLINK(mode):
 
1622
                return 'tree-reference'
 
1623
            return 'directory'
 
1624
 
 
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'
 
1630
            return 'directory'
 
1631
        else:
 
1632
            return kind
 
1633
 
 
1634
    def _live_entry(self, relpath):
 
1635
        raise NotImplementedError(self._live_entry)
 
1636
 
 
1637
    def transform(self, pb=None):
 
1638
        from .transform import GitTreeTransform
 
1639
        return GitTreeTransform(self, pb=pb)
 
1640
 
 
1641
    def preview_transform(self, pb=None):
 
1642
        from .transform import GitTransformPreview
 
1643
        return GitTransformPreview(self, pb=pb)
 
1644
 
 
1645
 
 
1646
class InterToIndexGitTree(InterGitTrees):
 
1647
    """InterTree that works between a Git revision tree and an index."""
 
1648
 
 
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
 
1653
        else:
 
1654
            self.store = OverlayObjectStore(
 
1655
                [self.source.store, self.target.store])
 
1656
        self.rename_detector = RenameDetector(self.store)
 
1657
 
 
1658
    @classmethod
 
1659
    def is_compatible(cls, source, target):
 
1660
        return (isinstance(source, GitRevisionTree) and
 
1661
                isinstance(target, MutableGitIndexTree))
 
1662
 
 
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
 
1682
 
 
1683
 
 
1684
_mod_tree.InterTree.register_optimiser(InterToIndexGitTree)
 
1685
 
 
1686
 
 
1687
class InterFromIndexGitTree(InterGitTrees):
 
1688
    """InterTree that works between a Git revision tree and an index."""
 
1689
 
 
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
 
1694
        else:
 
1695
            self.store = OverlayObjectStore(
 
1696
                [self.source.store, self.target.store])
 
1697
        self.rename_detector = RenameDetector(self.store)
 
1698
 
 
1699
    @classmethod
 
1700
    def is_compatible(cls, source, target):
 
1701
        return (isinstance(target, GitRevisionTree) and
 
1702
                isinstance(source, MutableGitIndexTree))
 
1703
 
 
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
 
1722
 
 
1723
 
 
1724
_mod_tree.InterTree.register_optimiser(InterFromIndexGitTree)
 
1725
 
 
1726
 
 
1727
class InterIndexGitTree(InterGitTrees):
 
1728
    """InterTree that works between a Git revision tree and an index."""
 
1729
 
 
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
 
1734
        else:
 
1735
            self.store = OverlayObjectStore(
 
1736
                [self.source.store, self.target.store])
 
1737
        self.rename_detector = RenameDetector(self.store)
 
1738
 
 
1739
    @classmethod
 
1740
    def is_compatible(cls, source, target):
 
1741
        return (isinstance(target, MutableGitIndexTree) and
 
1742
                isinstance(source, MutableGitIndexTree))
 
1743
 
 
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
 
1766
 
 
1767
 
 
1768
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
 
1769
 
 
1770
 
 
1771
def snapshot_workingtree(target, want_unversioned=False):
 
1772
    extras = set()
 
1773
    blobs = {}
 
1774
    # Report dirified directories to commit_tree first, so that they can be
 
1775
    # replaced with non-empty directories if they have contents.
 
1776
    dirified = []
 
1777
    trust_executable = target._supports_executable()
 
1778
    for path, index_entry in target._recurse_index_entries():
 
1779
        try:
 
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)
 
1785
            else:
 
1786
                raise
 
1787
        else:
 
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)
 
1793
                else:
 
1794
                    dirified.append((path, Tree().id, stat.S_IFDIR))
 
1795
                    target.store.add_object(Tree())
 
1796
            else:
 
1797
                mode = live_entry.mode
 
1798
                if not trust_executable:
 
1799
                    if mode_is_executable(index_entry.mode):
 
1800
                        mode |= 0o111
 
1801
                    else:
 
1802
                        mode &= ~0o111
 
1803
                if live_entry.sha != index_entry.sha:
 
1804
                    rp = decode_git_path(path)
 
1805
                    if stat.S_ISREG(live_entry.mode):
 
1806
                        blob = Blob()
 
1807
                        with target.get_file(rp) as f:
 
1808
                            blob.data = f.read()
 
1809
                    elif stat.S_ISLNK(live_entry.mode):
 
1810
                        blob = Blob()
 
1811
                        blob.data = target.get_symlink_target(rp).encode(osutils._fs_enc)
 
1812
                    else:
 
1813
                        blob = None
 
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):
 
1819
            try:
 
1820
                e, accessible = osutils.normalized_filename(e)
 
1821
            except UnicodeDecodeError:
 
1822
                raise errors.BadFilenameEncoding(
 
1823
                    e, osutils._fs_enc)
 
1824
            np = encode_git_path(e)
 
1825
            if np in blobs:
 
1826
                continue
 
1827
            st = target._lstat(e)
 
1828
            if stat.S_ISDIR(st.st_mode):
 
1829
                blob = Tree()
 
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)
 
1833
            else:
 
1834
                continue
 
1835
            target.store.add_object(blob)
 
1836
            blobs[np] = (blob.id, cleanup_mode(st.st_mode))
 
1837
            extras.add(np)
 
1838
    return commit_tree(
 
1839
        target.store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()]), extras
 
1840
 
 
1841
 
 
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.
 
1848
 
 
1849
    """
 
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