/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: 2019-09-29 12:45:26 UTC
  • mto: This revision was merged to the branch mainline in revision 7402.
  • Revision ID: jelmer@jelmer.uk-20190929124526-f2o8u8rk883l2g8o
Remove unused _iter_children function.

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