/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

s/follow_tree_references/recurse_nested/g

Show diffs side-by-side

added added

removed removed

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