/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-06-29 15:50:22 UTC
  • mto: This revision was merged to the branch mainline in revision 7374.
  • Revision ID: jelmer@jelmer.uk-20190629155022-jagfuax2bl39bjin
Drop file id roundtripping support in Git.

Stashing bzr-specific metadata in Git is fraught with problems. Instead, we'll
be opportunistic when trying to match files from bzr and git.

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