/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-02-07 02:14:30 UTC
  • mto: This revision was merged to the branch mainline in revision 7492.
  • Revision ID: jelmer@jelmer.uk-20200207021430-m49iq3x4x8xlib6x
Drop python2 support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2009 Jelmer Vernooij <jelmer@samba.org>
 
1
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
18
18
"""Git Trees."""
19
19
 
20
 
from bzrlib import (
 
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
 
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,
21
56
    delta,
22
57
    errors,
 
58
    mutabletree,
 
59
    osutils,
23
60
    revisiontree,
24
 
    tree,
 
61
    trace,
 
62
    tree as _mod_tree,
 
63
    workingtree,
 
64
    )
 
65
from ..revision import (
 
66
    CURRENT_REVISION,
 
67
    NULL_REVISION,
25
68
    )
26
69
 
27
 
from bzrlib.plugins.git.inventory import (
28
 
    GitInventory,
29
 
    )
30
 
from bzrlib.plugins.git.mapping import (
 
70
from .mapping import (
31
71
    mode_is_executable,
32
72
    mode_kind,
33
 
    )
 
73
    default_mapping,
 
74
    )
 
75
from .transportgit import (
 
76
    TransportObjectStore,
 
77
    TransportRepo,
 
78
    )
 
79
 
 
80
 
 
81
class GitTreeDirectory(_mod_tree.TreeDirectory):
 
82
 
 
83
    __slots__ = ['file_id', 'name', 'parent_id', 'children']
 
84
 
 
85
    def __init__(self, file_id, name, parent_id):
 
86
        self.file_id = file_id
 
87
        self.name = name
 
88
        self.parent_id = parent_id
 
89
        # TODO(jelmer)
 
90
        self.children = {}
 
91
 
 
92
    @property
 
93
    def kind(self):
 
94
        return 'directory'
 
95
 
 
96
    @property
 
97
    def executable(self):
 
98
        return False
 
99
 
 
100
    def copy(self):
 
101
        return self.__class__(
 
102
            self.file_id, self.name, self.parent_id)
 
103
 
 
104
    def __repr__(self):
 
105
        return "%s(file_id=%r, name=%r, parent_id=%r)" % (
 
106
            self.__class__.__name__, self.file_id, self.name,
 
107
            self.parent_id)
 
108
 
 
109
    def __eq__(self, other):
 
110
        return (self.kind == other.kind and
 
111
                self.file_id == other.file_id and
 
112
                self.name == other.name and
 
113
                self.parent_id == other.parent_id)
 
114
 
 
115
 
 
116
class GitTreeFile(_mod_tree.TreeFile):
 
117
 
 
118
    __slots__ = ['file_id', 'name', 'parent_id', 'text_size', 'text_sha1',
 
119
                 'executable']
 
120
 
 
121
    def __init__(self, file_id, name, parent_id, text_size=None,
 
122
                 text_sha1=None, executable=None):
 
123
        self.file_id = file_id
 
124
        self.name = name
 
125
        self.parent_id = parent_id
 
126
        self.text_size = text_size
 
127
        self.text_sha1 = text_sha1
 
128
        self.executable = executable
 
129
 
 
130
    @property
 
131
    def kind(self):
 
132
        return 'file'
 
133
 
 
134
    def __eq__(self, other):
 
135
        return (self.kind == other.kind and
 
136
                self.file_id == other.file_id and
 
137
                self.name == other.name and
 
138
                self.parent_id == other.parent_id and
 
139
                self.text_sha1 == other.text_sha1 and
 
140
                self.text_size == other.text_size and
 
141
                self.executable == other.executable)
 
142
 
 
143
    def __repr__(self):
 
144
        return ("%s(file_id=%r, name=%r, parent_id=%r, text_size=%r, "
 
145
                "text_sha1=%r, executable=%r)") % (
 
146
            type(self).__name__, self.file_id, self.name, self.parent_id,
 
147
            self.text_size, self.text_sha1, self.executable)
 
148
 
 
149
    def copy(self):
 
150
        ret = self.__class__(
 
151
            self.file_id, self.name, self.parent_id)
 
152
        ret.text_sha1 = self.text_sha1
 
153
        ret.text_size = self.text_size
 
154
        ret.executable = self.executable
 
155
        return ret
 
156
 
 
157
 
 
158
class GitTreeSymlink(_mod_tree.TreeLink):
 
159
 
 
160
    __slots__ = ['file_id', 'name', 'parent_id', 'symlink_target']
 
161
 
 
162
    def __init__(self, file_id, name, parent_id,
 
163
                 symlink_target=None):
 
164
        self.file_id = file_id
 
165
        self.name = name
 
166
        self.parent_id = parent_id
 
167
        self.symlink_target = symlink_target
 
168
 
 
169
    @property
 
170
    def kind(self):
 
171
        return 'symlink'
 
172
 
 
173
    @property
 
174
    def executable(self):
 
175
        return False
 
176
 
 
177
    @property
 
178
    def text_size(self):
 
179
        return None
 
180
 
 
181
    def __repr__(self):
 
182
        return "%s(file_id=%r, name=%r, parent_id=%r, symlink_target=%r)" % (
 
183
            type(self).__name__, self.file_id, self.name, self.parent_id,
 
184
            self.symlink_target)
 
185
 
 
186
    def __eq__(self, other):
 
187
        return (self.kind == other.kind and
 
188
                self.file_id == other.file_id and
 
189
                self.name == other.name and
 
190
                self.parent_id == other.parent_id and
 
191
                self.symlink_target == other.symlink_target)
 
192
 
 
193
    def copy(self):
 
194
        return self.__class__(
 
195
            self.file_id, self.name, self.parent_id,
 
196
            self.symlink_target)
 
197
 
 
198
 
 
199
class GitTreeSubmodule(_mod_tree.TreeReference):
 
200
 
 
201
    __slots__ = ['file_id', 'name', 'parent_id', 'reference_revision']
 
202
 
 
203
    def __init__(self, file_id, name, parent_id, reference_revision=None):
 
204
        self.file_id = file_id
 
205
        self.name = name
 
206
        self.parent_id = parent_id
 
207
        self.reference_revision = reference_revision
 
208
 
 
209
    @property
 
210
    def executable(self):
 
211
        return False
 
212
 
 
213
    @property
 
214
    def kind(self):
 
215
        return 'tree-reference'
 
216
 
 
217
    def __repr__(self):
 
218
        return ("%s(file_id=%r, name=%r, parent_id=%r, "
 
219
                "reference_revision=%r)") % (
 
220
            type(self).__name__, self.file_id, self.name, self.parent_id,
 
221
            self.reference_revision)
 
222
 
 
223
    def __eq__(self, other):
 
224
        return (self.kind == other.kind and
 
225
                self.file_id == other.file_id and
 
226
                self.name == other.name and
 
227
                self.parent_id == other.parent_id and
 
228
                self.reference_revision == other.reference_revision)
 
229
 
 
230
    def copy(self):
 
231
        return self.__class__(
 
232
            self.file_id, self.name, self.parent_id,
 
233
            self.reference_revision)
 
234
 
 
235
 
 
236
entry_factory = {
 
237
    'directory': GitTreeDirectory,
 
238
    'file': GitTreeFile,
 
239
    'symlink': GitTreeSymlink,
 
240
    'tree-reference': GitTreeSubmodule,
 
241
    }
 
242
 
 
243
 
 
244
def ensure_normalized_path(path):
 
245
    """Check whether path is normalized.
 
246
 
 
247
    :raises InvalidNormalization: When path is not normalized, and cannot be
 
248
        accessed on this platform by the normalized path.
 
249
    :return: The NFC normalised version of path.
 
250
    """
 
251
    norm_path, can_access = osutils.normalized_filename(path)
 
252
    if norm_path != path:
 
253
        if can_access:
 
254
            return norm_path
 
255
        else:
 
256
            raise errors.InvalidNormalization(path)
 
257
    return path
34
258
 
35
259
 
36
260
class GitRevisionTree(revisiontree.RevisionTree):
39
263
    def __init__(self, repository, revision_id):
40
264
        self._revision_id = revision_id
41
265
        self._repository = repository
42
 
        store = repository._git.object_store
43
 
        assert isinstance(revision_id, str)
44
 
        git_id, self.mapping = repository.lookup_bzr_revision_id(revision_id)
45
 
        try:
46
 
            commit = store[git_id]
47
 
        except KeyError, r:
48
 
            raise errors.NoSuchRevision(repository, revision_id)
49
 
        self.tree = commit.tree
50
 
        fileid_map = self.mapping.get_fileid_map(store.__getitem__, self.tree)
51
 
        self._inventory = GitInventory(self.tree, self.mapping, fileid_map,
52
 
            store, revision_id)
 
266
        self._submodules = None
 
267
        self.store = repository._git.object_store
 
268
        if not isinstance(revision_id, bytes):
 
269
            raise TypeError(revision_id)
 
270
        self.commit_id, self.mapping = repository.lookup_bzr_revision_id(
 
271
            revision_id)
 
272
        if revision_id == NULL_REVISION:
 
273
            self.tree = None
 
274
            self.mapping = default_mapping
 
275
        else:
 
276
            try:
 
277
                commit = self.store[self.commit_id]
 
278
            except KeyError:
 
279
                raise errors.NoSuchRevision(repository, revision_id)
 
280
            self.tree = commit.tree
 
281
 
 
282
    def _submodule_info(self):
 
283
        if self._submodules is None:
 
284
            try:
 
285
                with self.get_file('.gitmodules') as f:
 
286
                    config = GitConfigFile.from_file(f)
 
287
                    self._submodules = {
 
288
                        path: (url, section)
 
289
                        for path, url, section in parse_submodules(config)}
 
290
            except errors.NoSuchFile:
 
291
                self._submodules = {}
 
292
        return self._submodules
 
293
 
 
294
    def _get_submodule_repository(self, relpath):
 
295
        if not isinstance(relpath, bytes):
 
296
            raise TypeError(relpath)
 
297
        try:
 
298
            info = self._submodule_info()[relpath]
 
299
        except KeyError:
 
300
            nested_repo_transport = self._repository.controldir.user_transport.clone(
 
301
                relpath.decode('utf-8'))
 
302
        else:
 
303
            nested_repo_transport = self._repository.controldir.control_transport.clone(
 
304
                posixpath.join('modules', info[1].decode('utf-8')))
 
305
        nested_controldir = _mod_controldir.ControlDir.open_from_transport(
 
306
            nested_repo_transport)
 
307
        return nested_controldir.find_repository()
 
308
 
 
309
    def _get_submodule_store(self, relpath):
 
310
        return self._get_submodule_repository(relpath)._git.object_store
 
311
 
 
312
    def get_nested_tree(self, path):
 
313
        encoded_path = path.encode('utf-8')
 
314
        nested_repo = self._get_submodule_repository(encoded_path)
 
315
        ref_rev = self.get_reference_revision(path)
 
316
        return nested_repo.revision_tree(ref_rev)
 
317
 
 
318
    def supports_rename_tracking(self):
 
319
        return False
 
320
 
 
321
    def get_file_revision(self, path):
 
322
        change_scanner = self._repository._file_change_scanner
 
323
        if self.commit_id == ZERO_SHA:
 
324
            return NULL_REVISION
 
325
        (unused_path, commit_id) = change_scanner.find_last_change_revision(
 
326
            path.encode('utf-8'), self.commit_id)
 
327
        return self._repository.lookup_foreign_revision_id(
 
328
            commit_id, self.mapping)
 
329
 
 
330
    def get_file_mtime(self, path):
 
331
        try:
 
332
            revid = self.get_file_revision(path)
 
333
        except KeyError:
 
334
            raise errors.NoSuchFile(path)
 
335
        try:
 
336
            rev = self._repository.get_revision(revid)
 
337
        except errors.NoSuchRevision:
 
338
            raise _mod_tree.FileTimestampUnavailable(path)
 
339
        return rev.timestamp
 
340
 
 
341
    def id2path(self, file_id, recurse='down'):
 
342
        try:
 
343
            path = self.mapping.parse_file_id(file_id)
 
344
        except ValueError:
 
345
            raise errors.NoSuchId(self, file_id)
 
346
        if self.is_versioned(path):
 
347
            return path
 
348
        raise errors.NoSuchId(self, file_id)
 
349
 
 
350
    def is_versioned(self, path):
 
351
        return self.has_filename(path)
 
352
 
 
353
    def path2id(self, path):
 
354
        if self.mapping.is_special_file(path):
 
355
            return None
 
356
        if not self.is_versioned(path):
 
357
            return None
 
358
        return self.mapping.generate_file_id(osutils.safe_unicode(path))
 
359
 
 
360
    def all_file_ids(self):
 
361
        raise errors.UnsupportedOperation(self.all_file_ids, self)
 
362
 
 
363
    def all_versioned_paths(self):
 
364
        ret = {u''}
 
365
        todo = [(self.store, b'', self.tree)]
 
366
        while todo:
 
367
            (store, path, tree_id) = todo.pop()
 
368
            if tree_id is None:
 
369
                continue
 
370
            tree = store[tree_id]
 
371
            for name, mode, hexsha in tree.items():
 
372
                subpath = posixpath.join(path, name)
 
373
                ret.add(subpath.decode('utf-8'))
 
374
                if stat.S_ISDIR(mode):
 
375
                    todo.append((store, subpath, hexsha))
 
376
        return ret
 
377
 
 
378
    def _lookup_path(self, path):
 
379
        if self.tree is None:
 
380
            raise errors.NoSuchFile(path)
 
381
 
 
382
        encoded_path = path.encode('utf-8')
 
383
        parts = encoded_path.split(b'/')
 
384
        hexsha = self.tree
 
385
        store = self.store
 
386
        mode = None
 
387
        for i, p in enumerate(parts):
 
388
            if not p:
 
389
                continue
 
390
            obj = store[hexsha]
 
391
            if not isinstance(obj, Tree):
 
392
                raise NotTreeError(hexsha)
 
393
            try:
 
394
                mode, hexsha = obj[p]
 
395
            except KeyError:
 
396
                raise errors.NoSuchFile(path)
 
397
            if S_ISGITLINK(mode) and i != len(parts) - 1:
 
398
                store = self._get_submodule_store(b'/'.join(parts[:i + 1]))
 
399
                hexsha = store[hexsha].tree
 
400
        return (store, mode, hexsha)
 
401
 
 
402
    def is_executable(self, path):
 
403
        (store, mode, hexsha) = self._lookup_path(path)
 
404
        if mode is None:
 
405
            # the tree root is a directory
 
406
            return False
 
407
        return mode_is_executable(mode)
 
408
 
 
409
    def kind(self, path):
 
410
        (store, mode, hexsha) = self._lookup_path(path)
 
411
        if mode is None:
 
412
            # the tree root is a directory
 
413
            return "directory"
 
414
        return mode_kind(mode)
 
415
 
 
416
    def has_filename(self, path):
 
417
        try:
 
418
            self._lookup_path(path)
 
419
        except errors.NoSuchFile:
 
420
            return False
 
421
        else:
 
422
            return True
 
423
 
 
424
    def _submodule_info(self):
 
425
        if self._submodules is None:
 
426
            try:
 
427
                with self.get_file('.gitmodules') as f:
 
428
                    config = GitConfigFile.from_file(f)
 
429
                    self._submodules = {
 
430
                        path: (url, section)
 
431
                        for path, url, section in parse_submodules(config)}
 
432
            except errors.NoSuchFile:
 
433
                self._submodules = {}
 
434
        return self._submodules
 
435
 
 
436
    def list_files(self, include_root=False, from_dir=None, recursive=True,
 
437
                   recurse_nested=False):
 
438
        if self.tree is None:
 
439
            return
 
440
        if from_dir is None or from_dir == '.':
 
441
            from_dir = u""
 
442
        (store, mode, hexsha) = self._lookup_path(from_dir)
 
443
        if mode is None:  # Root
 
444
            root_ie = self._get_dir_ie(b"", None)
 
445
        else:
 
446
            parent_path = posixpath.dirname(from_dir)
 
447
            parent_id = self.mapping.generate_file_id(parent_path)
 
448
            if mode_kind(mode) == 'directory':
 
449
                root_ie = self._get_dir_ie(from_dir.encode("utf-8"), parent_id)
 
450
            else:
 
451
                root_ie = self._get_file_ie(
 
452
                    store, from_dir.encode("utf-8"),
 
453
                    posixpath.basename(from_dir), mode, hexsha)
 
454
        if include_root:
 
455
            yield (from_dir, "V", root_ie.kind, root_ie)
 
456
        todo = []
 
457
        if root_ie.kind == 'directory':
 
458
            todo.append((store, from_dir.encode("utf-8"),
 
459
                         b"", hexsha, root_ie.file_id))
 
460
        while todo:
 
461
            (store, path, relpath, hexsha, parent_id) = todo.pop()
 
462
            tree = store[hexsha]
 
463
            for name, mode, hexsha in tree.iteritems():
 
464
                if self.mapping.is_special_file(name):
 
465
                    continue
 
466
                child_path = posixpath.join(path, name)
 
467
                child_relpath = posixpath.join(relpath, name)
 
468
                if S_ISGITLINK(mode) and recurse_nested:
 
469
                    mode = stat.S_IFDIR
 
470
                    store = self._get_submodule_store(child_relpath)
 
471
                    hexsha = store[hexsha].tree
 
472
                if stat.S_ISDIR(mode):
 
473
                    ie = self._get_dir_ie(child_path, parent_id)
 
474
                    if recursive:
 
475
                        todo.append(
 
476
                            (store, child_path, child_relpath, hexsha,
 
477
                             ie.file_id))
 
478
                else:
 
479
                    ie = self._get_file_ie(
 
480
                        store, child_path, name, mode, hexsha, parent_id)
 
481
                yield (child_relpath.decode('utf-8'), "V", ie.kind, ie)
 
482
 
 
483
    def _get_file_ie(self, store, path, name, mode, hexsha, parent_id):
 
484
        if not isinstance(path, bytes):
 
485
            raise TypeError(path)
 
486
        if not isinstance(name, bytes):
 
487
            raise TypeError(name)
 
488
        kind = mode_kind(mode)
 
489
        path = path.decode('utf-8')
 
490
        name = name.decode("utf-8")
 
491
        file_id = self.mapping.generate_file_id(path)
 
492
        ie = entry_factory[kind](file_id, name, parent_id)
 
493
        if kind == 'symlink':
 
494
            ie.symlink_target = store[hexsha].data.decode('utf-8')
 
495
        elif kind == 'tree-reference':
 
496
            ie.reference_revision = self.mapping.revision_id_foreign_to_bzr(
 
497
                hexsha)
 
498
        else:
 
499
            data = store[hexsha].data
 
500
            ie.text_sha1 = osutils.sha_string(data)
 
501
            ie.text_size = len(data)
 
502
            ie.executable = mode_is_executable(mode)
 
503
        return ie
 
504
 
 
505
    def _get_dir_ie(self, path, parent_id):
 
506
        path = path.decode('utf-8')
 
507
        file_id = self.mapping.generate_file_id(path)
 
508
        return GitTreeDirectory(file_id, posixpath.basename(path), parent_id)
 
509
 
 
510
    def iter_child_entries(self, path):
 
511
        (store, mode, tree_sha) = self._lookup_path(path)
 
512
 
 
513
        if mode is not None and not stat.S_ISDIR(mode):
 
514
            return
 
515
 
 
516
        encoded_path = path.encode('utf-8')
 
517
        file_id = self.path2id(path)
 
518
        tree = store[tree_sha]
 
519
        for name, mode, hexsha in tree.iteritems():
 
520
            if self.mapping.is_special_file(name):
 
521
                continue
 
522
            child_path = posixpath.join(encoded_path, name)
 
523
            if stat.S_ISDIR(mode):
 
524
                yield self._get_dir_ie(child_path, file_id)
 
525
            else:
 
526
                yield self._get_file_ie(store, child_path, name, mode, hexsha,
 
527
                                        file_id)
 
528
 
 
529
    def iter_entries_by_dir(self, specific_files=None,
 
530
                            recurse_nested=False):
 
531
        if self.tree is None:
 
532
            return
 
533
        if specific_files is not None:
 
534
            if specific_files in ([""], []):
 
535
                specific_files = None
 
536
            else:
 
537
                specific_files = set([p.encode('utf-8')
 
538
                                      for p in specific_files])
 
539
        todo = deque([(self.store, b"", self.tree, self.path2id(''))])
 
540
        if specific_files is None or u"" in specific_files:
 
541
            yield u"", self._get_dir_ie(b"", None)
 
542
        while todo:
 
543
            store, path, tree_sha, parent_id = todo.popleft()
 
544
            tree = store[tree_sha]
 
545
            extradirs = []
 
546
            for name, mode, hexsha in tree.iteritems():
 
547
                if self.mapping.is_special_file(name):
 
548
                    continue
 
549
                child_path = posixpath.join(path, name)
 
550
                child_path_decoded = child_path.decode('utf-8')
 
551
                if recurse_nested and S_ISGITLINK(mode):
 
552
                    mode = stat.S_IFDIR
 
553
                    store = self._get_submodule_store(child_path)
 
554
                    hexsha = store[hexsha].tree
 
555
                if stat.S_ISDIR(mode):
 
556
                    if (specific_files is None or
 
557
                            any([p for p in specific_files if p.startswith(
 
558
                                child_path)])):
 
559
                        extradirs.append(
 
560
                            (store, child_path, hexsha,
 
561
                             self.path2id(child_path_decoded)))
 
562
                if specific_files is None or child_path in specific_files:
 
563
                    if stat.S_ISDIR(mode):
 
564
                        yield (child_path_decoded,
 
565
                               self._get_dir_ie(child_path, parent_id))
 
566
                    else:
 
567
                        yield (child_path_decoded,
 
568
                               self._get_file_ie(store, child_path, name, mode,
 
569
                                                 hexsha, parent_id))
 
570
            todo.extendleft(reversed(extradirs))
 
571
 
 
572
    def iter_references(self):
 
573
        if self.supports_tree_reference():
 
574
            for path, entry in self.iter_entries_by_dir():
 
575
                if entry.kind == 'tree-reference':
 
576
                    yield path
53
577
 
54
578
    def get_revision_id(self):
55
579
        """See RevisionTree.get_revision_id."""
56
580
        return self._revision_id
57
581
 
58
 
    def get_file_text(self, file_id, path=None):
 
582
    def get_file_sha1(self, path, stat_value=None):
 
583
        if self.tree is None:
 
584
            raise errors.NoSuchFile(path)
 
585
        return osutils.sha_string(self.get_file_text(path))
 
586
 
 
587
    def get_file_verifier(self, path, stat_value=None):
 
588
        (store, mode, hexsha) = self._lookup_path(path)
 
589
        return ("GIT", hexsha)
 
590
 
 
591
    def get_file_size(self, path):
 
592
        (store, mode, hexsha) = self._lookup_path(path)
 
593
        if stat.S_ISREG(mode):
 
594
            return len(store[hexsha].data)
 
595
        return None
 
596
 
 
597
    def get_file_text(self, path):
59
598
        """See RevisionTree.get_file_text."""
60
 
        if path is not None:
61
 
            entry = self._inventory._get_ie(path)
62
 
        else:
63
 
            entry = self._inventory[file_id]
64
 
        if entry.kind in ('directory', 'tree-reference'):
65
 
            return ""
66
 
        return entry.object.data
67
 
 
68
 
 
69
 
def tree_delta_from_git_changes(changes, mapping,
70
 
        (old_fileid_map, new_fileid_map), specific_file=None,
71
 
        require_versioned=False):
 
599
        (store, mode, hexsha) = self._lookup_path(path)
 
600
        if stat.S_ISREG(mode):
 
601
            return store[hexsha].data
 
602
        else:
 
603
            return b""
 
604
 
 
605
    def get_symlink_target(self, path):
 
606
        """See RevisionTree.get_symlink_target."""
 
607
        (store, mode, hexsha) = self._lookup_path(path)
 
608
        if stat.S_ISLNK(mode):
 
609
            return store[hexsha].data.decode('utf-8')
 
610
        else:
 
611
            return None
 
612
 
 
613
    def get_reference_revision(self, path):
 
614
        """See RevisionTree.get_symlink_target."""
 
615
        (store, mode, hexsha) = self._lookup_path(path)
 
616
        if S_ISGITLINK(mode):
 
617
            try:
 
618
                nested_repo = self._get_submodule_repository(path.encode('utf-8'))
 
619
            except errors.NotBranchError:
 
620
                return self.mapping.revision_id_foreign_to_bzr(hexsha)
 
621
            else:
 
622
                return nested_repo.lookup_foreign_revision_id(hexsha)
 
623
        else:
 
624
            return None
 
625
 
 
626
    def _comparison_data(self, entry, path):
 
627
        if entry is None:
 
628
            return None, False, None
 
629
        return entry.kind, entry.executable, None
 
630
 
 
631
    def path_content_summary(self, path):
 
632
        """See Tree.path_content_summary."""
 
633
        try:
 
634
            (store, mode, hexsha) = self._lookup_path(path)
 
635
        except errors.NoSuchFile:
 
636
            return ('missing', None, None, None)
 
637
        kind = mode_kind(mode)
 
638
        if kind == 'file':
 
639
            executable = mode_is_executable(mode)
 
640
            contents = store[hexsha].data
 
641
            return (kind, len(contents), executable,
 
642
                    osutils.sha_string(contents))
 
643
        elif kind == 'symlink':
 
644
            return (kind, None, None, store[hexsha].data.decode('utf-8'))
 
645
        elif kind == 'tree-reference':
 
646
            nested_repo = self._get_submodule_repository(path.encode('utf-8'))
 
647
            return (kind, None, None,
 
648
                    nested_repo.lookup_foreign_revision_id(hexsha))
 
649
        else:
 
650
            return (kind, None, None, None)
 
651
 
 
652
    def find_related_paths_across_trees(self, paths, trees=[],
 
653
                                        require_versioned=True):
 
654
        if paths is None:
 
655
            return None
 
656
        if require_versioned:
 
657
            trees = [self] + (trees if trees is not None else [])
 
658
            unversioned = set()
 
659
            for p in paths:
 
660
                for t in trees:
 
661
                    if t.is_versioned(p):
 
662
                        break
 
663
                else:
 
664
                    unversioned.add(p)
 
665
            if unversioned:
 
666
                raise errors.PathsNotVersionedError(unversioned)
 
667
        return filter(self.is_versioned, paths)
 
668
 
 
669
    def _iter_tree_contents(self, include_trees=False):
 
670
        if self.tree is None:
 
671
            return iter([])
 
672
        return self.store.iter_tree_contents(
 
673
            self.tree, include_trees=include_trees)
 
674
 
 
675
    def annotate_iter(self, path, default_revision=CURRENT_REVISION):
 
676
        """Return an iterator of revision_id, line tuples.
 
677
 
 
678
        For working trees (and mutable trees in general), the special
 
679
        revision_id 'current:' will be used for lines that are new in this
 
680
        tree, e.g. uncommitted changes.
 
681
        :param default_revision: For lines that don't match a basis, mark them
 
682
            with this revision id. Not all implementations will make use of
 
683
            this value.
 
684
        """
 
685
        with self.lock_read():
 
686
            # Now we have the parents of this content
 
687
            from breezy.annotate import Annotator
 
688
            from .annotate import AnnotateProvider
 
689
            annotator = Annotator(AnnotateProvider(
 
690
                self._repository._file_change_scanner))
 
691
            this_key = (path, self.get_file_revision(path))
 
692
            annotations = [(key[-1], line)
 
693
                           for key, line in annotator.annotate_flat(this_key)]
 
694
            return annotations
 
695
 
 
696
    def _get_rules_searcher(self, default_searcher):
 
697
        return default_searcher
 
698
 
 
699
    def walkdirs(self, prefix=u""):
 
700
        (store, mode, hexsha) = self._lookup_path(prefix)
 
701
        todo = deque(
 
702
            [(store, prefix.encode('utf-8'), hexsha, self.path2id(prefix))])
 
703
        while todo:
 
704
            store, path, tree_sha, parent_id = todo.popleft()
 
705
            path_decoded = path.decode('utf-8')
 
706
            tree = store[tree_sha]
 
707
            children = []
 
708
            for name, mode, hexsha in tree.iteritems():
 
709
                if self.mapping.is_special_file(name):
 
710
                    continue
 
711
                child_path = posixpath.join(path, name)
 
712
                file_id = self.path2id(child_path.decode('utf-8'))
 
713
                if stat.S_ISDIR(mode):
 
714
                    todo.append((store, child_path, hexsha, file_id))
 
715
                children.append(
 
716
                    (child_path.decode('utf-8'), name.decode('utf-8'),
 
717
                        mode_kind(mode), None,
 
718
                        file_id, mode_kind(mode)))
 
719
            yield (path_decoded, parent_id), children
 
720
 
 
721
 
 
722
def tree_delta_from_git_changes(changes, mappings,
 
723
                                specific_files=None,
 
724
                                require_versioned=False, include_root=False,
 
725
                                target_extras=None):
72
726
    """Create a TreeDelta from two git trees.
73
727
 
74
728
    source and target are iterators over tuples with:
75
729
        (filename, sha, mode)
76
730
    """
 
731
    (old_mapping, new_mapping) = mappings
 
732
    if target_extras is None:
 
733
        target_extras = set()
77
734
    ret = delta.TreeDelta()
 
735
    added = []
78
736
    for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
79
 
        if mapping.is_control_file(oldpath):
 
737
        if newpath == b'' and not include_root:
 
738
            continue
 
739
        if oldpath is not None:
 
740
            oldpath_decoded = oldpath.decode('utf-8')
 
741
        else:
 
742
            oldpath_decoded = None
 
743
        if newpath is not None:
 
744
            newpath_decoded = newpath.decode('utf-8')
 
745
        else:
 
746
            newpath_decoded = None
 
747
        if not (specific_files is None or
 
748
                (oldpath is not None and
 
749
                    osutils.is_inside_or_parent_of_any(
 
750
                        specific_files, oldpath_decoded)) or
 
751
                (newpath is not None and
 
752
                    osutils.is_inside_or_parent_of_any(
 
753
                        specific_files, newpath_decoded))):
 
754
            continue
 
755
 
 
756
        if oldpath_decoded is None:
 
757
            fileid = new_mapping.generate_file_id(newpath_decoded)
 
758
            oldexe = None
 
759
            oldkind = None
 
760
            oldname = None
 
761
            oldparent = None
 
762
            oldversioned = False
 
763
        else:
 
764
            oldversioned = True
 
765
            if oldmode:
 
766
                oldexe = mode_is_executable(oldmode)
 
767
                oldkind = mode_kind(oldmode)
 
768
            else:
 
769
                oldexe = False
 
770
                oldkind = None
 
771
            if oldpath_decoded == u'':
 
772
                oldparent = None
 
773
                oldname = u''
 
774
            else:
 
775
                (oldparentpath, oldname) = osutils.split(oldpath_decoded)
 
776
                oldparent = old_mapping.generate_file_id(oldparentpath)
 
777
            fileid = old_mapping.generate_file_id(oldpath_decoded)
 
778
        if newpath_decoded is None:
 
779
            newexe = None
 
780
            newkind = None
 
781
            newname = None
 
782
            newparent = None
 
783
            newversioned = False
 
784
        else:
 
785
            newversioned = (newpath_decoded not in target_extras)
 
786
            if newmode:
 
787
                newexe = mode_is_executable(newmode)
 
788
                newkind = mode_kind(newmode)
 
789
            else:
 
790
                newexe = False
 
791
                newkind = None
 
792
            if newpath_decoded == u'':
 
793
                newparent = None
 
794
                newname = u''
 
795
            else:
 
796
                newparentpath, newname = osutils.split(newpath_decoded)
 
797
                newparent = new_mapping.generate_file_id(newparentpath)
 
798
        if old_mapping.is_special_file(oldpath):
80
799
            oldpath = None
81
 
        if mapping.is_control_file(newpath):
 
800
        if new_mapping.is_special_file(newpath):
82
801
            newpath = None
83
802
        if oldpath is None and newpath is None:
84
803
            continue
 
804
        change = _mod_tree.TreeChange(
 
805
            fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
 
806
            (oldversioned, newversioned),
 
807
            (oldparent, newparent), (oldname, newname),
 
808
            (oldkind, newkind), (oldexe, newexe))
85
809
        if oldpath is None:
86
 
            ret.added.append((newpath, new_fileid_map.lookup_file_id(newpath.encode("utf-8")), mode_kind(newmode)))
87
 
        elif newpath is None:
88
 
            ret.removed.append((oldpath, old_fileid_map.lookup_file_id(oldpath.encode("utf-8")), mode_kind(oldmode)))
 
810
            added.append((newpath, newkind))
 
811
        elif newpath is None or newmode == 0:
 
812
            ret.removed.append(change)
89
813
        elif oldpath != newpath:
90
 
            ret.renamed.append((oldpath, newpath, old_fileid_map.lookup_file_id(oldpath.encode("utf-8")), mode_kind(newmode), (oldsha != newsha), (oldmode != newmode)))
 
814
            ret.renamed.append(change)
91
815
        elif mode_kind(oldmode) != mode_kind(newmode):
92
 
            ret.kind_changed.append((newpath, new_fileid_map.lookup_file_id(newpath.encode("utf-8")), mode_kind(oldmode), mode_kind(newmode)))
 
816
            ret.kind_changed.append(change)
93
817
        elif oldsha != newsha or oldmode != newmode:
94
 
            ret.modified.append((newpath, new_fileid_map.lookup_file_id(newpath.encode("utf-8")), mode_kind(newmode), (oldsha != newsha), (oldmode != newmode)))
95
 
        else:
96
 
            ret.unchanged.append((newpath, new_fileid_map.lookup_file_id(newpath.encode("utf-8")), mode_kind(newmode)))
 
818
            if stat.S_ISDIR(oldmode) and stat.S_ISDIR(newmode):
 
819
                continue
 
820
            ret.modified.append(change)
 
821
        else:
 
822
            ret.unchanged.append(change)
 
823
 
 
824
    implicit_dirs = {b''}
 
825
    for path, kind in added:
 
826
        if kind == 'directory' or path in target_extras:
 
827
            continue
 
828
        implicit_dirs.update(osutils.parent_directories(path))
 
829
 
 
830
    for path, kind in added:
 
831
        if kind == 'directory' and path not in implicit_dirs:
 
832
            continue
 
833
        path_decoded = osutils.normalized_filename(path)[0]
 
834
        parent_path, basename = osutils.split(path_decoded)
 
835
        parent_id = new_mapping.generate_file_id(parent_path)
 
836
        if path in target_extras:
 
837
            ret.unversioned.append(_mod_tree.TreeChange(
 
838
                None, (None, path_decoded),
 
839
                True, (False, False), (None, parent_id),
 
840
                (None, basename), (None, kind), (None, False)))
 
841
        else:
 
842
            file_id = new_mapping.generate_file_id(path_decoded)
 
843
            ret.added.append(
 
844
                _mod_tree.TreeChange(
 
845
                    file_id, (None, path_decoded), True,
 
846
                    (False, True),
 
847
                    (None, parent_id),
 
848
                    (None, basename), (None, kind), (None, False)))
 
849
 
97
850
    return ret
98
851
 
99
852
 
100
 
def changes_from_git_changes(changes, mapping, specific_file=None,
101
 
                                require_versioned=False):
 
853
def changes_from_git_changes(changes, mapping, specific_files=None,
 
854
                             include_unchanged=False, target_extras=None):
102
855
    """Create a iter_changes-like generator from a git stream.
103
856
 
104
857
    source and target are iterators over tuples with:
105
858
        (filename, sha, mode)
106
859
    """
 
860
    if target_extras is None:
 
861
        target_extras = set()
107
862
    for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
108
 
        path = (oldpath, newpath)
109
 
        if oldpath is None:
110
 
            fileid = mapping.generate_file_id(newpath)
 
863
        if oldpath is not None:
 
864
            oldpath_decoded = oldpath.decode('utf-8')
 
865
        else:
 
866
            oldpath_decoded = None
 
867
        if newpath is not None:
 
868
            newpath_decoded = newpath.decode('utf-8')
 
869
        else:
 
870
            newpath_decoded = None
 
871
        if not (specific_files is None or
 
872
                (oldpath_decoded is not None and
 
873
                    osutils.is_inside_or_parent_of_any(
 
874
                        specific_files, oldpath_decoded)) or
 
875
                (newpath_decoded is not None and
 
876
                    osutils.is_inside_or_parent_of_any(
 
877
                        specific_files, newpath_decoded))):
 
878
            continue
 
879
        if oldpath is not None and mapping.is_special_file(oldpath):
 
880
            continue
 
881
        if newpath is not None and mapping.is_special_file(newpath):
 
882
            continue
 
883
        if oldpath_decoded is None:
 
884
            fileid = mapping.generate_file_id(newpath_decoded)
111
885
            oldexe = None
112
886
            oldkind = None
113
887
            oldname = None
114
888
            oldparent = None
 
889
            oldversioned = False
115
890
        else:
116
 
            oldexe = mode_is_executable(oldmode)
117
 
            oldkind = mode_kind(oldmode)
118
 
            try:
119
 
                (oldparentpath, oldname) = oldpath.rsplit("/", 1)
120
 
            except ValueError:
 
891
            oldversioned = True
 
892
            if oldmode:
 
893
                oldexe = mode_is_executable(oldmode)
 
894
                oldkind = mode_kind(oldmode)
 
895
            else:
 
896
                oldexe = False
 
897
                oldkind = None
 
898
            if oldpath_decoded == u'':
121
899
                oldparent = None
122
 
                oldname = oldpath
 
900
                oldname = u''
123
901
            else:
 
902
                (oldparentpath, oldname) = osutils.split(oldpath_decoded)
124
903
                oldparent = mapping.generate_file_id(oldparentpath)
125
 
            fileid = mapping.generate_file_id(oldpath)
126
 
        if newpath is None:
 
904
            fileid = mapping.generate_file_id(oldpath_decoded)
 
905
        if newpath_decoded is None:
127
906
            newexe = None
128
907
            newkind = None
129
908
            newname = None
130
909
            newparent = None
 
910
            newversioned = False
131
911
        else:
132
 
            newexe = mode_is_executable(newmode)
133
 
            newkind = mode_kind(newmode)
134
 
            try:
135
 
                newparentpath, newname = newpath.rsplit("/", 1)
136
 
            except ValueError:
 
912
            newversioned = (newpath_decoded not in target_extras)
 
913
            if newmode:
 
914
                newexe = mode_is_executable(newmode)
 
915
                newkind = mode_kind(newmode)
 
916
            else:
 
917
                newexe = False
 
918
                newkind = None
 
919
            if newpath_decoded == u'':
137
920
                newparent = None
138
 
                newname = newpath
 
921
                newname = u''
139
922
            else:
 
923
                newparentpath, newname = osutils.split(newpath_decoded)
140
924
                newparent = mapping.generate_file_id(newparentpath)
141
 
        yield (fileid, (oldpath, newpath), (oldsha != newsha),
142
 
             (oldpath is not None, newpath is not None),
143
 
             (oldparent, newparent), (oldname, newname),
144
 
             (oldkind, newkind), (oldexe, newexe))
145
 
 
146
 
 
147
 
class InterGitRevisionTrees(tree.InterTree):
148
 
    """InterTree that works between two git revision trees."""
 
925
        if (not include_unchanged and
 
926
            oldkind == 'directory' and newkind == 'directory' and
 
927
                oldpath_decoded == newpath_decoded):
 
928
            continue
 
929
        yield _mod_tree.TreeChange(
 
930
            fileid, (oldpath_decoded, newpath_decoded), (oldsha != newsha),
 
931
            (oldversioned, newversioned),
 
932
            (oldparent, newparent), (oldname, newname),
 
933
            (oldkind, newkind), (oldexe, newexe))
 
934
 
 
935
 
 
936
class InterGitTrees(_mod_tree.InterTree):
 
937
    """InterTree that works between two git trees."""
149
938
 
150
939
    _matching_from_tree_format = None
151
940
    _matching_to_tree_format = None
159
948
    def compare(self, want_unchanged=False, specific_files=None,
160
949
                extra_trees=None, require_versioned=False, include_root=False,
161
950
                want_unversioned=False):
162
 
        if self.source._repository._git.object_store != self.target._repository._git.object_store:
163
 
            raise AssertionError
164
 
        changes = self.source._repository._git.object_store.tree_changes(
165
 
            self.source.tree, self.target.tree, want_unchanged=want_unchanged)
166
 
        source_fileid_map = self.source.mapping.get_fileid_map(
167
 
            self.source._repository._git.object_store.__getitem__,
168
 
            self.source.tree)
169
 
        target_fileid_map = self.target.mapping.get_fileid_map(
170
 
            self.target._repository._git.object_store.__getitem__,
171
 
            self.target.tree)
172
 
        return tree_delta_from_git_changes(changes, self.target.mapping,
173
 
            (source_fileid_map, target_fileid_map),
174
 
            specific_file=specific_files)
 
951
        with self.lock_read():
 
952
            changes, target_extras = self._iter_git_changes(
 
953
                want_unchanged=want_unchanged,
 
954
                require_versioned=require_versioned,
 
955
                specific_files=specific_files,
 
956
                extra_trees=extra_trees,
 
957
                want_unversioned=want_unversioned)
 
958
            return tree_delta_from_git_changes(
 
959
                changes, (self.source.mapping, self.target.mapping),
 
960
                specific_files=specific_files,
 
961
                include_root=include_root, target_extras=target_extras)
175
962
 
176
963
    def iter_changes(self, include_unchanged=False, specific_files=None,
177
 
        pb=None, extra_trees=[], require_versioned=True,
178
 
        want_unversioned=False):
179
 
        if self.source._repository._git.object_store != self.target._repository._git.object_store:
180
 
            raise AssertionError
181
 
        changes = self.source._repository._git.object_store.tree_changes(
182
 
            self.source.tree, self.target.tree,
183
 
            want_unchanged=include_unchanged)
184
 
        return changes_from_git_changes(changes, self.target.mapping,
185
 
            specific_file=specific_files)
186
 
 
187
 
 
188
 
tree.InterTree.register_optimiser(InterGitRevisionTrees)
 
964
                     pb=None, extra_trees=[], require_versioned=True,
 
965
                     want_unversioned=False):
 
966
        with self.lock_read():
 
967
            changes, target_extras = self._iter_git_changes(
 
968
                want_unchanged=include_unchanged,
 
969
                require_versioned=require_versioned,
 
970
                specific_files=specific_files,
 
971
                extra_trees=extra_trees,
 
972
                want_unversioned=want_unversioned)
 
973
            return changes_from_git_changes(
 
974
                changes, self.target.mapping,
 
975
                specific_files=specific_files,
 
976
                include_unchanged=include_unchanged,
 
977
                target_extras=target_extras)
 
978
 
 
979
    def _iter_git_changes(self, want_unchanged=False, specific_files=None,
 
980
                          require_versioned=False, extra_trees=None,
 
981
                          want_unversioned=False):
 
982
        raise NotImplementedError(self._iter_git_changes)
 
983
 
 
984
 
 
985
class InterGitRevisionTrees(InterGitTrees):
 
986
    """InterTree that works between two git revision trees."""
 
987
 
 
988
    _matching_from_tree_format = None
 
989
    _matching_to_tree_format = None
 
990
    _test_mutable_trees_to_test_trees = None
 
991
 
 
992
    @classmethod
 
993
    def is_compatible(cls, source, target):
 
994
        return (isinstance(source, GitRevisionTree) and
 
995
                isinstance(target, GitRevisionTree))
 
996
 
 
997
    def _iter_git_changes(self, want_unchanged=False, specific_files=None,
 
998
                          require_versioned=True, extra_trees=None,
 
999
                          want_unversioned=False):
 
1000
        trees = [self.source]
 
1001
        if extra_trees is not None:
 
1002
            trees.extend(extra_trees)
 
1003
        if specific_files is not None:
 
1004
            specific_files = self.target.find_related_paths_across_trees(
 
1005
                specific_files, trees,
 
1006
                require_versioned=require_versioned)
 
1007
 
 
1008
        if (self.source._repository._git.object_store !=
 
1009
                self.target._repository._git.object_store):
 
1010
            store = OverlayObjectStore(
 
1011
                [self.source._repository._git.object_store,
 
1012
                    self.target._repository._git.object_store])
 
1013
        else:
 
1014
            store = self.source._repository._git.object_store
 
1015
        return store.tree_changes(
 
1016
            self.source.tree, self.target.tree, want_unchanged=want_unchanged,
 
1017
            include_trees=True, change_type_same=True), set()
 
1018
 
 
1019
 
 
1020
_mod_tree.InterTree.register_optimiser(InterGitRevisionTrees)
 
1021
 
 
1022
 
 
1023
class MutableGitIndexTree(mutabletree.MutableTree):
 
1024
 
 
1025
    def __init__(self):
 
1026
        self._lock_mode = None
 
1027
        self._lock_count = 0
 
1028
        self._versioned_dirs = None
 
1029
        self._index_dirty = False
 
1030
        self._submodules = None
 
1031
 
 
1032
    def is_versioned(self, path):
 
1033
        with self.lock_read():
 
1034
            path = path.rstrip('/').encode('utf-8')
 
1035
            (index, subpath) = self._lookup_index(path)
 
1036
            return (subpath in index or self._has_dir(path))
 
1037
 
 
1038
    def _has_dir(self, path):
 
1039
        if not isinstance(path, bytes):
 
1040
            raise TypeError(path)
 
1041
        if path == b"":
 
1042
            return True
 
1043
        if self._versioned_dirs is None:
 
1044
            self._load_dirs()
 
1045
        return path in self._versioned_dirs
 
1046
 
 
1047
    def _load_dirs(self):
 
1048
        if self._lock_mode is None:
 
1049
            raise errors.ObjectNotLocked(self)
 
1050
        self._versioned_dirs = set()
 
1051
        for p, i in self._recurse_index_entries():
 
1052
            self._ensure_versioned_dir(posixpath.dirname(p))
 
1053
 
 
1054
    def _ensure_versioned_dir(self, dirname):
 
1055
        if not isinstance(dirname, bytes):
 
1056
            raise TypeError(dirname)
 
1057
        if dirname in self._versioned_dirs:
 
1058
            return
 
1059
        if dirname != b"":
 
1060
            self._ensure_versioned_dir(posixpath.dirname(dirname))
 
1061
        self._versioned_dirs.add(dirname)
 
1062
 
 
1063
    def path2id(self, path):
 
1064
        with self.lock_read():
 
1065
            path = path.rstrip('/')
 
1066
            if self.is_versioned(path.rstrip('/')):
 
1067
                return self.mapping.generate_file_id(
 
1068
                    osutils.safe_unicode(path))
 
1069
            return None
 
1070
 
 
1071
    def id2path(self, file_id, recurse='down'):
 
1072
        if file_id is None:
 
1073
            return ''
 
1074
        if type(file_id) is not bytes:
 
1075
            raise TypeError(file_id)
 
1076
        with self.lock_read():
 
1077
            try:
 
1078
                path = self.mapping.parse_file_id(file_id)
 
1079
            except ValueError:
 
1080
                raise errors.NoSuchId(self, file_id)
 
1081
            if self.is_versioned(path):
 
1082
                return path
 
1083
            raise errors.NoSuchId(self, file_id)
 
1084
 
 
1085
    def _set_root_id(self, file_id):
 
1086
        raise errors.UnsupportedOperation(self._set_root_id, self)
 
1087
 
 
1088
    def _add(self, files, ids, kinds):
 
1089
        for (path, file_id, kind) in zip(files, ids, kinds):
 
1090
            if file_id is not None:
 
1091
                raise workingtree.SettingFileIdUnsupported()
 
1092
            path, can_access = osutils.normalized_filename(path)
 
1093
            if not can_access:
 
1094
                raise errors.InvalidNormalization(path)
 
1095
            self._index_add_entry(path, kind)
 
1096
 
 
1097
    def _read_submodule_head(self, path):
 
1098
        raise NotImplementedError(self._read_submodule_head)
 
1099
 
 
1100
    def _submodule_info(self):
 
1101
        if self._submodules is None:
 
1102
            try:
 
1103
                with self.get_file('.gitmodules') as f:
 
1104
                    config = GitConfigFile.from_file(f)
 
1105
                    self._submodules = {
 
1106
                        path: (url, section)
 
1107
                        for path, url, section in parse_submodules(config)}
 
1108
            except errors.NoSuchFile:
 
1109
                self._submodules = {}
 
1110
        return self._submodules
 
1111
 
 
1112
    def _lookup_index(self, encoded_path):
 
1113
        if not isinstance(encoded_path, bytes):
 
1114
            raise TypeError(encoded_path)
 
1115
        # Common case:
 
1116
        if encoded_path in self.index:
 
1117
            return self.index, encoded_path
 
1118
        # TODO(jelmer): Perhaps have a cache with paths under which some
 
1119
        # submodules exist?
 
1120
        index = self.index
 
1121
        remaining_path = encoded_path
 
1122
        while True:
 
1123
            parts = remaining_path.split(b'/')
 
1124
            for i in range(1, len(parts)):
 
1125
                basepath = b'/'.join(parts[:i])
 
1126
                try:
 
1127
                    (ctime, mtime, dev, ino, mode, uid, gid, size, sha,
 
1128
                     flags) = index[basepath]
 
1129
                except KeyError:
 
1130
                    continue
 
1131
                else:
 
1132
                    if S_ISGITLINK(mode):
 
1133
                        index = self._get_submodule_index(basepath)
 
1134
                        remaining_path = b'/'.join(parts[i:])
 
1135
                        break
 
1136
                    else:
 
1137
                        return index, remaining_path
 
1138
            else:
 
1139
                return index, remaining_path
 
1140
        return index, remaining_path
 
1141
 
 
1142
    def _index_del_entry(self, index, path):
 
1143
        del index[path]
 
1144
        # TODO(jelmer): Keep track of dirty per index
 
1145
        self._index_dirty = True
 
1146
 
 
1147
    def _index_add_entry(self, path, kind, flags=0, reference_revision=None):
 
1148
        if kind == "directory":
 
1149
            # Git indexes don't contain directories
 
1150
            return
 
1151
        if kind == "file":
 
1152
            blob = Blob()
 
1153
            try:
 
1154
                file, stat_val = self.get_file_with_stat(path)
 
1155
            except (errors.NoSuchFile, IOError):
 
1156
                # TODO: Rather than come up with something here, use the old
 
1157
                # index
 
1158
                file = BytesIO()
 
1159
                stat_val = os.stat_result(
 
1160
                    (stat.S_IFREG | 0o644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
 
1161
            with file:
 
1162
                blob.set_raw_string(file.read())
 
1163
            # Add object to the repository if it didn't exist yet
 
1164
            if blob.id not in self.store:
 
1165
                self.store.add_object(blob)
 
1166
            hexsha = blob.id
 
1167
        elif kind == "symlink":
 
1168
            blob = Blob()
 
1169
            try:
 
1170
                stat_val = self._lstat(path)
 
1171
            except EnvironmentError:
 
1172
                # TODO: Rather than come up with something here, use the
 
1173
                # old index
 
1174
                stat_val = os.stat_result(
 
1175
                    (stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
 
1176
            blob.set_raw_string(
 
1177
                self.get_symlink_target(path).encode("utf-8"))
 
1178
            # Add object to the repository if it didn't exist yet
 
1179
            if blob.id not in self.store:
 
1180
                self.store.add_object(blob)
 
1181
            hexsha = blob.id
 
1182
        elif kind == "tree-reference":
 
1183
            if reference_revision is not None:
 
1184
                hexsha = self.branch.lookup_bzr_revision_id(
 
1185
                    reference_revision)[0]
 
1186
            else:
 
1187
                hexsha = self._read_submodule_head(path)
 
1188
                if hexsha is None:
 
1189
                    raise errors.NoCommits(path)
 
1190
            try:
 
1191
                stat_val = self._lstat(path)
 
1192
            except EnvironmentError:
 
1193
                stat_val = os.stat_result(
 
1194
                    (S_IFGITLINK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
 
1195
            stat_val = os.stat_result((S_IFGITLINK, ) + stat_val[1:])
 
1196
        else:
 
1197
            raise AssertionError("unknown kind '%s'" % kind)
 
1198
        # Add an entry to the index or update the existing entry
 
1199
        ensure_normalized_path(path)
 
1200
        encoded_path = path.encode("utf-8")
 
1201
        if b'\r' in encoded_path or b'\n' in encoded_path:
 
1202
            # TODO(jelmer): Why do we need to do this?
 
1203
            trace.mutter('ignoring path with invalid newline in it: %r', path)
 
1204
            return
 
1205
        (index, index_path) = self._lookup_index(encoded_path)
 
1206
        index[index_path] = index_entry_from_stat(stat_val, hexsha, flags)
 
1207
        self._index_dirty = True
 
1208
        if self._versioned_dirs is not None:
 
1209
            self._ensure_versioned_dir(index_path)
 
1210
 
 
1211
    def _recurse_index_entries(self, index=None, basepath=b"",
 
1212
                               recurse_nested=False):
 
1213
        # Iterate over all index entries
 
1214
        with self.lock_read():
 
1215
            if index is None:
 
1216
                index = self.index
 
1217
            for path, value in index.items():
 
1218
                (ctime, mtime, dev, ino, mode, uid, gid, size, sha,
 
1219
                 flags) = value
 
1220
                if S_ISGITLINK(mode) and recurse_nested:
 
1221
                    subindex = self._get_submodule_index(path)
 
1222
                    for entry in self._recurse_index_entries(
 
1223
                            index=subindex, basepath=path,
 
1224
                            recurse_nested=recurse_nested):
 
1225
                        yield entry
 
1226
                else:
 
1227
                    yield (posixpath.join(basepath, path), value)
 
1228
 
 
1229
    def iter_entries_by_dir(self, specific_files=None,
 
1230
                            recurse_nested=False):
 
1231
        with self.lock_read():
 
1232
            if specific_files is not None:
 
1233
                specific_files = set(specific_files)
 
1234
            else:
 
1235
                specific_files = None
 
1236
            root_ie = self._get_dir_ie(u"", None)
 
1237
            ret = {}
 
1238
            if specific_files is None or u"" in specific_files:
 
1239
                ret[(u"", u"")] = root_ie
 
1240
            dir_ids = {u"": root_ie.file_id}
 
1241
            for path, value in self._recurse_index_entries(
 
1242
                    recurse_nested=recurse_nested):
 
1243
                if self.mapping.is_special_file(path):
 
1244
                    continue
 
1245
                path = path.decode("utf-8")
 
1246
                if specific_files is not None and path not in specific_files:
 
1247
                    continue
 
1248
                (parent, name) = posixpath.split(path)
 
1249
                try:
 
1250
                    file_ie = self._get_file_ie(name, path, value, None)
 
1251
                except errors.NoSuchFile:
 
1252
                    continue
 
1253
                if specific_files is None:
 
1254
                    for (dir_path, dir_ie) in self._add_missing_parent_ids(
 
1255
                            parent, dir_ids):
 
1256
                        ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
 
1257
                file_ie.parent_id = self.path2id(parent)
 
1258
                ret[(posixpath.dirname(path), path)] = file_ie
 
1259
            # Special casing for directories
 
1260
            if specific_files:
 
1261
                for path in specific_files:
 
1262
                    key = (posixpath.dirname(path), path)
 
1263
                    if key not in ret and self.is_versioned(path):
 
1264
                        ret[key] = self._get_dir_ie(path, self.path2id(key[0]))
 
1265
            return ((path, ie) for ((_, path), ie) in sorted(ret.items()))
 
1266
 
 
1267
    def iter_references(self):
 
1268
        if self.supports_tree_reference():
 
1269
            # TODO(jelmer): Implement a more efficient version of this
 
1270
            for path, entry in self.iter_entries_by_dir():
 
1271
                if entry.kind == 'tree-reference':
 
1272
                    yield path
 
1273
 
 
1274
    def _get_dir_ie(self, path, parent_id):
 
1275
        file_id = self.path2id(path)
 
1276
        return GitTreeDirectory(file_id,
 
1277
                                posixpath.basename(path).strip("/"), parent_id)
 
1278
 
 
1279
    def _get_file_ie(self, name, path, value, parent_id):
 
1280
        if not isinstance(name, str):
 
1281
            raise TypeError(name)
 
1282
        if not isinstance(path, str):
 
1283
            raise TypeError(path)
 
1284
        if not isinstance(value, tuple) or len(value) != 10:
 
1285
            raise TypeError(value)
 
1286
        (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
 
1287
        file_id = self.path2id(path)
 
1288
        if not isinstance(file_id, bytes):
 
1289
            raise TypeError(file_id)
 
1290
        kind = mode_kind(mode)
 
1291
        ie = entry_factory[kind](file_id, name, parent_id)
 
1292
        if kind == 'symlink':
 
1293
            ie.symlink_target = self.get_symlink_target(path)
 
1294
        elif kind == 'tree-reference':
 
1295
            ie.reference_revision = self.get_reference_revision(path)
 
1296
        else:
 
1297
            try:
 
1298
                data = self.get_file_text(path)
 
1299
            except errors.NoSuchFile:
 
1300
                data = None
 
1301
            except IOError as e:
 
1302
                if e.errno != errno.ENOENT:
 
1303
                    raise
 
1304
                data = None
 
1305
            if data is None:
 
1306
                data = self.branch.repository._git.object_store[sha].data
 
1307
            ie.text_sha1 = osutils.sha_string(data)
 
1308
            ie.text_size = len(data)
 
1309
            ie.executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
1310
        return ie
 
1311
 
 
1312
    def _add_missing_parent_ids(self, path, dir_ids):
 
1313
        if path in dir_ids:
 
1314
            return []
 
1315
        parent = posixpath.dirname(path).strip("/")
 
1316
        ret = self._add_missing_parent_ids(parent, dir_ids)
 
1317
        parent_id = dir_ids[parent]
 
1318
        ie = self._get_dir_ie(path, parent_id)
 
1319
        dir_ids[path] = ie.file_id
 
1320
        ret.append((path, ie))
 
1321
        return ret
 
1322
 
 
1323
    def _comparison_data(self, entry, path):
 
1324
        if entry is None:
 
1325
            return None, False, None
 
1326
        return entry.kind, entry.executable, None
 
1327
 
 
1328
    def _unversion_path(self, path):
 
1329
        if self._lock_mode is None:
 
1330
            raise errors.ObjectNotLocked(self)
 
1331
        encoded_path = path.encode("utf-8")
 
1332
        count = 0
 
1333
        (index, subpath) = self._lookup_index(encoded_path)
 
1334
        try:
 
1335
            self._index_del_entry(index, encoded_path)
 
1336
        except KeyError:
 
1337
            # A directory, perhaps?
 
1338
            # TODO(jelmer): Deletes that involve submodules?
 
1339
            for p in list(index):
 
1340
                if p.startswith(subpath + b"/"):
 
1341
                    count += 1
 
1342
                    self._index_del_entry(index, p)
 
1343
        else:
 
1344
            count = 1
 
1345
        self._versioned_dirs = None
 
1346
        return count
 
1347
 
 
1348
    def unversion(self, paths):
 
1349
        with self.lock_tree_write():
 
1350
            for path in paths:
 
1351
                if self._unversion_path(path) == 0:
 
1352
                    raise errors.NoSuchFile(path)
 
1353
            self._versioned_dirs = None
 
1354
            self.flush()
 
1355
 
 
1356
    def flush(self):
 
1357
        pass
 
1358
 
 
1359
    def update_basis_by_delta(self, revid, delta):
 
1360
        # TODO(jelmer): This shouldn't be called, it's inventory specific.
 
1361
        for (old_path, new_path, file_id, ie) in delta:
 
1362
            if old_path is not None:
 
1363
                (index, old_subpath) = self._lookup_index(
 
1364
                    old_path.encode('utf-8'))
 
1365
                if old_subpath in index:
 
1366
                    self._index_del_entry(index, old_subpath)
 
1367
                    self._versioned_dirs = None
 
1368
            if new_path is not None and ie.kind != 'directory':
 
1369
                self._index_add_entry(new_path, ie.kind)
 
1370
        self.flush()
 
1371
        self._set_merges_from_parent_ids([])
 
1372
 
 
1373
    def move(self, from_paths, to_dir=None, after=None):
 
1374
        rename_tuples = []
 
1375
        with self.lock_tree_write():
 
1376
            to_abs = self.abspath(to_dir)
 
1377
            if not os.path.isdir(to_abs):
 
1378
                raise errors.BzrMoveFailedError('', to_dir,
 
1379
                                                errors.NotADirectory(to_abs))
 
1380
 
 
1381
            for from_rel in from_paths:
 
1382
                from_tail = os.path.split(from_rel)[-1]
 
1383
                to_rel = os.path.join(to_dir, from_tail)
 
1384
                self.rename_one(from_rel, to_rel, after=after)
 
1385
                rename_tuples.append((from_rel, to_rel))
 
1386
            self.flush()
 
1387
            return rename_tuples
 
1388
 
 
1389
    def rename_one(self, from_rel, to_rel, after=None):
 
1390
        from_path = from_rel.encode("utf-8")
 
1391
        to_rel, can_access = osutils.normalized_filename(to_rel)
 
1392
        if not can_access:
 
1393
            raise errors.InvalidNormalization(to_rel)
 
1394
        to_path = to_rel.encode("utf-8")
 
1395
        with self.lock_tree_write():
 
1396
            if not after:
 
1397
                # Perhaps it's already moved?
 
1398
                after = (
 
1399
                    not self.has_filename(from_rel) and
 
1400
                    self.has_filename(to_rel) and
 
1401
                    not self.is_versioned(to_rel))
 
1402
            if after:
 
1403
                if not self.has_filename(to_rel):
 
1404
                    raise errors.BzrMoveFailedError(
 
1405
                        from_rel, to_rel, errors.NoSuchFile(to_rel))
 
1406
                if self.basis_tree().is_versioned(to_rel):
 
1407
                    raise errors.BzrMoveFailedError(
 
1408
                        from_rel, to_rel, errors.AlreadyVersionedError(to_rel))
 
1409
 
 
1410
                kind = self.kind(to_rel)
 
1411
            else:
 
1412
                try:
 
1413
                    to_kind = self.kind(to_rel)
 
1414
                except errors.NoSuchFile:
 
1415
                    exc_type = errors.BzrRenameFailedError
 
1416
                    to_kind = None
 
1417
                else:
 
1418
                    exc_type = errors.BzrMoveFailedError
 
1419
                if self.is_versioned(to_rel):
 
1420
                    raise exc_type(from_rel, to_rel,
 
1421
                                   errors.AlreadyVersionedError(to_rel))
 
1422
                if not self.has_filename(from_rel):
 
1423
                    raise errors.BzrMoveFailedError(
 
1424
                        from_rel, to_rel, errors.NoSuchFile(from_rel))
 
1425
                kind = self.kind(from_rel)
 
1426
                if not self.is_versioned(from_rel) and kind != 'directory':
 
1427
                    raise exc_type(from_rel, to_rel,
 
1428
                                   errors.NotVersionedError(from_rel))
 
1429
                if self.has_filename(to_rel):
 
1430
                    raise errors.RenameFailedFilesExist(
 
1431
                        from_rel, to_rel, errors.FileExists(to_rel))
 
1432
 
 
1433
                kind = self.kind(from_rel)
 
1434
 
 
1435
            if not after and kind != 'directory':
 
1436
                (index, from_subpath) = self._lookup_index(from_path)
 
1437
                if from_subpath not in index:
 
1438
                    # It's not a file
 
1439
                    raise errors.BzrMoveFailedError(
 
1440
                        from_rel, to_rel,
 
1441
                        errors.NotVersionedError(path=from_rel))
 
1442
 
 
1443
            if not after:
 
1444
                try:
 
1445
                    self._rename_one(from_rel, to_rel)
 
1446
                except OSError as e:
 
1447
                    if e.errno == errno.ENOENT:
 
1448
                        raise errors.BzrMoveFailedError(
 
1449
                            from_rel, to_rel, errors.NoSuchFile(to_rel))
 
1450
                    raise
 
1451
            if kind != 'directory':
 
1452
                (index, from_index_path) = self._lookup_index(from_path)
 
1453
                try:
 
1454
                    self._index_del_entry(index, from_path)
 
1455
                except KeyError:
 
1456
                    pass
 
1457
                self._index_add_entry(to_rel, kind)
 
1458
            else:
 
1459
                todo = [(p, i) for (p, i) in self._recurse_index_entries()
 
1460
                        if p.startswith(from_path + b'/')]
 
1461
                for child_path, child_value in todo:
 
1462
                    (child_to_index, child_to_index_path) = self._lookup_index(
 
1463
                        posixpath.join(to_path, posixpath.relpath(child_path, from_path)))
 
1464
                    child_to_index[child_to_index_path] = child_value
 
1465
                    # TODO(jelmer): Mark individual index as dirty
 
1466
                    self._index_dirty = True
 
1467
                    (child_from_index, child_from_index_path) = self._lookup_index(
 
1468
                        child_path)
 
1469
                    self._index_del_entry(
 
1470
                        child_from_index, child_from_index_path)
 
1471
 
 
1472
            self._versioned_dirs = None
 
1473
            self.flush()
 
1474
 
 
1475
    def find_related_paths_across_trees(self, paths, trees=[],
 
1476
                                        require_versioned=True):
 
1477
        if paths is None:
 
1478
            return None
 
1479
 
 
1480
        if require_versioned:
 
1481
            trees = [self] + (trees if trees is not None else [])
 
1482
            unversioned = set()
 
1483
            for p in paths:
 
1484
                for t in trees:
 
1485
                    if t.is_versioned(p):
 
1486
                        break
 
1487
                else:
 
1488
                    unversioned.add(p)
 
1489
            if unversioned:
 
1490
                raise errors.PathsNotVersionedError(unversioned)
 
1491
 
 
1492
        return filter(self.is_versioned, paths)
 
1493
 
 
1494
    def path_content_summary(self, path):
 
1495
        """See Tree.path_content_summary."""
 
1496
        try:
 
1497
            stat_result = self._lstat(path)
 
1498
        except OSError as e:
 
1499
            if getattr(e, 'errno', None) == errno.ENOENT:
 
1500
                # no file.
 
1501
                return ('missing', None, None, None)
 
1502
            # propagate other errors
 
1503
            raise
 
1504
        kind = mode_kind(stat_result.st_mode)
 
1505
        if kind == 'file':
 
1506
            return self._file_content_summary(path, stat_result)
 
1507
        elif kind == 'directory':
 
1508
            # perhaps it looks like a plain directory, but it's really a
 
1509
            # reference.
 
1510
            if self._directory_is_tree_reference(path):
 
1511
                kind = 'tree-reference'
 
1512
            return kind, None, None, None
 
1513
        elif kind == 'symlink':
 
1514
            target = osutils.readlink(self.abspath(path))
 
1515
            return ('symlink', None, None, target)
 
1516
        else:
 
1517
            return (kind, None, None, None)
 
1518
 
 
1519
    def stored_kind(self, relpath):
 
1520
        (index, index_path) = self._lookup_index(relpath.encode('utf-8'))
 
1521
        if index is None:
 
1522
            return kind
 
1523
        try:
 
1524
            mode = index[index_path].mode
 
1525
        except KeyError:
 
1526
            return kind
 
1527
        else:
 
1528
            if S_ISGITLINK(mode):
 
1529
                return 'tree-reference'
 
1530
            return 'directory'
 
1531
 
 
1532
    def kind(self, relpath):
 
1533
        kind = osutils.file_kind(self.abspath(relpath))
 
1534
        if kind == 'directory':
 
1535
            if self._directory_is_tree_reference(relpath):
 
1536
                return 'tree-reference'
 
1537
            return 'directory'
 
1538
        else:
 
1539
            return kind
 
1540
 
 
1541
    def _live_entry(self, relpath):
 
1542
        raise NotImplementedError(self._live_entry)
 
1543
 
 
1544
    def get_transform(self, pb=None):
 
1545
        from ..transform import TreeTransform
 
1546
        return TreeTransform(self, pb=pb)
 
1547
 
 
1548
 
 
1549
 
 
1550
class InterIndexGitTree(InterGitTrees):
 
1551
    """InterTree that works between a Git revision tree and an index."""
 
1552
 
 
1553
    def __init__(self, source, target):
 
1554
        super(InterIndexGitTree, self).__init__(source, target)
 
1555
        self._index = target.index
 
1556
 
 
1557
    @classmethod
 
1558
    def is_compatible(cls, source, target):
 
1559
        return (isinstance(source, GitRevisionTree) and
 
1560
                isinstance(target, MutableGitIndexTree))
 
1561
 
 
1562
    def _iter_git_changes(self, want_unchanged=False, specific_files=None,
 
1563
                          require_versioned=False, extra_trees=None,
 
1564
                          want_unversioned=False):
 
1565
        trees = [self.source]
 
1566
        if extra_trees is not None:
 
1567
            trees.extend(extra_trees)
 
1568
        if specific_files is not None:
 
1569
            specific_files = self.target.find_related_paths_across_trees(
 
1570
                specific_files, trees,
 
1571
                require_versioned=require_versioned)
 
1572
        # TODO(jelmer): Restrict to specific_files, for performance reasons.
 
1573
        with self.lock_read():
 
1574
            return changes_between_git_tree_and_working_copy(
 
1575
                self.source.store, self.source.tree,
 
1576
                self.target, want_unchanged=want_unchanged,
 
1577
                want_unversioned=want_unversioned)
 
1578
 
 
1579
 
 
1580
_mod_tree.InterTree.register_optimiser(InterIndexGitTree)
 
1581
 
 
1582
 
 
1583
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
 
1584
                                              want_unchanged=False,
 
1585
                                              want_unversioned=False):
 
1586
    """Determine the changes between a git tree and a working tree with index.
 
1587
 
 
1588
    """
 
1589
    extras = set()
 
1590
    blobs = {}
 
1591
    # Report dirified directories to commit_tree first, so that they can be
 
1592
    # replaced with non-empty directories if they have contents.
 
1593
    dirified = []
 
1594
    trust_executable = target._supports_executable()
 
1595
    for path, index_entry in target._recurse_index_entries():
 
1596
        try:
 
1597
            live_entry = target._live_entry(path)
 
1598
        except EnvironmentError as e:
 
1599
            if e.errno == errno.ENOENT:
 
1600
                # Entry was removed; keep it listed, but mark it as gone.
 
1601
                blobs[path] = (ZERO_SHA, 0)
 
1602
            else:
 
1603
                raise
 
1604
        else:
 
1605
            if live_entry is None:
 
1606
                # Entry was turned into a directory.
 
1607
                # Maybe it's just a submodule that's not checked out?
 
1608
                if S_ISGITLINK(index_entry.mode):
 
1609
                    blobs[path] = (index_entry.sha, index_entry.mode)
 
1610
                else:
 
1611
                    dirified.append((path, Tree().id, stat.S_IFDIR))
 
1612
                    store.add_object(Tree())
 
1613
            else:
 
1614
                mode = live_entry.mode
 
1615
                if not trust_executable:
 
1616
                    if mode_is_executable(index_entry.mode):
 
1617
                        mode |= 0o111
 
1618
                    else:
 
1619
                        mode &= ~0o111
 
1620
                blobs[path] = (live_entry.sha, cleanup_mode(live_entry.mode))
 
1621
    if want_unversioned:
 
1622
        for e in target.extras():
 
1623
            st = target._lstat(e)
 
1624
            try:
 
1625
                np, accessible = osutils.normalized_filename(e)
 
1626
            except UnicodeDecodeError:
 
1627
                raise errors.BadFilenameEncoding(
 
1628
                    e, osutils._fs_enc)
 
1629
            if stat.S_ISDIR(st.st_mode):
 
1630
                blob = Tree()
 
1631
            else:
 
1632
                blob = blob_from_path_and_stat(
 
1633
                    target.abspath(e).encode(osutils._fs_enc), st)
 
1634
            store.add_object(blob)
 
1635
            np = np.encode('utf-8')
 
1636
            blobs[np] = (blob.id, cleanup_mode(st.st_mode))
 
1637
            extras.add(np)
 
1638
    to_tree_sha = commit_tree(
 
1639
        store, dirified + [(p, s, m) for (p, (s, m)) in blobs.items()])
 
1640
    return store.tree_changes(
 
1641
        from_tree_sha, to_tree_sha, include_trees=True,
 
1642
        want_unchanged=want_unchanged, change_type_same=True), extras