/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: 2018-11-11 04:08:32 UTC
  • mto: (7143.16.20 even-more-cleanups)
  • mto: This revision was merged to the branch mainline in revision 7175.
  • Revision ID: jelmer@jelmer.uk-20181111040832-nsljjynzzwmznf3h
Run autopep8.

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