/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-06-28 23:13:22 UTC
  • mto: (7490.40.37 work)
  • mto: This revision was merged to the branch mainline in revision 7519.
  • Revision ID: jelmer@jelmer.uk-20200628231322-6h0upmtsh8ec7504
some refactoring.

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 = path.encode('utf-8')
 
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(from_dir.encode("utf-8"), parent_id)
 
456
            else:
 
457
                root_ie = self._get_file_ie(
 
458
                    store, from_dir.encode("utf-8"),
 
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, from_dir.encode("utf-8"),
 
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
 
 
728
def tree_delta_from_git_changes(changes, mappings,
 
729
                                specific_files=None,
 
730
                                require_versioned=False, include_root=False,
 
731
                                source_extras=None, target_extras=None):
 
732
    """Create a TreeDelta from two git trees.
 
733
 
 
734
    source and target are iterators over tuples with:
 
735
        (filename, sha, mode)
 
736
    """
 
737
    (old_mapping, new_mapping) = mappings
 
738
    if target_extras is None:
 
739
        target_extras = set()
 
740
    if source_extras is None:
 
741
        source_extras = set()
 
742
    ret = delta.TreeDelta()
 
743
    added = []
 
744
    for (change_type, old, new) in changes:
 
745
        (oldpath, oldmode, oldsha) = old
 
746
        (newpath, newmode, newsha) = new
 
747
        if newpath == b'' and not include_root:
 
748
            continue
 
749
        copied = (change_type == 'copy')
 
750
        if oldpath is not None:
 
751
            oldpath_decoded = decode_git_path(oldpath)
 
752
        else:
 
753
            oldpath_decoded = None
 
754
        if newpath is not None:
 
755
            newpath_decoded = decode_git_path(newpath)
 
756
        else:
 
757
            newpath_decoded = None
 
758
        if not (specific_files is None or
 
759
                (oldpath is not None and
 
760
                    osutils.is_inside_or_parent_of_any(
 
761
                        specific_files, oldpath_decoded)) or
 
762
                (newpath is not None and
 
763
                    osutils.is_inside_or_parent_of_any(
 
764
                        specific_files, newpath_decoded))):
 
765
            continue
 
766
 
 
767
        if oldpath is None:
 
768
            oldexe = None
 
769
            oldkind = None
 
770
            oldname = None
 
771
            oldparent = None
 
772
            oldversioned = False
 
773
        else:
 
774
            oldversioned = (oldpath not in source_extras)
 
775
            if oldmode:
 
776
                oldexe = mode_is_executable(oldmode)
 
777
                oldkind = mode_kind(oldmode)
 
778
            else:
 
779
                oldexe = False
 
780
                oldkind = None
 
781
            if oldpath == b'':
 
782
                oldparent = None
 
783
                oldname = u''
 
784
            else:
 
785
                (oldparentpath, oldname) = osutils.split(oldpath_decoded)
 
786
                oldparent = old_mapping.generate_file_id(oldparentpath)
 
787
        if newpath is None:
 
788
            newexe = None
 
789
            newkind = None
 
790
            newname = None
 
791
            newparent = None
 
792
            newversioned = False
 
793
        else:
 
794
            newversioned = (newpath not in target_extras)
 
795
            if newmode:
 
796
                newexe = mode_is_executable(newmode)
 
797
                newkind = mode_kind(newmode)
 
798
            else:
 
799
                newexe = False
 
800
                newkind = None
 
801
            if newpath_decoded == u'':
 
802
                newparent = None
 
803
                newname = u''
 
804
            else:
 
805
                newparentpath, newname = osutils.split(newpath_decoded)
 
806
                newparent = new_mapping.generate_file_id(newparentpath)
 
807
        if oldversioned and not copied:
 
808
            fileid = old_mapping.generate_file_id(oldpath_decoded)
 
809
        elif newversioned:
 
810
            fileid = new_mapping.generate_file_id(newpath_decoded)
 
811
        else:
 
812
            fileid = None
 
813
        if old_mapping.is_special_file(oldpath):
 
814
            oldpath = None
 
815
        if new_mapping.is_special_file(newpath):
 
816
            newpath = None
 
817
        if oldpath is None and newpath is None:
 
818
            continue
 
819
        change = _mod_tree.TreeChange(
 
820
            fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
 
821
            (oldversioned, newversioned),
 
822
            (oldparent, newparent), (oldname, newname),
 
823
            (oldkind, newkind), (oldexe, newexe),
 
824
            copied=copied)
 
825
        if newpath is not None and not newversioned and newkind != 'directory':
 
826
            change.file_id = None
 
827
            ret.unversioned.append(change)
 
828
        elif change_type == 'add':
 
829
            added.append((newpath, newkind))
 
830
        elif newpath is None or newmode == 0:
 
831
            ret.removed.append(change)
 
832
        elif change_type == 'delete':
 
833
            ret.removed.append(change)
 
834
        elif change_type == 'copy':
 
835
            if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
 
836
                continue
 
837
            ret.copied.append(change)
 
838
        elif change_type == 'rename':
 
839
            if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
 
840
                continue
 
841
            ret.renamed.append(change)
 
842
        elif mode_kind(oldmode) != mode_kind(newmode):
 
843
            ret.kind_changed.append(change)
 
844
        elif oldsha != newsha or oldmode != newmode:
 
845
            if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
 
846
                continue
 
847
            ret.modified.append(change)
 
848
        else:
 
849
            ret.unchanged.append(change)
 
850
 
 
851
    implicit_dirs = {b''}
 
852
    for path, kind in added:
 
853
        if kind == 'directory' or path in target_extras:
 
854
            continue
 
855
        implicit_dirs.update(osutils.parent_directories(path))
 
856
 
 
857
    for path, kind in added:
 
858
        if kind == 'directory' and path not in implicit_dirs:
 
859
            continue
 
860
        path_decoded = osutils.normalized_filename(path)[0]
 
861
        parent_path, basename = osutils.split(path_decoded)
 
862
        parent_id = new_mapping.generate_file_id(parent_path)
 
863
        file_id = new_mapping.generate_file_id(path_decoded)
 
864
        ret.added.append(
 
865
            _mod_tree.TreeChange(
 
866
                file_id, (None, path_decoded), True,
 
867
                (False, True),
 
868
                (None, parent_id),
 
869
                (None, basename), (None, kind), (None, False)))
 
870
 
 
871
    return ret
 
872
 
 
873
 
 
874
def changes_from_git_changes(changes, mapping, specific_files=None,
 
875
                             include_unchanged=False, source_extras=None,
 
876
                             target_extras=None):
 
877
    """Create a iter_changes-like generator from a git stream.
 
878
 
 
879
    source and target are iterators over tuples with:
 
880
        (filename, sha, mode)
 
881
    """
 
882
    if target_extras is None:
 
883
        target_extras = set()
 
884
    if source_extras is None:
 
885
        source_extras = set()
 
886
    for (change_type, old, new) in changes:
 
887
        if change_type == 'unchanged' and not include_unchanged:
 
888
            continue
 
889
        (oldpath, oldmode, oldsha) = old
 
890
        (newpath, newmode, newsha) = new
 
891
        if oldpath is not None:
 
892
            oldpath_decoded = decode_git_path(oldpath)
 
893
        else:
 
894
            oldpath_decoded = None
 
895
        if newpath is not None:
 
896
            newpath_decoded = decode_git_path(newpath)
 
897
        else:
 
898
            newpath_decoded = None
 
899
        if not (specific_files is None or
 
900
                (oldpath_decoded is not None and
 
901
                    osutils.is_inside_or_parent_of_any(
 
902
                        specific_files, oldpath_decoded)) or
 
903
                (newpath_decoded is not None and
 
904
                    osutils.is_inside_or_parent_of_any(
 
905
                        specific_files, newpath_decoded))):
 
906
            continue
 
907
        if oldpath is not None and mapping.is_special_file(oldpath):
 
908
            continue
 
909
        if newpath is not None and mapping.is_special_file(newpath):
 
910
            continue
 
911
        if oldpath is None:
 
912
            oldexe = None
 
913
            oldkind = None
 
914
            oldname = None
 
915
            oldparent = None
 
916
            oldversioned = False
 
917
        else:
 
918
            oldversioned = (oldpath not in source_extras)
 
919
            if oldmode:
 
920
                oldexe = mode_is_executable(oldmode)
 
921
                oldkind = mode_kind(oldmode)
 
922
            else:
 
923
                oldexe = False
 
924
                oldkind = None
 
925
            if oldpath_decoded == u'':
 
926
                oldparent = None
 
927
                oldname = u''
 
928
            else:
 
929
                (oldparentpath, oldname) = osutils.split(oldpath_decoded)
 
930
                oldparent = mapping.generate_file_id(oldparentpath)
 
931
        if newpath is None:
 
932
            newexe = None
 
933
            newkind = None
 
934
            newname = None
 
935
            newparent = None
 
936
            newversioned = False
 
937
        else:
 
938
            newversioned = (newpath not in target_extras)
 
939
            if newmode:
 
940
                newexe = mode_is_executable(newmode)
 
941
                newkind = mode_kind(newmode)
 
942
            else:
 
943
                newexe = False
 
944
                newkind = None
 
945
            if newpath_decoded == u'':
 
946
                newparent = None
 
947
                newname = u''
 
948
            else:
 
949
                newparentpath, newname = osutils.split(newpath_decoded)
 
950
                newparent = mapping.generate_file_id(newparentpath)
 
951
        if (not include_unchanged and
 
952
                oldkind == 'directory' and newkind == 'directory' and
 
953
                oldpath_decoded == newpath_decoded):
 
954
            continue
 
955
        if oldversioned and change_type != 'copy':
 
956
            fileid = mapping.generate_file_id(oldpath_decoded)
 
957
        elif newversioned:
 
958
            fileid = mapping.generate_file_id(newpath_decoded)
 
959
        else:
 
960
            fileid = None
 
961
        yield _mod_tree.TreeChange(
 
962
            fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
 
963
            (oldversioned, newversioned),
 
964
            (oldparent, newparent), (oldname, newname),
 
965
            (oldkind, newkind), (oldexe, newexe),
 
966
            copied=(change_type == 'copy'))
 
967
 
 
968
 
 
969
class InterGitTrees(_mod_tree.InterTree):
 
970
    """InterTree that works between two git trees."""
 
971
 
 
972
    _matching_from_tree_format = None
 
973
    _matching_to_tree_format = None
 
974
    _test_mutable_trees_to_test_trees = None
 
975
 
 
976
    @classmethod
 
977
    def is_compatible(cls, source, target):
 
978
        return (isinstance(source, GitRevisionTree) and
 
979
                isinstance(target, GitRevisionTree))
 
980
 
 
981
    def compare(self, want_unchanged=False, specific_files=None,
 
982
                extra_trees=None, require_versioned=False, include_root=False,
 
983
                want_unversioned=False):
 
984
        with self.lock_read():
 
985
            changes, source_extras, target_extras = self._iter_git_changes(
 
986
                want_unchanged=want_unchanged,
 
987
                require_versioned=require_versioned,
 
988
                specific_files=specific_files,
 
989
                extra_trees=extra_trees,
 
990
                want_unversioned=want_unversioned)
 
991
            return tree_delta_from_git_changes(
 
992
                changes, (self.source.mapping, self.target.mapping),
 
993
                specific_files=specific_files,
 
994
                include_root=include_root,
 
995
                source_extras=source_extras, target_extras=target_extras)
 
996
 
 
997
    def iter_changes(self, include_unchanged=False, specific_files=None,
 
998
                     pb=None, extra_trees=[], require_versioned=True,
 
999
                     want_unversioned=False):
 
1000
        with self.lock_read():
 
1001
            changes, source_extras, target_extras = self._iter_git_changes(
 
1002
                want_unchanged=include_unchanged,
 
1003
                require_versioned=require_versioned,
 
1004
                specific_files=specific_files,
 
1005
                extra_trees=extra_trees,
 
1006
                want_unversioned=want_unversioned)
 
1007
            return changes_from_git_changes(
 
1008
                changes, self.target.mapping,
 
1009
                specific_files=specific_files,
 
1010
                include_unchanged=include_unchanged,
 
1011
                source_extras=source_extras,
 
1012
                target_extras=target_extras)
 
1013
 
 
1014
    def _iter_git_changes(self, want_unchanged=False, specific_files=None,
 
1015
                          require_versioned=False, extra_trees=None,
 
1016
                          want_unversioned=False):
 
1017
        raise NotImplementedError(self._iter_git_changes)
 
1018
 
 
1019
    def find_target_path(self, path, recurse='none'):
 
1020
        ret = self.find_target_paths([path], recurse=recurse)
 
1021
        return ret[path]
 
1022
 
 
1023
    def find_source_path(self, path, recurse='none'):
 
1024
        ret = self.find_source_paths([path], recurse=recurse)
 
1025
        return ret[path]
 
1026
 
 
1027
    def find_target_paths(self, paths, recurse='none'):
 
1028
        paths = set(paths)
 
1029
        ret = {}
 
1030
        changes = self._iter_git_changes(specific_files=paths)[0]
 
1031
        for (change_type, old, new) in changes:
 
1032
            if old[0] is None:
 
1033
                continue
 
1034
            oldpath = decode_git_path(old[0])
 
1035
            if oldpath in paths:
 
1036
                ret[oldpath] = decode_git_path(new[0]) if new[0] else None
 
1037
        for path in paths:
 
1038
            if path not in ret:
 
1039
                if self.source.has_filename(path):
 
1040
                    if self.target.has_filename(path):
 
1041
                        ret[path] = path
 
1042
                    else:
 
1043
                        ret[path] = None
 
1044
                else:
 
1045
                    raise errors.NoSuchFile(path)
 
1046
        return ret
 
1047
 
 
1048
    def find_source_paths(self, paths, recurse='none'):
 
1049
        paths = set(paths)
 
1050
        ret = {}
 
1051
        changes = self._iter_git_changes(specific_files=paths)[0]
 
1052
        for (change_type, old, new) in changes:
 
1053
            if new[0] is None:
 
1054
                continue
 
1055
            newpath = decode_git_path(new[0])
 
1056
            if newpath in paths:
 
1057
                ret[newpath] = decode_git_path(old[0]) if old[0] else None
 
1058
        for path in paths:
 
1059
            if path not in ret:
 
1060
                if self.target.has_filename(path):
 
1061
                    if self.source.has_filename(path):
 
1062
                        ret[path] = path
 
1063
                    else:
 
1064
                        ret[path] = None
 
1065
                else:
 
1066
                    raise errors.NoSuchFile(path)
 
1067
        return ret
 
1068
 
 
1069
 
 
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):
 
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=True,
 
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):
 
1112
 
 
1113
    def __init__(self):
 
1114
        self._lock_mode = None
 
1115
        self._lock_count = 0
 
1116
        self._versioned_dirs = None
 
1117
        self._index_dirty = False
 
1118
        self._submodules = None
 
1119
 
 
1120
    def is_versioned(self, path):
 
1121
        with self.lock_read():
 
1122
            path = encode_git_path(path.rstrip('/'))
 
1123
            (index, subpath) = self._lookup_index(path)
 
1124
            return (subpath in index or self._has_dir(path))
 
1125
 
 
1126
    def _has_dir(self, path):
 
1127
        if not isinstance(path, bytes):
 
1128
            raise TypeError(path)
 
1129
        if path == b"":
 
1130
            return True
 
1131
        if self._versioned_dirs is None:
 
1132
            self._load_dirs()
 
1133
        return path in self._versioned_dirs
 
1134
 
 
1135
    def _load_dirs(self):
 
1136
        if self._lock_mode is None:
 
1137
            raise errors.ObjectNotLocked(self)
 
1138
        self._versioned_dirs = set()
 
1139
        for p, i in self._recurse_index_entries():
 
1140
            self._ensure_versioned_dir(posixpath.dirname(p))
 
1141
 
 
1142
    def _ensure_versioned_dir(self, dirname):
 
1143
        if not isinstance(dirname, bytes):
 
1144
            raise TypeError(dirname)
 
1145
        if dirname in self._versioned_dirs:
 
1146
            return
 
1147
        if dirname != b"":
 
1148
            self._ensure_versioned_dir(posixpath.dirname(dirname))
 
1149
        self._versioned_dirs.add(dirname)
 
1150
 
 
1151
    def path2id(self, path):
 
1152
        with self.lock_read():
 
1153
            path = path.rstrip('/')
 
1154
            if self.is_versioned(path.rstrip('/')):
 
1155
                return self.mapping.generate_file_id(
 
1156
                    osutils.safe_unicode(path))
 
1157
            return None
 
1158
 
 
1159
    def id2path(self, file_id, recurse='down'):
 
1160
        if file_id is None:
 
1161
            return ''
 
1162
        if type(file_id) is not bytes:
 
1163
            raise TypeError(file_id)
 
1164
        with self.lock_read():
 
1165
            try:
 
1166
                path = self.mapping.parse_file_id(file_id)
 
1167
            except ValueError:
 
1168
                raise errors.NoSuchId(self, file_id)
 
1169
            if self.is_versioned(path):
 
1170
                return path
 
1171
            raise errors.NoSuchId(self, file_id)
 
1172
 
 
1173
    def _set_root_id(self, file_id):
 
1174
        raise errors.UnsupportedOperation(self._set_root_id, self)
 
1175
 
 
1176
    def _add(self, files, ids, kinds):
 
1177
        for (path, file_id, kind) in zip(files, ids, kinds):
 
1178
            if file_id is not None:
 
1179
                raise workingtree.SettingFileIdUnsupported()
 
1180
            path, can_access = osutils.normalized_filename(path)
 
1181
            if not can_access:
 
1182
                raise errors.InvalidNormalization(path)
 
1183
            self._index_add_entry(path, kind)
 
1184
 
 
1185
    def _read_submodule_head(self, path):
 
1186
        raise NotImplementedError(self._read_submodule_head)
 
1187
 
 
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
    def _lookup_index(self, encoded_path):
 
1201
        if not isinstance(encoded_path, bytes):
 
1202
            raise TypeError(encoded_path)
 
1203
        # Common case:
 
1204
        if encoded_path in self.index:
 
1205
            return self.index, encoded_path
 
1206
        # TODO(jelmer): Perhaps have a cache with paths under which some
 
1207
        # submodules exist?
 
1208
        index = self.index
 
1209
        remaining_path = encoded_path
 
1210
        while True:
 
1211
            parts = remaining_path.split(b'/')
 
1212
            for i in range(1, len(parts)):
 
1213
                basepath = b'/'.join(parts[:i])
 
1214
                try:
 
1215
                    (ctime, mtime, dev, ino, mode, uid, gid, size, sha,
 
1216
                     flags) = index[basepath]
 
1217
                except KeyError:
 
1218
                    continue
 
1219
                else:
 
1220
                    if S_ISGITLINK(mode):
 
1221
                        index = self._get_submodule_index(basepath)
 
1222
                        remaining_path = b'/'.join(parts[i:])
 
1223
                        break
 
1224
                    else:
 
1225
                        return index, remaining_path
 
1226
            else:
 
1227
                return index, remaining_path
 
1228
        return index, remaining_path
 
1229
 
 
1230
    def _index_del_entry(self, index, path):
 
1231
        del index[path]
 
1232
        # TODO(jelmer): Keep track of dirty per index
 
1233
        self._index_dirty = True
 
1234
 
 
1235
    def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
 
1236
        if kind == "directory":
 
1237
            # Git indexes don't contain directories
 
1238
            return
 
1239
        if kind == "file":
 
1240
            blob = Blob()
 
1241
            try:
 
1242
                file, stat_val = self.get_file_with_stat(path)
 
1243
            except (errors.NoSuchFile, IOError):
 
1244
                # TODO: Rather than come up with something here, use the old
 
1245
                # index
 
1246
                file = BytesIO()
 
1247
                stat_val = os.stat_result(
 
1248
                    (stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
 
1249
            with file:
 
1250
                blob.set_raw_string(file.read())
 
1251
            # Add object to the repository if it didn't exist yet
 
1252
            if blob.id not in self.store:
 
1253
                self.store.add_object(blob)
 
1254
            hexsha = blob.id
 
1255
        elif kind == "symlink":
 
1256
            blob = Blob()
 
1257
            try:
 
1258
                stat_val = self._lstat(path)
 
1259
            except EnvironmentError:
 
1260
                # TODO: Rather than come up with something here, use the
 
1261
                # old index
 
1262
                stat_val = os.stat_result(
 
1263
                    (stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
 
1264
            blob.set_raw_string(
 
1265
                self.get_symlink_target(path).encode("utf-8"))
 
1266
            # Add object to the repository if it didn't exist yet
 
1267
            if blob.id not in self.store:
 
1268
                self.store.add_object(blob)
 
1269
            hexsha = blob.id
 
1270
        elif kind == "tree-reference":
 
1271
            if reference_revision is not None:
 
1272
                hexsha = self.branch.lookup_bzr_revision_id(
 
1273
                    reference_revision)[0]
 
1274
            else:
 
1275
                hexsha = self._read_submodule_head(path)
 
1276
                if hexsha is None:
 
1277
                    raise errors.NoCommits(path)
 
1278
            try:
 
1279
                stat_val = self._lstat(path)
 
1280
            except EnvironmentError:
 
1281
                stat_val = os.stat_result(
 
1282
                    (S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
 
1283
            stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
 
1284
        else:
 
1285
            raise AssertionError("unknown kind '%s'" % kind)
 
1286
        # Add an entry to the index or update the existing entry
 
1287
        ensure_normalized_path(path)
 
1288
        encoded_path = encode_git_path(path)
 
1289
        if b'\r' in encoded_path or b'\n' in encoded_path:
 
1290
            # TODO(jelmer): Why do we need to do this?
 
1291
            trace.mutter('ignoring path with invalid newline in it: %r', path)
 
1292
            return
 
1293
        (index, index_path) = self._lookup_index(encoded_path)
 
1294
        index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
 
1295
        self._index_dirty = True
 
1296
        if self._versioned_dirs is not None:
 
1297
            self._ensure_versioned_dir(index_path)
 
1298
 
 
1299
    def _recurse_index_entries(self, index=None, basepath=b"",
 
1300
                               recurse_nested=False):
 
1301
        # Iterate over all index entries
 
1302
        with self.lock_read():
 
1303
            if index is None:
 
1304
                index = self.index
 
1305
            for path, value in index.items():
 
1306
                (ctime, mtime, dev, ino, mode, uid, gid, size, sha,
 
1307
                 flags) = value
 
1308
                if S_ISGITLINK(mode) and recurse_nested:
 
1309
                    subindex = self._get_submodule_index(path)
 
1310
                    for entry in self._recurse_index_entries(
 
1311
                            index=subindex, basepath=path,
 
1312
                            recurse_nested=recurse_nested):
 
1313
                        yield entry
 
1314
                else:
 
1315
                    yield (posixpath.join(basepath, path), value)
 
1316
 
 
1317
    def iter_entries_by_dir(self, specific_files=None,
 
1318
                            recurse_nested=False):
 
1319
        with self.lock_read():
 
1320
            if specific_files is not None:
 
1321
                specific_files = set(specific_files)
 
1322
            else:
 
1323
                specific_files = None
 
1324
            root_ie = self._get_dir_ie(u"", None)
 
1325
            ret = {}
 
1326
            if specific_files is None or u"" in specific_files:
 
1327
                ret[(u"", u"")] = root_ie
 
1328
            dir_ids = {u"": root_ie.file_id}
 
1329
            for path, value in self._recurse_index_entries(
 
1330
                    recurse_nested=recurse_nested):
 
1331
                if self.mapping.is_special_file(path):
 
1332
                    continue
 
1333
                path = decode_git_path(path)
 
1334
                if specific_files is not None and path not in specific_files:
 
1335
                    continue
 
1336
                (parent, name) = posixpath.split(path)
 
1337
                try:
 
1338
                    file_ie = self._get_file_ie(name, path, value, None)
 
1339
                except errors.NoSuchFile:
 
1340
                    continue
 
1341
                if specific_files is None:
 
1342
                    for (dir_path, dir_ie) in self._add_missing_parent_ids(
 
1343
                            parent, dir_ids):
 
1344
                        ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
 
1345
                file_ie.parent_id = self.path2id(parent)
 
1346
                ret[(posixpath.dirname(path), path)] = file_ie
 
1347
            # Special casing for directories
 
1348
            if specific_files:
 
1349
                for path in specific_files:
 
1350
                    key = (posixpath.dirname(path), path)
 
1351
                    if key not in ret and self.is_versioned(path):
 
1352
                        ret[key] = self._get_dir_ie(path, self.path2id(key[0]))
 
1353
            return ((path, ie) for ((_, path), ie) in sorted(viewitems(ret)))
 
1354
 
 
1355
    def iter_references(self):
 
1356
        if self.supports_tree_reference():
 
1357
            # TODO(jelmer): Implement a more efficient version of this
 
1358
            for path, entry in self.iter_entries_by_dir():
 
1359
                if entry.kind == 'tree-reference':
 
1360
                    yield path
 
1361
 
 
1362
    def _get_dir_ie(self, path, parent_id):
 
1363
        file_id = self.path2id(path)
 
1364
        return GitTreeDirectory(file_id,
 
1365
                                posixpath.basename(path).strip("/"), parent_id)
 
1366
 
 
1367
    def _get_file_ie(self, name, path, value, parent_id):
 
1368
        if not isinstance(name, text_type):
 
1369
            raise TypeError(name)
 
1370
        if not isinstance(path, text_type):
 
1371
            raise TypeError(path)
 
1372
        if not isinstance(value, tuple) or len(value) != 10:
 
1373
            raise TypeError(value)
 
1374
        (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
 
1375
        file_id = self.path2id(path)
 
1376
        if not isinstance(file_id, bytes):
 
1377
            raise TypeError(file_id)
 
1378
        kind = mode_kind(mode)
 
1379
        ie = entry_factory[kind](file_id, name, parent_id)
 
1380
        if kind == 'symlink':
 
1381
            ie.symlink_target = self.get_symlink_target(path)
 
1382
        elif kind == 'tree-reference':
 
1383
            ie.reference_revision = self.get_reference_revision(path)
 
1384
        else:
 
1385
            try:
 
1386
                data = self.get_file_text(path)
 
1387
            except errors.NoSuchFile:
 
1388
                data = None
 
1389
            except IOError as e:
 
1390
                if e.errno != errno.ENOENT:
 
1391
                    raise
 
1392
                data = None
 
1393
            if data is None:
 
1394
                data = self.branch.repository._git.object_store[sha].data
 
1395
            ie.text_sha1 = osutils.sha_string(data)
 
1396
            ie.text_size = len(data)
 
1397
            ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
1398
        return ie
 
1399
 
 
1400
    def _add_missing_parent_ids(self, path, dir_ids):
 
1401
        if path in dir_ids:
 
1402
            return []
 
1403
        parent = posixpath.dirname(path).strip("/")
 
1404
        ret = self._add_missing_parent_ids(parent, dir_ids)
 
1405
        parent_id = dir_ids[parent]
 
1406
        ie = self._get_dir_ie(path, parent_id)
 
1407
        dir_ids[path] = ie.file_id
 
1408
        ret.append((path, ie))
 
1409
        return ret
 
1410
 
 
1411
    def _comparison_data(self, entry, path):
 
1412
        if entry is None:
 
1413
            return None, False, None
 
1414
        return entry.kind, entry.executable, None
 
1415
 
 
1416
    def _unversion_path(self, path):
 
1417
        if self._lock_mode is None:
 
1418
            raise errors.ObjectNotLocked(self)
 
1419
        encoded_path = encode_git_path(path)
 
1420
        count = 0
 
1421
        (index, subpath) = self._lookup_index(encoded_path)
 
1422
        try:
 
1423
            self._index_del_entry(index, encoded_path)
 
1424
        except KeyError:
 
1425
            # A directory, perhaps?
 
1426
            # TODO(jelmer): Deletes that involve submodules?
 
1427
            for p in list(index):
 
1428
                if p.startswith(subpath + b"/"):
 
1429
                    count += 1
 
1430
                    self._index_del_entry(index, p)
 
1431
        else:
 
1432
            count = 1
 
1433
        self._versioned_dirs = None
 
1434
        return count
 
1435
 
 
1436
    def unversion(self, paths):
 
1437
        with self.lock_tree_write():
 
1438
            for path in paths:
 
1439
                if self._unversion_path(path) == 0:
 
1440
                    raise errors.NoSuchFile(path)
 
1441
            self._versioned_dirs = None
 
1442
            self.flush()
 
1443
 
 
1444
    def flush(self):
 
1445
        pass
 
1446
 
 
1447
    def update_basis_by_delta(self, revid, delta):
 
1448
        # TODO(jelmer): This shouldn't be called, it's inventory specific.
 
1449
        for (old_path, new_path, file_id, ie) in delta:
 
1450
            if old_path is not None:
 
1451
                (index, old_subpath) = self._lookup_index(
 
1452
                    encode_git_path(old_path))
 
1453
                if old_subpath in index:
 
1454
                    self._index_del_entry(index, old_subpath)
 
1455
                    self._versioned_dirs = None
 
1456
            if new_path is not None and ie.kind != 'directory':
 
1457
                self._index_add_entry(new_path, ie.kind)
 
1458
        self.flush()
 
1459
        self._set_merges_from_parent_ids([])
 
1460
 
 
1461
    def move(self, from_paths, to_dir=None, after=None):
 
1462
        rename_tuples = []
 
1463
        with self.lock_tree_write():
 
1464
            to_abs = self.abspath(to_dir)
 
1465
            if not os.path.isdir(to_abs):
 
1466
                raise errors.BzrMoveFailedError('', to_dir,
 
1467
                                                errors.NotADirectory(to_abs))
 
1468
 
 
1469
            for from_rel in from_paths:
 
1470
                from_tail = os.path.split(from_rel)[-1]
 
1471
                to_rel = os.path.join(to_dir, from_tail)
 
1472
                self.rename_one(from_rel, to_rel, after=after)
 
1473
                rename_tuples.append((from_rel, to_rel))
 
1474
            self.flush()
 
1475
            return rename_tuples
 
1476
 
 
1477
    def rename_one(self, from_rel, to_rel, after=None):
 
1478
        from_path = encode_git_path(from_rel)
 
1479
        to_rel, can_access = osutils.normalized_filename(to_rel)
 
1480
        if not can_access:
 
1481
            raise errors.InvalidNormalization(to_rel)
 
1482
        to_path = encode_git_path(to_rel)
 
1483
        with self.lock_tree_write():
 
1484
            if not after:
 
1485
                # Perhaps it's already moved?
 
1486
                after = (
 
1487
                    not self.has_filename(from_rel) and
 
1488
                    self.has_filename(to_rel) and
 
1489
                    not self.is_versioned(to_rel))
 
1490
            if after:
 
1491
                if not self.has_filename(to_rel):
 
1492
                    raise errors.BzrMoveFailedError(
 
1493
                        from_rel, to_rel, errors.NoSuchFile(to_rel))
 
1494
                if self.basis_tree().is_versioned(to_rel):
 
1495
                    raise errors.BzrMoveFailedError(
 
1496
                        from_rel, to_rel, errors.AlreadyVersionedError(to_rel))
 
1497
 
 
1498
                kind = self.kind(to_rel)
 
1499
            else:
 
1500
                try:
 
1501
                    to_kind = self.kind(to_rel)
 
1502
                except errors.NoSuchFile:
 
1503
                    exc_type = errors.BzrRenameFailedError
 
1504
                    to_kind = None
 
1505
                else:
 
1506
                    exc_type = errors.BzrMoveFailedError
 
1507
                if self.is_versioned(to_rel):
 
1508
                    raise exc_type(from_rel, to_rel,
 
1509
                                   errors.AlreadyVersionedError(to_rel))
 
1510
                if not self.has_filename(from_rel):
 
1511
                    raise errors.BzrMoveFailedError(
 
1512
                        from_rel, to_rel, errors.NoSuchFile(from_rel))
 
1513
                kind = self.kind(from_rel)
 
1514
                if not self.is_versioned(from_rel) and kind != 'directory':
 
1515
                    raise exc_type(from_rel, to_rel,
 
1516
                                   errors.NotVersionedError(from_rel))
 
1517
                if self.has_filename(to_rel):
 
1518
                    raise errors.RenameFailedFilesExist(
 
1519
                        from_rel, to_rel, errors.FileExists(to_rel))
 
1520
 
 
1521
                kind = self.kind(from_rel)
 
1522
 
 
1523
            if not after and kind != 'directory':
 
1524
                (index, from_subpath) = self._lookup_index(from_path)
 
1525
                if from_subpath not in index:
 
1526
                    # It's not a file
 
1527
                    raise errors.BzrMoveFailedError(
 
1528
                        from_rel, to_rel,
 
1529
                        errors.NotVersionedError(path=from_rel))
 
1530
 
 
1531
            if not after:
 
1532
                try:
 
1533
                    self._rename_one(from_rel, to_rel)
 
1534
                except OSError as e:
 
1535
                    if e.errno == errno.ENOENT:
 
1536
                        raise errors.BzrMoveFailedError(
 
1537
                            from_rel, to_rel, errors.NoSuchFile(to_rel))
 
1538
                    raise
 
1539
            if kind != 'directory':
 
1540
                (index, from_index_path) = self._lookup_index(from_path)
 
1541
                try:
 
1542
                    self._index_del_entry(index, from_path)
 
1543
                except KeyError:
 
1544
                    pass
 
1545
                self._index_add_entry(to_rel, kind)
 
1546
            else:
 
1547
                todo = [(p, i) for (p, i) in self._recurse_index_entries()
 
1548
                        if p.startswith(from_path + b'/')]
 
1549
                for child_path, child_value in todo:
 
1550
                    (child_to_index, child_to_index_path) = self._lookup_index(
 
1551
                        posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
 
1552
                    child_to_index[child_to_index_path] = child_value
 
1553
                    # TODO(jelmer): Mark individual index as dirty
 
1554
                    self._index_dirty = True
 
1555
                    (child_from_index, child_from_index_path) = self._lookup_index(
 
1556
                        child_path)
 
1557
                    self._index_del_entry(
 
1558
                        child_from_index, child_from_index_path)
 
1559
 
 
1560
            self._versioned_dirs = None
 
1561
            self.flush()
 
1562
 
 
1563
    def find_related_paths_across_trees(self, paths, trees=[],
 
1564
                                        require_versioned=True):
 
1565
        if paths is None:
 
1566
            return None
 
1567
 
 
1568
        if require_versioned:
 
1569
            trees = [self] + (trees if trees is not None else [])
 
1570
            unversioned = set()
 
1571
            for p in paths:
 
1572
                for t in trees:
 
1573
                    if t.is_versioned(p):
 
1574
                        break
 
1575
                else:
 
1576
                    unversioned.add(p)
 
1577
            if unversioned:
 
1578
                raise errors.PathsNotVersionedError(unversioned)
 
1579
 
 
1580
        return filter(self.is_versioned, paths)
 
1581
 
 
1582
    def path_content_summary(self, path):
 
1583
        """See Tree.path_content_summary."""
 
1584
        try:
 
1585
            stat_result = self._lstat(path)
 
1586
        except OSError as e:
 
1587
            if getattr(e, 'errno', None) == errno.ENOENT:
 
1588
                # no file.
 
1589
                return ('missing', None, None, None)
 
1590
            # propagate other errors
 
1591
            raise
 
1592
        kind = mode_kind(stat_result.st_mode)
 
1593
        if kind == 'file':
 
1594
            return self._file_content_summary(path, stat_result)
 
1595
        elif kind == 'directory':
 
1596
            # perhaps it looks like a plain directory, but it's really a
 
1597
            # reference.
 
1598
            if self._directory_is_tree_reference(path):
 
1599
                kind = 'tree-reference'
 
1600
            return kind, None, None, None
 
1601
        elif kind == 'symlink':
 
1602
            target = osutils.readlink(self.abspath(path))
 
1603
            return ('symlink', None, None, target)
 
1604
        else:
 
1605
            return (kind, None, None, None)
 
1606
 
 
1607
    def stored_kind(self, relpath):
 
1608
        (index, index_path) = self._lookup_index(encode_git_path(relpath))
 
1609
        if index is None:
 
1610
            return kind
 
1611
        try:
 
1612
            mode = index[index_path].mode
 
1613
        except KeyError:
 
1614
            return kind
 
1615
        else:
 
1616
            if S_ISGITLINK(mode):
 
1617
                return 'tree-reference'
 
1618
            return 'directory'
 
1619
 
 
1620
    def kind(self, relpath):
 
1621
        kind = osutils.file_kind(self.abspath(relpath))
 
1622
        if kind == 'directory':
 
1623
            if self._directory_is_tree_reference(relpath):
 
1624
                return 'tree-reference'
 
1625
            return 'directory'
 
1626
        else:
 
1627
            return kind
 
1628
 
 
1629
    def _live_entry(self, relpath):
 
1630
        raise NotImplementedError(self._live_entry)
 
1631
 
 
1632
    def get_transform(self, pb=None):
 
1633
        from ..transform import TreeTransform
 
1634
        return TreeTransform(self, pb=pb)
 
1635
 
 
1636
 
 
1637
 
 
1638
class InterIndexGitTree(InterGitTrees):
 
1639
    """InterTree that works between a Git revision tree and an index."""
 
1640
 
 
1641
    def __init__(self, source, target):
 
1642
        super(InterIndexGitTree, self).__init__(source, target)
 
1643
        self._index = target.index
 
1644
        if self.source.store == self.target.store:
 
1645
            self.store = self.source.store
 
1646
        else:
 
1647
            self.store = OverlayObjectStore(
 
1648
                [self.source.store, self.target.store])
 
1649
        self.rename_detector = RenameDetector(self.store)
 
1650
 
 
1651
    @classmethod
 
1652
    def is_compatible(cls, source, target):
 
1653
        return (isinstance(source, GitRevisionTree) and
 
1654
                isinstance(target, MutableGitIndexTree))
 
1655
 
 
1656
    def _iter_git_changes(self, want_unchanged=False, specific_files=None,
 
1657
                          require_versioned=False, extra_trees=None,
 
1658
                          want_unversioned=False):
 
1659
        trees = [self.source]
 
1660
        if extra_trees is not None:
 
1661
            trees.extend(extra_trees)
 
1662
        if specific_files is not None:
 
1663
            specific_files = self.target.find_related_paths_across_trees(
 
1664
                specific_files, trees,
 
1665
                require_versioned=require_versioned)
 
1666
        # TODO(jelmer): Restrict to specific_files, for performance reasons.
 
1667
        with self.lock_read():
 
1668
            changes, target_extras = changes_between_git_tree_and_working_copy(
 
1669
                self.source.store, self.source.tree,
 
1670
                self.target, want_unchanged=want_unchanged,
 
1671
                want_unversioned=want_unversioned,
 
1672
                rename_detector=self.rename_detector)
 
1673
            return changes, set(), target_extras
 
1674
 
 
1675
 
 
1676
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
 
1677
 
 
1678
 
 
1679
def changes_between_git_tree_and_working_copy(source_store, from_tree_sha, target,
 
1680
                                              want_unchanged=False,
 
1681
                                              want_unversioned=False,
 
1682
                                              rename_detector=None):
 
1683
    """Determine the changes between a git tree and a working tree with index.
 
1684
 
 
1685
    """
 
1686
    extras = set()
 
1687
    blobs = {}
 
1688
    # Report dirified directories to commit_tree first, so that they can be
 
1689
    # replaced with non-empty directories if they have contents.
 
1690
    dirified = []
 
1691
    trust_executable = target._supports_executable()
 
1692
    for path, index_entry in target._recurse_index_entries():
 
1693
        try:
 
1694
            live_entry = target._live_entry(path)
 
1695
        except EnvironmentError as e:
 
1696
            if e.errno == errno.ENOENT:
 
1697
                # Entry was removed; keep it listed, but mark it as gone.
 
1698
                blobs[path] = (ZERO_SHA, 0)
 
1699
            else:
 
1700
                raise
 
1701
        else:
 
1702
            if live_entry is None:
 
1703
                # Entry was turned into a directory.
 
1704
                # Maybe it's just a submodule that's not checked out?
 
1705
                if S_ISGITLINK(index_entry.mode):
 
1706
                    blobs[path] = (index_entry.sha, index_entry.mode)
 
1707
                else:
 
1708
                    dirified.append((path, Tree().id, stat.S_IFDIR))
 
1709
                    target.store.add_object(Tree())
 
1710
            else:
 
1711
                mode = live_entry.mode
 
1712
                if not trust_executable:
 
1713
                    if mode_is_executable(index_entry.mode):
 
1714
                        mode |= 0o111
 
1715
                    else:
 
1716
                        mode &= ~0o111
 
1717
                if live_entry.sha != index_entry.sha:
 
1718
                    rp = decode_git_path(path)
 
1719
                    if stat.S_ISREG(live_entry.mode):
 
1720
                        blob = Blob()
 
1721
                        with target.get_file(rp) as f:
 
1722
                            blob.data = f.read()
 
1723
                    elif stat.S_ISLNK(live_entry.mode):
 
1724
                        blob = Blob()
 
1725
                        blob.data = target.get_symlink_target(rp).encode(osutils._fs_enc)
 
1726
                    else:
 
1727
                        blob = None
 
1728
                    if blob is not None:
 
1729
                        target.store.add_object(blob)
 
1730
                blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
 
1731
    if want_unversioned:
 
1732
        for e in target._iter_files_recursive(include_dirs=False):
 
1733
            try:
 
1734
                e, accessible = osutils.normalized_filename(e)
 
1735
            except UnicodeDecodeError:
 
1736
                raise errors.BadFilenameEncoding(
 
1737
                    e, osutils._fs_enc)
 
1738
            np = encode_git_path(e)
 
1739
            if np in blobs:
 
1740
                continue
 
1741
            st = target._lstat(e)
 
1742
            if stat.S_ISDIR(st.st_mode):
 
1743
                blob = Tree()
 
1744
            elif stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode):
 
1745
                blob = blob_from_path_and_stat(
 
1746
                    target.abspath(e).encode(osutils._fs_enc), st)
 
1747
            else:
 
1748
                continue
 
1749
            target.store.add_object(blob)
 
1750
            blobs[np] = (blob.id, cleanup_mode(st.st_mode))
 
1751
            extras.add(np)
 
1752
    to_tree_sha = commit_tree(
 
1753
        target.store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
 
1754
    store = OverlayObjectStore([source_store, target.store])
 
1755
    return tree_changes(
 
1756
        store, from_tree_sha, to_tree_sha, include_trees=True,
 
1757
        rename_detector=rename_detector,
 
1758
        want_unchanged=want_unchanged, change_type_same=True), extras