/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-11-02 23:19:18 UTC
  • mto: This revision was merged to the branch mainline in revision 7413.
  • Revision ID: jelmer@jelmer.uk-20191102231918-8umqkgb2j0lc262j
Fix support for reading from a dumb git server.

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