/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: Robert Collins
  • Date: 2010-05-11 08:36:16 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100511083616-b8fjb19zomwupid0
Make all lock methods return Result objects, rather than lock_read returning self, as per John's review.

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