/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.264.10 by Jelmer Vernooij
Yield inventory entries.
1
# Copyright (C) 2008-2011 Jelmer Vernooij <jelmer@samba.org>
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
0.200.381 by Jelmer Vernooij
Support working trees properly, status and ls.
17
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
18
"""An adapter between a Git index and a Bazaar Working Tree"""
19
0.200.1594 by Jelmer Vernooij
Use absolute_import everywhere.
20
from __future__ import absolute_import
0.200.381 by Jelmer Vernooij
Support working trees properly, status and ls.
21
0.200.1731 by Jelmer Vernooij
Add support for checking untracked changes.
22
import itertools
0.200.385 by Jelmer Vernooij
Cope with removed files.
23
from cStringIO import (
24
    StringIO,
25
    )
0.200.1210 by Jelmer Vernooij
Implement GitWorkingTree._walkdirs.
26
from collections import defaultdict
0.239.4 by Jelmer Vernooij
Cope with nonexistent files and directories in get_file_sha1.
27
import errno
0.200.1538 by Jelmer Vernooij
More work on tree-reference support.
28
from dulwich.errors import NotGitRepository
0.200.1655 by Jelmer Vernooij
Basic support for git ignores.
29
from dulwich.ignore import (
0.200.1658 by Jelmer Vernooij
Fix handling of ignores - return patterns that matched.
30
    IgnoreFilterManager,
0.200.1655 by Jelmer Vernooij
Basic support for git ignores.
31
    )
0.200.1096 by Jelmer Vernooij
Implement GitWorkingTreeFormat.initialize.
32
from dulwich.index import (
33
    Index,
0.200.1531 by Jelmer Vernooij
Don't trust index contents - verify against file timestamps.
34
    changes_from_tree,
35
    cleanup_mode,
0.200.1754 by Jelmer Vernooij
Avoid updating index when just comparing trees.
36
    commit_tree,
0.200.1531 by Jelmer Vernooij
Don't trust index contents - verify against file timestamps.
37
    index_entry_from_stat,
0.200.1754 by Jelmer Vernooij
Avoid updating index when just comparing trees.
38
    iter_fresh_blobs,
0.200.1096 by Jelmer Vernooij
Implement GitWorkingTreeFormat.initialize.
39
    )
0.200.1202 by Jelmer Vernooij
Implement has_or_had_id.
40
from dulwich.object_store import (
41
    tree_lookup_path,
42
    )
0.200.383 by Jelmer Vernooij
Simplify, support rewriting index based on inventory.
43
from dulwich.objects import (
44
    Blob,
0.200.1538 by Jelmer Vernooij
More work on tree-reference support.
45
    S_IFGITLINK,
0.200.948 by Jelmer Vernooij
Cope with empty inventories.
46
    ZERO_SHA,
47
    )
0.200.1538 by Jelmer Vernooij
More work on tree-reference support.
48
from dulwich.repo import Repo
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
49
import os
0.264.10 by Jelmer Vernooij
Yield inventory entries.
50
import posixpath
0.200.1655 by Jelmer Vernooij
Basic support for git ignores.
51
import re
0.200.384 by Jelmer Vernooij
Fix reading of inventory from index.
52
import stat
0.200.1215 by Jelmer Vernooij
Implement GitWorkingTree.remove.
53
import sys
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
54
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
55
from ... import (
0.200.382 by Jelmer Vernooij
Support flushing index.
56
    errors,
0.262.1 by Jelmer Vernooij
Fix WorkingTree.conflicts().
57
    conflicts as _mod_conflicts,
0.200.1752 by Jelmer Vernooij
Don't traverse nested trees in WorkingTree.smart_add.
58
    controldir as _mod_controldir,
0.200.1655 by Jelmer Vernooij
Basic support for git ignores.
59
    globbing,
0.200.409 by Jelmer Vernooij
Support parsing .gitignore.
60
    ignores,
0.200.1476 by Jelmer Vernooij
Cope with working tree refactoring.
61
    lock,
0.200.381 by Jelmer Vernooij
Support working trees properly, status and ls.
62
    osutils,
0.200.1720 by Jelmer Vernooij
Fix handling of pending merges.
63
    revision as _mod_revision,
0.200.1215 by Jelmer Vernooij
Implement GitWorkingTree.remove.
64
    trace,
0.200.1752 by Jelmer Vernooij
Don't traverse nested trees in WorkingTree.smart_add.
65
    transport as _mod_transport,
0.200.519 by Jelmer Vernooij
Move imports down, might not be available in older bzr-git versions.
66
    tree,
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
67
    workingtree,
68
    )
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
69
from ...bzr import (
70
    inventory,
71
    )
0.200.1680 by Jelmer Vernooij
Fix repo locks.
72
from ...mutabletree import (
73
    MutableTree,
74
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
75
76
77
from .dir import (
0.200.1096 by Jelmer Vernooij
Implement GitWorkingTreeFormat.initialize.
78
    LocalGitDir,
79
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
80
from .tree import (
0.200.622 by Jelmer Vernooij
Implement InterTree.iter_changes() as well.
81
    changes_from_git_changes,
0.200.617 by Jelmer Vernooij
Add custom InterTree for use between git revision trees.
82
    tree_delta_from_git_changes,
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
83
    InterGitTrees,
0.200.617 by Jelmer Vernooij
Add custom InterTree for use between git revision trees.
84
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
85
from .mapping import (
0.200.971 by Chadrik
Fix 'bzr status' after 'bzr add' in native git working trees.
86
    GitFileIdMap,
0.264.10 by Jelmer Vernooij
Yield inventory entries.
87
    mode_kind,
0.200.971 by Chadrik
Fix 'bzr status' after 'bzr add' in native git working trees.
88
    )
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
89
0.200.409 by Jelmer Vernooij
Support parsing .gitignore.
90
IGNORE_FILENAME = ".gitignore"
91
92
0.200.1768 by Jelmer Vernooij
Fix handling of normalized filenames.
93
def ensure_normalized_path(path):
94
    """Check whether path is normalized.
95
96
    :raises InvalidNormalization: When path is not normalized, and cannot be
97
        accessed on this platform by the normalized path.
98
    :return: The NFC normalised version of path.
99
    """
100
    norm_path, can_access = osutils.normalized_filename(path)
101
    if norm_path != path:
102
        if can_access:
103
            return norm_path
104
        else:
105
            raise errors.InvalidNormalization(path)
106
    return path
107
108
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
109
class GitWorkingTree(workingtree.WorkingTree):
110
    """A Git working tree."""
111
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
112
    def __init__(self, controldir, repo, branch, index):
0.200.1741 by Jelmer Vernooij
Fix opentree tests.
113
        basedir = controldir.root_transport.local_abspath('.')
114
        self.basedir = osutils.realpath(basedir)
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
115
        self.controldir = controldir
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
116
        self.repository = repo
0.200.1205 by Jelmer Vernooij
Implement GitWorkingTree.stored_kind.
117
        self.store = self.repository._git.object_store
0.200.384 by Jelmer Vernooij
Fix reading of inventory from index.
118
        self.mapping = self.repository.get_mapping()
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
119
        self._branch = branch
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
120
        self._transport = controldir.transport
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
121
        self._format = GitWorkingTreeFormat()
0.200.803 by Jelmer Vernooij
Default to non-bare repositories when initializing a control directory.
122
        self.index = index
0.200.1242 by Jelmer Vernooij
Support directories better.
123
        self._versioned_dirs = None
0.200.239 by Jelmer Vernooij
Provide views.
124
        self.views = self._make_views()
0.200.1173 by Jelmer Vernooij
Provide GitWorkingTree._rules_searcher.
125
        self._rules_searcher = None
0.200.381 by Jelmer Vernooij
Support working trees properly, status and ls.
126
        self._detect_case_handling()
0.200.1202 by Jelmer Vernooij
Implement has_or_had_id.
127
        self._reset_data()
128
        self._fileid_map = self._basis_fileid_map.copy()
0.200.1476 by Jelmer Vernooij
Cope with working tree refactoring.
129
        self._lock_mode = None
130
        self._lock_count = 0
131
0.200.1650 by Jelmer Vernooij
Implement GitWorkingTree.supports_tree_reference.
132
    def supports_tree_reference(self):
133
        return False
134
0.200.1476 by Jelmer Vernooij
Cope with working tree refactoring.
135
    def lock_read(self):
136
        """Lock the repository for read operations.
137
0.200.1646 by Jelmer Vernooij
Rename bzrlib to breezy.
138
        :return: A breezy.lock.LogicalLockResult.
0.200.1476 by Jelmer Vernooij
Cope with working tree refactoring.
139
        """
140
        if not self._lock_mode:
141
            self._lock_mode = 'r'
142
            self._lock_count = 1
0.200.1525 by Jelmer Vernooij
Make sure to always use an up-to-date index.
143
            self.index.read()
0.200.1476 by Jelmer Vernooij
Cope with working tree refactoring.
144
        else:
145
            self._lock_count += 1
146
        self.branch.lock_read()
147
        return lock.LogicalLockResult(self.unlock)
148
0.200.1477 by Jelmer Vernooij
Implement GitWorkingTree.lock_tree_write.
149
    def lock_tree_write(self):
150
        if not self._lock_mode:
151
            self._lock_mode = 'w'
152
            self._lock_count = 1
0.200.1525 by Jelmer Vernooij
Make sure to always use an up-to-date index.
153
            self.index.read()
0.200.1477 by Jelmer Vernooij
Implement GitWorkingTree.lock_tree_write.
154
        elif self._lock_mode == 'r':
155
            raise errors.ReadOnlyError(self)
156
        else:
157
            self._lock_count +=1
158
        self.branch.lock_read()
159
        return lock.LogicalLockResult(self.unlock)
160
0.200.1476 by Jelmer Vernooij
Cope with working tree refactoring.
161
    def lock_write(self, token=None):
162
        if not self._lock_mode:
163
            self._lock_mode = 'w'
164
            self._lock_count = 1
0.200.1525 by Jelmer Vernooij
Make sure to always use an up-to-date index.
165
            self.index.read()
0.200.1476 by Jelmer Vernooij
Cope with working tree refactoring.
166
        elif self._lock_mode == 'r':
167
            raise errors.ReadOnlyError(self)
168
        else:
169
            self._lock_count +=1
170
        self.branch.lock_write()
171
        return lock.LogicalLockResult(self.unlock)
172
173
    def is_locked(self):
174
        return self._lock_count >= 1
175
176
    def get_physical_lock_status(self):
177
        return False
178
179
    def unlock(self):
180
        if not self._lock_count:
181
            return lock.cant_unlock_not_held(self)
0.200.1530 by Jelmer Vernooij
Fix lock order.
182
        self.branch.unlock()
0.200.1476 by Jelmer Vernooij
Cope with working tree refactoring.
183
        self._cleanup()
184
        self._lock_count -= 1
185
        if self._lock_count > 0:
186
            return
187
        self._lock_mode = None
0.200.173 by Jelmer Vernooij
Merge changes, open index.
188
0.200.1658 by Jelmer Vernooij
Fix handling of ignores - return patterns that matched.
189
    def _cleanup(self):
190
        pass
191
0.200.1322 by Jelmer Vernooij
Add case detection.
192
    def _detect_case_handling(self):
193
        try:
194
            self._transport.stat(".git/cOnFiG")
195
        except errors.NoSuchFile:
196
            self.case_sensitive = True
197
        else:
198
            self.case_sensitive = False
199
0.200.1315 by Jelmer Vernooij
Implement WorkingTree.merge_modified.
200
    def merge_modified(self):
201
        return {}
202
0.200.1696 by Jelmer Vernooij
Fix set_merge_modified.
203
    def set_merge_modified(self, modified_hashes):
0.298.1 by Jelmer Vernooij
mark GitWorkngTree.set_merge_modified as unsupported.
204
        raise errors.UnsupportedOperation(self.set_merge_modified, self)
0.200.1690 by Jelmer Vernooij
Implement WorkingTree.set_merge_modified.
205
0.200.1220 by Jelmer Vernooij
Support set_parent_trees.
206
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
207
        self.set_parent_ids([p for p, t in parents_list])
208
0.305.1 by Jelmer Vernooij
Reset RHS parents after commit.
209
    def _set_merges_from_parent_ids(self, rhs_parent_ids):
0.200.1779 by Jelmer Vernooij
Actually store git revision ids rather than bzr revision ids.
210
        try:
0.305.1 by Jelmer Vernooij
Reset RHS parents after commit.
211
            merges = [self.branch.lookup_bzr_revision_id(revid)[0] for revid in rhs_parent_ids]
0.200.1779 by Jelmer Vernooij
Actually store git revision ids rather than bzr revision ids.
212
        except errors.NoSuchRevision as e:
213
            raise errors.GhostRevisionUnusableHere(e.revision)
0.304.1 by Jelmer Vernooij
Delete MERGE_HEAD if there are no parent ids.
214
        if merges:
215
            self.control_transport.put_bytes('MERGE_HEAD', '\n'.join(merges),
216
                mode=self.controldir._get_file_mode())
217
        else:
218
            try:
219
                self.control_transport.delete('MERGE_HEAD')
220
            except errors.NoSuchFile:
221
                pass
0.200.1720 by Jelmer Vernooij
Fix handling of pending merges.
222
223
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
224
        """Set the parent ids to revision_ids.
225
226
        See also set_parent_trees. This api will try to retrieve the tree data
227
        for each element of revision_ids from the trees repository. If you have
228
        tree data already available, it is more efficient to use
229
        set_parent_trees rather than set_parent_ids. set_parent_ids is however
230
        an easier API to use.
231
232
        :param revision_ids: The revision_ids to set as the parent ids of this
233
            working tree. Any of these may be ghosts.
234
        """
235
        with self.lock_tree_write():
236
            self._check_parents_for_ghosts(revision_ids,
237
                allow_leftmost_as_ghost=allow_leftmost_as_ghost)
238
            for revision_id in revision_ids:
239
                _mod_revision.check_not_reserved_id(revision_id)
240
241
            revision_ids = self._filter_parent_ids_by_ancestry(revision_ids)
242
243
            if len(revision_ids) > 0:
244
                self.set_last_revision(revision_ids[0])
245
            else:
246
                self.set_last_revision(_mod_revision.NULL_REVISION)
247
0.305.1 by Jelmer Vernooij
Reset RHS parents after commit.
248
            self._set_merges_from_parent_ids(revision_ids[1:])
0.200.1720 by Jelmer Vernooij
Fix handling of pending merges.
249
250
    def get_parent_ids(self):
251
        """See Tree.get_parent_ids.
252
253
        This implementation reads the pending merges list and last_revision
254
        value and uses that to decide what the parents list should be.
255
        """
256
        last_rev = _mod_revision.ensure_null(self._last_revision())
257
        if _mod_revision.NULL_REVISION == last_rev:
258
            parents = []
259
        else:
260
            parents = [last_rev]
261
        try:
262
            merges_bytes = self.control_transport.get_bytes('MERGE_HEAD')
263
        except errors.NoSuchFile:
264
            pass
265
        else:
266
            for l in osutils.split_lines(merges_bytes):
267
                revision_id = l.rstrip('\n')
0.200.1779 by Jelmer Vernooij
Actually store git revision ids rather than bzr revision ids.
268
                parents.append(self.branch.lookup_foreign_revision_id(revision_id))
0.200.1720 by Jelmer Vernooij
Fix handling of pending merges.
269
        return parents
270
0.200.1599 by Jelmer Vernooij
Implement GitWorkingTree.iter_children.
271
    def iter_children(self, file_id):
272
        dpath = self.id2path(file_id) + "/"
273
        if dpath in self.index:
274
            return
275
        for path in self.index:
276
            if not path.startswith(dpath):
277
                continue
278
            if "/" in path[len(dpath):]:
279
                # Not a direct child but something further down
280
                continue
281
            yield self.path2id(path)
282
0.316.2 by Jelmer Vernooij
Flush after modifying index.
283
    def _index_add_entry(self, path, kind, flags=0):
0.200.1525 by Jelmer Vernooij
Make sure to always use an up-to-date index.
284
        assert self._lock_mode is not None
0.200.1206 by Jelmer Vernooij
Implement GitWorkingTree.all_file_ids.
285
        assert isinstance(path, basestring)
0.264.2 by Jelmer Vernooij
Implement GitWorkingTree.{_add,__iter__,id2path}.
286
        if kind == "directory":
287
            # Git indexes don't contain directories
288
            return
289
        if kind == "file":
290
            blob = Blob()
291
            try:
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
292
                file, stat_val = self.get_file_with_stat(path)
0.264.2 by Jelmer Vernooij
Implement GitWorkingTree.{_add,__iter__,id2path}.
293
            except (errors.NoSuchFile, IOError):
294
                # TODO: Rather than come up with something here, use the old index
295
                file = StringIO()
0.265.1 by Martin
Don't import posix module, the os wrapper exists for portability
296
                stat_val = os.stat_result(
297
                    (stat.S_IFREG | 0644, 0, 0, 0, 0, 0, 0, 0, 0, 0))
0.264.2 by Jelmer Vernooij
Implement GitWorkingTree.{_add,__iter__,id2path}.
298
            blob.set_raw_string(file.read())
299
        elif kind == "symlink":
300
            blob = Blob()
301
            try:
302
                stat_val = os.lstat(self.abspath(path))
303
            except (errors.NoSuchFile, OSError):
0.200.1636 by Jelmer Vernooij
Some formatting fixes.
304
                # TODO: Rather than come up with something here, use the
0.264.2 by Jelmer Vernooij
Implement GitWorkingTree.{_add,__iter__,id2path}.
305
                # old index
0.265.1 by Martin
Don't import posix module, the os wrapper exists for portability
306
                stat_val = os.stat_result(
307
                    (stat.S_IFLNK, 0, 0, 0, 0, 0, 0, 0, 0, 0))
0.200.1321 by Jelmer Vernooij
More fixes for compatibility with bzr.dev testsuite.
308
            blob.set_raw_string(
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
309
                self.get_symlink_target(path).encode("utf-8"))
0.264.2 by Jelmer Vernooij
Implement GitWorkingTree.{_add,__iter__,id2path}.
310
        else:
311
            raise AssertionError("unknown kind '%s'" % kind)
312
        # Add object to the repository if it didn't exist yet
0.200.1205 by Jelmer Vernooij
Implement GitWorkingTree.stored_kind.
313
        if not blob.id in self.store:
314
            self.store.add_object(blob)
0.264.2 by Jelmer Vernooij
Implement GitWorkingTree.{_add,__iter__,id2path}.
315
        # Add an entry to the index or update the existing entry
0.200.1768 by Jelmer Vernooij
Fix handling of normalized filenames.
316
        ensure_normalized_path(path)
0.200.1242 by Jelmer Vernooij
Support directories better.
317
        encoded_path = path.encode("utf-8")
0.200.1770 by Jelmer Vernooij
Fix test for illegal characters in filenames.
318
        if b'\r' in encoded_path or b'\n' in encoded_path:
319
            # TODO(jelmer): Why do we need to do this?
320
            trace.mutter('ignoring path with invalid newline in it: %r', path)
321
            return
0.200.1531 by Jelmer Vernooij
Don't trust index contents - verify against file timestamps.
322
        self.index[encoded_path] = index_entry_from_stat(
323
            stat_val, blob.id, flags)
0.200.1242 by Jelmer Vernooij
Support directories better.
324
        if self._versioned_dirs is not None:
325
            self._ensure_versioned_dir(encoded_path)
326
327
    def _ensure_versioned_dir(self, dirname):
0.200.1249 by Jelmer Vernooij
Fix file id for tree root
328
        if dirname in self._versioned_dirs:
0.200.1242 by Jelmer Vernooij
Support directories better.
329
            return
0.200.1249 by Jelmer Vernooij
Fix file id for tree root
330
        if dirname != "":
331
            self._ensure_versioned_dir(posixpath.dirname(dirname))
0.200.1242 by Jelmer Vernooij
Support directories better.
332
        self._versioned_dirs.add(dirname)
333
334
    def _load_dirs(self):
0.200.1525 by Jelmer Vernooij
Make sure to always use an up-to-date index.
335
        assert self._lock_mode is not None
0.200.1242 by Jelmer Vernooij
Support directories better.
336
        self._versioned_dirs = set()
337
        for p in self.index:
338
            self._ensure_versioned_dir(posixpath.dirname(p))
0.264.2 by Jelmer Vernooij
Implement GitWorkingTree.{_add,__iter__,id2path}.
339
0.200.1215 by Jelmer Vernooij
Implement GitWorkingTree.remove.
340
    def _unversion_path(self, path):
0.200.1525 by Jelmer Vernooij
Make sure to always use an up-to-date index.
341
        assert self._lock_mode is not None
0.200.1215 by Jelmer Vernooij
Implement GitWorkingTree.remove.
342
        encoded_path = path.encode("utf-8")
0.287.6 by Jelmer Vernooij
Fix some more tests.
343
        count = 0
0.200.1215 by Jelmer Vernooij
Implement GitWorkingTree.remove.
344
        try:
345
            del self.index[encoded_path]
346
        except KeyError:
347
            # A directory, perhaps?
348
            for p in list(self.index):
0.200.1692 by Jelmer Vernooij
Mark three more tests as xfail.
349
                if p.startswith(encoded_path+b"/"):
0.287.6 by Jelmer Vernooij
Fix some more tests.
350
                    count += 1
0.200.1215 by Jelmer Vernooij
Implement GitWorkingTree.remove.
351
                    del self.index[p]
0.287.6 by Jelmer Vernooij
Fix some more tests.
352
        else:
353
            count = 1
0.200.1772 by Jelmer Vernooij
Fix handling of unversioned file in get_file_sha1.
354
        self._versioned_dirs = None
0.287.6 by Jelmer Vernooij
Fix some more tests.
355
        return count
0.200.1215 by Jelmer Vernooij
Implement GitWorkingTree.remove.
356
0.285.8 by Jelmer Vernooij
Fix more tests for swapped arguments.
357
    def unversion(self, paths, file_ids=None):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
358
        with self.lock_tree_write():
0.200.1690 by Jelmer Vernooij
Implement WorkingTree.set_merge_modified.
359
            for path in paths:
0.200.1742 by Jelmer Vernooij
Fix some unversion tests.
360
                encoded_path = path.encode("utf-8")
361
                try:
362
                    del self.index[encoded_path]
363
                except KeyError:
364
                    if not self._has_dir(path):
365
                        raise errors.NoSuchFile(path)
0.200.1772 by Jelmer Vernooij
Fix handling of unversioned file in get_file_sha1.
366
            self._versioned_dirs = None
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
367
            self.flush()
0.200.1215 by Jelmer Vernooij
Implement GitWorkingTree.remove.
368
0.200.1678 by Jelmer Vernooij
Fix tests.
369
    def update_basis_by_delta(self, revid, delta):
370
        # TODO(jelmer): This shouldn't be called, it's inventory specific.
0.316.2 by Jelmer Vernooij
Flush after modifying index.
371
        for (old_path, new_path, file_id, ie) in delta:
372
            if old_path is not None and old_path.encode('utf-8') in self.index:
373
                del self.index[old_path.encode('utf-8')]
374
                self._versioned_dirs = None
375
            if new_path is not None and ie.kind != 'directory':
376
                self._index_add_entry(new_path, ie.kind)
377
        self.flush()
378
        self._set_merges_from_parent_ids([])
0.200.1678 by Jelmer Vernooij
Fix tests.
379
0.200.1243 by Jelmer Vernooij
Implement WorkingTree.check_state.
380
    def check_state(self):
381
        """Check that the working state is/isn't valid."""
382
        pass
383
0.200.1215 by Jelmer Vernooij
Implement GitWorkingTree.remove.
384
    def remove(self, files, verbose=False, to_file=None, keep_files=True,
385
        force=False):
386
        """Remove nominated files from the working tree metadata.
387
388
        :param files: File paths relative to the basedir.
389
        :param keep_files: If true, the files will also be kept.
390
        :param force: Delete files and directories, even if they are changed
391
            and even if the directories are not empty.
392
        """
393
        if isinstance(files, basestring):
394
            files = [files]
395
396
        if to_file is None:
397
            to_file = sys.stdout
398
0.200.1735 by Jelmer Vernooij
Fix remove tests.
399
        files = list(files)
0.200.1215 by Jelmer Vernooij
Implement GitWorkingTree.remove.
400
401
        if len(files) == 0:
402
            return # nothing to do
403
404
        # Sort needed to first handle directory content before the directory
405
        files.sort(reverse=True)
406
407
        def backup(file_to_backup):
408
            abs_path = self.abspath(file_to_backup)
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
409
            backup_name = self.controldir._available_backup_name(file_to_backup)
0.200.1215 by Jelmer Vernooij
Implement GitWorkingTree.remove.
410
            osutils.rename(abs_path, self.abspath(backup_name))
411
            return "removed %s (but kept a copy: %s)" % (
412
                file_to_backup, backup_name)
413
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
414
        with self.lock_tree_write():
415
            for f in files:
0.200.1735 by Jelmer Vernooij
Fix remove tests.
416
                if f == '':
417
                    continue
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
418
                else:
419
                    abs_path = self.abspath(f)
420
                    if verbose:
421
                        # having removed it, it must be either ignored or unknown
422
                        if self.is_ignored(f):
423
                            new_status = 'I'
424
                        else:
425
                            new_status = '?'
426
                        # XXX: Really should be a more abstract reporter interface
0.287.6 by Jelmer Vernooij
Fix some more tests.
427
                        kind_ch = osutils.kind_marker(self.kind(f))
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
428
                        to_file.write(new_status + '       ' + f + kind_ch + '\n')
429
                    # Unversion file
0.287.6 by Jelmer Vernooij
Fix some more tests.
430
                    # TODO(jelmer): _unversion_path() is O(size-of-index) for directories
431
                    if self._unversion_path(f) == 0:
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
432
                        if (osutils.isdir(abs_path) and
0.287.6 by Jelmer Vernooij
Fix some more tests.
433
                            len(os.listdir(abs_path)) == 0):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
434
                            if not keep_files:
435
                                osutils.delete_any(abs_path)
0.287.6 by Jelmer Vernooij
Fix some more tests.
436
                            message = "removed %s" % (f,)
437
                        else:
438
                            message = "%s is not versioned." % (f,)
439
                    else:
440
                        message = "removed %s" % (f,)
441
                        if osutils.lexists(abs_path):
442
                            if (osutils.isdir(abs_path) and
443
                                len(os.listdir(abs_path)) > 0):
444
                                if force:
445
                                    osutils.rmtree(abs_path)
446
                                    message = "deleted %s" % (f,)
447
                                else:
448
                                    message = backup(f)
449
                            else:
450
                                if not keep_files:
451
                                    osutils.delete_any(abs_path)
452
                                    message = "deleted %s" % (f,)
0.200.1215 by Jelmer Vernooij
Implement GitWorkingTree.remove.
453
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
454
                # print only one message (if any) per file.
455
                if message is not None:
456
                    trace.note(message)
457
            self.flush()
0.200.1192 by Jelmer Vernooij
Implement path2id.
458
0.264.2 by Jelmer Vernooij
Implement GitWorkingTree.{_add,__iter__,id2path}.
459
    def _add(self, files, ids, kinds):
460
        for (path, file_id, kind) in zip(files, ids, kinds):
0.200.1201 by Jelmer Vernooij
Implement _set_root_id.
461
            if file_id is not None:
0.200.1663 by Jelmer Vernooij
Raise SettingFileIdUnsupported
462
                raise workingtree.SettingFileIdUnsupported()
463
            self._index_add_entry(path, kind)
0.200.1201 by Jelmer Vernooij
Implement _set_root_id.
464
0.200.1240 by Jelmer Vernooij
Implement GitWorkingTree.smart_add.
465
    def smart_add(self, file_list, recurse=True, action=None, save=True):
0.200.1771 by Jelmer Vernooij
Fix implicit tree unicode add test.
466
        if not file_list:
467
            file_list = [u'.']
0.200.1781 by Jelmer Vernooij
Support expanding symlinks.
468
469
        # expand any symlinks in the directory part, while leaving the
470
        # filename alone
471
        # only expanding if symlinks are supported avoids windows path bugs
472
        if osutils.has_symlinks():
473
            file_list = list(map(osutils.normalizepath, file_list))
474
0.200.1240 by Jelmer Vernooij
Implement GitWorkingTree.smart_add.
475
        added = []
476
        ignored = {}
477
        user_dirs = []
0.200.1733 by Jelmer Vernooij
Support handling of custom ids in smart_add.
478
        def call_action(filepath, kind):
479
            if action is not None:
480
                parent_path = posixpath.dirname(filepath)
481
                parent_id = self.path2id(parent_path)
482
                parent_ie = self._get_dir_ie(parent_path, parent_id)
483
                file_id = action(self, parent_ie, filepath, kind)
484
                if file_id is not None:
485
                    raise workingtree.SettingFileIdUnsupported()
486
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
487
        with self.lock_tree_write():
488
            for filepath in osutils.canonical_relpaths(self.basedir, file_list):
0.200.1768 by Jelmer Vernooij
Fix handling of normalized filenames.
489
                filepath = osutils.normalized_filename(filepath)[0]
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
490
                abspath = self.abspath(filepath)
0.200.1240 by Jelmer Vernooij
Implement GitWorkingTree.smart_add.
491
                kind = osutils.file_kind(abspath)
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
492
                if kind in ("file", "symlink"):
0.200.1733 by Jelmer Vernooij
Support handling of custom ids in smart_add.
493
                    call_action(filepath, kind)
0.200.1308 by Jelmer Vernooij
Write index to disk after adding files.
494
                    if save:
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
495
                        self._index_add_entry(filepath, kind)
496
                    added.append(filepath)
497
                elif kind == "directory":
0.200.1733 by Jelmer Vernooij
Support handling of custom ids in smart_add.
498
                    call_action(filepath, kind)
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
499
                    if recurse:
500
                        user_dirs.append(filepath)
501
                else:
502
                    raise errors.BadFileKindError(filename=abspath, kind=kind)
503
            for user_dir in user_dirs:
504
                abs_user_dir = self.abspath(user_dir)
0.200.1752 by Jelmer Vernooij
Don't traverse nested trees in WorkingTree.smart_add.
505
                if user_dir != '':
506
                    try:
507
                        transport = _mod_transport.get_transport_from_path(abs_user_dir)
508
                        _mod_controldir.ControlDirFormat.find_format(transport)
509
                        subtree = True
510
                    except errors.NotBranchError:
511
                        subtree = False
512
                    except errors.UnsupportedFormatError:
513
                        subtree = False
514
                else:
515
                    subtree = False
516
                if subtree:
0.200.1769 by Jelmer Vernooij
Raise proper error when encountering nested trees.
517
                    trace.warning('skipping nested tree %r', abs_user_dir)
0.200.1752 by Jelmer Vernooij
Don't traverse nested trees in WorkingTree.smart_add.
518
                    continue
519
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
520
                for name in os.listdir(abs_user_dir):
521
                    subp = os.path.join(user_dir, name)
522
                    if self.is_control_filename(subp) or self.mapping.is_special_file(subp):
523
                        continue
524
                    ignore_glob = self.is_ignored(subp)
525
                    if ignore_glob is not None:
526
                        ignored.setdefault(ignore_glob, []).append(subp)
527
                        continue
528
                    abspath = self.abspath(subp)
529
                    kind = osutils.file_kind(abspath)
530
                    if kind == "directory":
531
                        user_dirs.append(subp)
532
                    else:
0.200.1733 by Jelmer Vernooij
Support handling of custom ids in smart_add.
533
                        call_action(filepath, kind)
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
534
                        if save:
535
                            self._index_add_entry(subp, kind)
0.200.1751 by Jelmer Vernooij
Fix smart_add return value.
536
                        added.append(subp)
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
537
            if added and save:
538
                self.flush()
539
            return added, ignored
0.200.1240 by Jelmer Vernooij
Implement GitWorkingTree.smart_add.
540
0.200.1201 by Jelmer Vernooij
Implement _set_root_id.
541
    def _set_root_id(self, file_id):
542
        self._fileid_map.set_file_id("", file_id)
0.264.2 by Jelmer Vernooij
Implement GitWorkingTree.{_add,__iter__,id2path}.
543
0.200.1193 by Jelmer Vernooij
Implement GitWorkingTree.{move,rename_one}.
544
    def move(self, from_paths, to_dir=None, after=False):
545
        rename_tuples = []
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
546
        with self.lock_tree_write():
547
            to_abs = self.abspath(to_dir)
548
            if not os.path.isdir(to_abs):
549
                raise errors.BzrMoveFailedError('', to_dir,
550
                    errors.NotADirectory(to_abs))
551
552
            for from_rel in from_paths:
553
                from_tail = os.path.split(from_rel)[-1]
554
                to_rel = os.path.join(to_dir, from_tail)
555
                self.rename_one(from_rel, to_rel, after=after)
556
                rename_tuples.append((from_rel, to_rel))
557
            self.flush()
558
            return rename_tuples
559
0.200.1193 by Jelmer Vernooij
Implement GitWorkingTree.{move,rename_one}.
560
    def rename_one(self, from_rel, to_rel, after=False):
0.200.1203 by Jelmer Vernooij
Fix per_workingtree.test_rename_one.TestRenameOne.test_rename_after_non_existant_non_ascii
561
        from_path = from_rel.encode("utf-8")
0.200.1768 by Jelmer Vernooij
Fix handling of normalized filenames.
562
        ensure_normalized_path(to_rel)
0.200.1203 by Jelmer Vernooij
Fix per_workingtree.test_rename_one.TestRenameOne.test_rename_after_non_existant_non_ascii
563
        to_path = to_rel.encode("utf-8")
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
564
        with self.lock_tree_write():
0.200.1737 by Jelmer Vernooij
Fix rename tests.
565
            if not after:
566
                if not self.has_filename(from_rel):
567
                    raise errors.BzrMoveFailedError(from_rel, to_rel,
568
                        errors.NoSuchFile(from_rel))
569
            else:
570
                if not self.has_filename(to_rel):
571
                    raise errors.BzrMoveFailedError(from_rel, to_rel,
572
                        errors.NoSuchFile(to_rel))
573
0.200.1748 by Jelmer Vernooij
Fix rename test.
574
            kind = self.kind(from_rel)
575
            if not from_path in self.index and kind != 'directory':
576
                # It's not a file
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
577
                raise errors.BzrMoveFailedError(from_rel, to_rel,
578
                    errors.NotVersionedError(path=from_rel))
0.200.1737 by Jelmer Vernooij
Fix rename tests.
579
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
580
            if not after:
0.200.1737 by Jelmer Vernooij
Fix rename tests.
581
                try:
582
                    os.rename(self.abspath(from_rel), self.abspath(to_rel))
583
                except OSError as e:
584
                    if e.errno == errno.ENOENT:
585
                        raise errors.BzrMoveFailedError(from_rel, to_rel,
586
                            errors.NoSuchFile(to_rel))
587
                    raise
0.200.1748 by Jelmer Vernooij
Fix rename test.
588
            if kind != 'directory':
589
                self.index[to_path] = self.index[from_path]
590
                del self.index[from_path]
0.200.1772 by Jelmer Vernooij
Fix handling of unversioned file in get_file_sha1.
591
            self._versioned_dirs = None
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
592
            self.flush()
0.200.1193 by Jelmer Vernooij
Implement GitWorkingTree.{move,rename_one}.
593
0.264.1 by Jelmer Vernooij
Provide stubs using inventory for the moment.:
594
    def get_root_id(self):
0.200.1192 by Jelmer Vernooij
Implement path2id.
595
        return self.path2id("")
596
0.200.1712 by Jelmer Vernooij
Add file_id prefix.
597
    def has_filename(self, filename):
598
        return osutils.lexists(self.abspath(filename))
599
0.200.1242 by Jelmer Vernooij
Support directories better.
600
    def _has_dir(self, path):
0.200.1368 by Jelmer Vernooij
There is always a tree root.
601
        if path == "":
602
            return True
0.200.1242 by Jelmer Vernooij
Support directories better.
603
        if self._versioned_dirs is None:
604
            self._load_dirs()
605
        return path in self._versioned_dirs
606
0.200.1192 by Jelmer Vernooij
Implement path2id.
607
    def path2id(self, path):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
608
        with self.lock_read():
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
609
            path = path.rstrip('/')
610
            if self.is_versioned(path.rstrip('/')):
611
                return self._fileid_map.lookup_file_id(path.encode("utf-8"))
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
612
            return None
0.264.1 by Jelmer Vernooij
Provide stubs using inventory for the moment.:
613
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
614
    def _iter_files_recursive(self, from_dir=None, include_dirs=False):
0.200.1328 by Jelmer Vernooij
More test fixes.
615
        if from_dir is None:
616
            from_dir = ""
617
        for (dirpath, dirnames, filenames) in os.walk(self.abspath(from_dir)):
0.200.1302 by Jelmer Vernooij
Significantly improve performance of WorkingTree.extras().
618
            dir_relpath = dirpath[len(self.basedir):].strip("/")
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
619
            if self.controldir.is_control_filename(dir_relpath):
0.200.605 by Jelmer Vernooij
Ignore directories in WorkingTree.extras().
620
                continue
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
621
            for name in list(dirnames):
622
                if self.controldir.is_control_filename(name):
623
                    dirnames.remove(name)
624
                    continue
625
                relpath = os.path.join(dir_relpath, name)
626
                if include_dirs:
627
                    yield relpath
628
                if not self._has_dir(relpath):
629
                    dirnames.remove(name)
630
            for name in filenames:
631
                if not self.mapping.is_special_file(name):
632
                    yield os.path.join(dir_relpath, name)
0.200.1327 by Jelmer Vernooij
Factor out all file browsing in extras.
633
634
    def extras(self):
635
        """Yield all unversioned files in this WorkingTree.
636
        """
0.200.1676 by Jelmer Vernooij
Fix typo.
637
        with self.lock_read():
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
638
            return set(self._iter_files_recursive()) - set(self.index)
0.200.605 by Jelmer Vernooij
Ignore directories in WorkingTree.extras().
639
0.200.382 by Jelmer Vernooij
Support flushing index.
640
    def flush(self):
0.287.6 by Jelmer Vernooij
Fix some more tests.
641
        # TODO: Maybe this should only write on dirty ?
642
        if self._lock_mode != 'w':
643
            raise errors.NotWriteLocked(self)
644
        self.index.write()
0.200.382 by Jelmer Vernooij
Support flushing index.
645
0.264.1 by Jelmer Vernooij
Provide stubs using inventory for the moment.:
646
    def __iter__(self):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
647
        with self.lock_read():
648
            for path in self.index:
649
                yield self.path2id(path)
650
            self._load_dirs()
651
            for path in self._versioned_dirs:
652
                yield self.path2id(path)
0.264.1 by Jelmer Vernooij
Provide stubs using inventory for the moment.:
653
0.200.1202 by Jelmer Vernooij
Implement has_or_had_id.
654
    def has_or_had_id(self, file_id):
655
        if self.has_id(file_id):
656
            return True
657
        if self.had_id(file_id):
658
            return True
659
        return False
660
661
    def had_id(self, file_id):
662
        path = self._basis_fileid_map.lookup_file_id(file_id)
663
        try:
664
            head = self.repository._git.head()
665
        except KeyError:
666
            # Assume no if basis is not accessible
667
            return False
0.200.1205 by Jelmer Vernooij
Implement GitWorkingTree.stored_kind.
668
        if head == ZERO_SHA:
669
            return False
0.200.1202 by Jelmer Vernooij
Implement has_or_had_id.
670
        root_tree = self.store[head].tree
671
        try:
672
            tree_lookup_path(self.store.__getitem__, root_tree, path)
673
        except KeyError:
674
            return False
675
        else:
676
            return True
677
0.200.1198 by Jelmer Vernooij
Implement GitWorkingTree.has_id.
678
    def has_id(self, file_id):
679
        try:
680
            self.id2path(file_id)
681
        except errors.NoSuchId:
682
            return False
683
        else:
684
            return True
685
0.264.1 by Jelmer Vernooij
Provide stubs using inventory for the moment.:
686
    def id2path(self, file_id):
0.200.1532 by Jelmer Vernooij
Cope with float timestamps.
687
        assert type(file_id) is str, "file id not a string: %r" % file_id
0.200.1411 by Jelmer Vernooij
Fix control files.
688
        file_id = osutils.safe_utf8(file_id)
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
689
        with self.lock_read():
0.200.1712 by Jelmer Vernooij
Add file_id prefix.
690
            try:
691
                path = self._fileid_map.lookup_path(file_id)
692
            except ValueError:
693
                raise errors.NoSuchId(self, file_id)
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
694
            path = path.decode('utf-8')
695
            if self.is_versioned(path):
696
                return path
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
697
            raise errors.NoSuchId(self, file_id)
0.264.1 by Jelmer Vernooij
Provide stubs using inventory for the moment.:
698
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
699
    def get_file_mtime(self, path, file_id=None):
0.200.1200 by Jelmer Vernooij
Support GitWorkingTree.get_file_mtime.
700
        """See Tree.get_file_mtime."""
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
701
        try:
702
            return os.lstat(self.abspath(path)).st_mtime
703
        except OSError, (num, msg):
704
            if num == errno.ENOENT:
705
                raise errors.NoSuchFile(path)
706
            raise
0.200.1200 by Jelmer Vernooij
Support GitWorkingTree.get_file_mtime.
707
0.200.1655 by Jelmer Vernooij
Basic support for git ignores.
708
    def is_ignored(self, filename):
709
        r"""Check whether the filename matches an ignore pattern.
710
711
        If the file is ignored, returns the pattern which caused it to
712
        be ignored, otherwise None.  So this can simply be used as a
713
        boolean if desired."""
714
        if getattr(self, '_global_ignoreglobster', None) is None:
715
            ignore_globs = set()
716
            ignore_globs.update(ignores.get_runtime_ignores())
717
            ignore_globs.update(ignores.get_user_ignores())
718
            self._global_ignoreglobster = globbing.ExceptionGlobster(ignore_globs)
0.200.1656 by Jelmer Vernooij
Report proper patterns, ignore files.
719
        match = self._global_ignoreglobster.match(filename)
720
        if match is not None:
721
            return match
0.200.1716 by Jelmer Vernooij
Fix some more tests.
722
        try:
723
            if self.kind(filename) == 'directory':
724
                filename += b'/'
725
        except errors.NoSuchFile:
726
            pass
727
        filename = filename.lstrip(b'/')
0.200.1658 by Jelmer Vernooij
Fix handling of ignores - return patterns that matched.
728
        ignore_manager = self._get_ignore_manager()
729
        ps = list(ignore_manager.find_matching(filename))
730
        if not ps:
731
            return None
732
        if not ps[-1].is_exclude:
733
            return None
734
        return bytes(ps[-1])
735
736
    def _get_ignore_manager(self):
737
        ignoremanager = getattr(self, '_ignoremanager', None)
738
        if ignoremanager is not None:
739
            return ignoremanager
740
741
        ignore_manager = IgnoreFilterManager.from_repo(self.repository._git)
742
        self._ignoremanager = ignore_manager
743
        return ignore_manager
0.200.409 by Jelmer Vernooij
Support parsing .gitignore.
744
0.200.1716 by Jelmer Vernooij
Fix some more tests.
745
    def _flush_ignore_list_cache(self):
746
        self._ignoremanager = None
747
0.200.508 by Jelmer Vernooij
Skip inventory caching bits.
748
    def set_last_revision(self, revid):
0.200.1720 by Jelmer Vernooij
Fix handling of pending merges.
749
        if _mod_revision.is_null(revid):
750
            self.branch.set_last_revision_info(0, revid)
751
            return False
752
        _mod_revision.check_not_reserved_id(revid)
753
        try:
754
            self.branch.generate_revision_history(revid)
755
        except errors.NoSuchRevision:
756
            raise errors.GhostRevisionUnusableHere(revid)
0.200.508 by Jelmer Vernooij
Skip inventory caching bits.
757
0.200.379 by Jelmer Vernooij
Re-enable working tree support.
758
    def _reset_data(self):
0.248.3 by Jelmer Vernooij
Handle working trees without valid HEAD branch.
759
        try:
760
            head = self.repository._git.head()
761
        except KeyError, name:
0.200.1202 by Jelmer Vernooij
Implement has_or_had_id.
762
            self._basis_fileid_map = GitFileIdMap({}, self.mapping)
0.200.948 by Jelmer Vernooij
Cope with empty inventories.
763
        else:
0.310.9 by Jelmer Vernooij
Some controldir fixes.
764
            if head == ZERO_SHA:
765
                self._basis_fileid_map = GitFileIdMap({}, self.mapping)
766
            else:
767
                self._basis_fileid_map = self.mapping.get_fileid_map(
768
                    self.store.__getitem__, self.store[head].tree)
0.200.379 by Jelmer Vernooij
Re-enable working tree support.
769
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
770
    def get_file_verifier(self, path, file_id=None, stat_value=None):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
771
        with self.lock_read():
772
            try:
773
                return ("GIT", self.index[path][-2])
774
            except KeyError:
775
                if self._has_dir(path):
776
                    return ("GIT", None)
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
777
                raise errors.NoSuchFile(path)
0.200.1302 by Jelmer Vernooij
Significantly improve performance of WorkingTree.extras().
778
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
779
    def get_file_sha1(self, path, file_id=None, stat_value=None):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
780
        with self.lock_read():
0.200.1772 by Jelmer Vernooij
Fix handling of unversioned file in get_file_sha1.
781
            if not self.is_versioned(path):
782
                raise errors.NoSuchFile(path)
783
            abspath = self.abspath(path)
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
784
            try:
785
                return osutils.sha_file_by_name(abspath)
786
            except OSError, (num, msg):
787
                if num in (errno.EISDIR, errno.ENOENT):
0.200.1772 by Jelmer Vernooij
Fix handling of unversioned file in get_file_sha1.
788
                    return None
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
789
                raise
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
790
0.200.610 by Jelmer Vernooij
Support retrieving basis tree properly.
791
    def revision_tree(self, revid):
792
        return self.repository.revision_tree(revid)
793
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
794
    def is_versioned(self, path):
795
        with self.lock_read():
796
            path = path.rstrip('/').encode('utf-8')
797
            return (path in self.index or self._has_dir(path))
0.200.1242 by Jelmer Vernooij
Support directories better.
798
0.200.1239 by Jelmer Vernooij
Implement GitWorkingTree.filter_unversioned_files.
799
    def filter_unversioned_files(self, files):
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
800
        return set([p for p in files if not self.is_versioned(p)])
0.200.1239 by Jelmer Vernooij
Implement GitWorkingTree.filter_unversioned_files.
801
0.264.11 by Jelmer Vernooij
Completer implementation of iter_entries_by_dir and list_files.
802
    def _get_dir_ie(self, path, parent_id):
0.200.1192 by Jelmer Vernooij
Implement path2id.
803
        file_id = self.path2id(path)
0.264.11 by Jelmer Vernooij
Completer implementation of iter_entries_by_dir and list_files.
804
        return inventory.InventoryDirectory(file_id,
0.200.1190 by Jelmer Vernooij
Fix get_symlink_target call.
805
            posixpath.basename(path).strip("/"), parent_id)
0.264.11 by Jelmer Vernooij
Completer implementation of iter_entries_by_dir and list_files.
806
807
    def _add_missing_parent_ids(self, path, dir_ids):
808
        if path in dir_ids:
809
            return []
810
        parent = posixpath.dirname(path).strip("/")
811
        ret = self._add_missing_parent_ids(parent, dir_ids)
812
        parent_id = dir_ids[parent]
813
        ie = self._get_dir_ie(path, parent_id)
814
        dir_ids[path] = ie.file_id
815
        ret.append((path, ie))
816
        return ret
817
0.200.1321 by Jelmer Vernooij
More fixes for compatibility with bzr.dev testsuite.
818
    def _get_file_ie(self, name, path, value, parent_id):
819
        assert isinstance(name, unicode)
0.200.1192 by Jelmer Vernooij
Implement path2id.
820
        assert isinstance(path, unicode)
0.264.10 by Jelmer Vernooij
Yield inventory entries.
821
        assert isinstance(value, tuple) and len(value) == 10
822
        (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
0.200.1192 by Jelmer Vernooij
Implement path2id.
823
        file_id = self.path2id(path)
0.264.10 by Jelmer Vernooij
Yield inventory entries.
824
        if type(file_id) != str:
825
            raise AssertionError
826
        kind = mode_kind(mode)
0.200.1321 by Jelmer Vernooij
More fixes for compatibility with bzr.dev testsuite.
827
        ie = inventory.entry_factory[kind](file_id, name, parent_id)
0.264.10 by Jelmer Vernooij
Yield inventory entries.
828
        if kind == 'symlink':
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
829
            ie.symlink_target = self.get_symlink_target(path, file_id)
0.264.10 by Jelmer Vernooij
Yield inventory entries.
830
        else:
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
831
            data = self.get_file_text(path, file_id)
0.264.10 by Jelmer Vernooij
Yield inventory entries.
832
            ie.text_sha1 = osutils.sha_string(data)
833
            ie.text_size = len(data)
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
834
            ie.executable = self.is_executable(path, file_id)
0.264.10 by Jelmer Vernooij
Yield inventory entries.
835
        ie.revision = None
836
        return ie
837
0.264.11 by Jelmer Vernooij
Completer implementation of iter_entries_by_dir and list_files.
838
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
839
        mode = stat_result.st_mode
840
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
841
0.318.1 by Jelmer Vernooij
Fix executable test.
842
    def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
843
        return self.basis_tree().is_executable(path)
844
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
845
    def stored_kind(self, path, file_id=None):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
846
        with self.lock_read():
847
            try:
848
                return mode_kind(self.index[path.encode("utf-8")][4])
849
            except KeyError:
850
                # Maybe it's a directory?
851
                if self._has_dir(path):
852
                    return "directory"
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
853
                raise errors.NoSuchFile(path)
0.200.1205 by Jelmer Vernooij
Implement GitWorkingTree.stored_kind.
854
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
855
    def is_executable(self, path, file_id=None):
0.200.1539 by Jelmer Vernooij
Cope with new is_executable.
856
        if getattr(self, "_supports_executable", osutils.supports_executable)():
857
            mode = os.lstat(self.abspath(path)).st_mode
858
        else:
0.319.1 by Jelmer Vernooij
Support falling back on basis for executable bits.
859
            try:
860
                mode = self.index[path.encode('utf-8')].mode
861
            except KeyError:
862
                mode = 0
863
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
0.264.11 by Jelmer Vernooij
Completer implementation of iter_entries_by_dir and list_files.
864
0.200.1539 by Jelmer Vernooij
Cope with new is_executable.
865
    def _is_executable_from_path_and_stat(self, path, stat_result):
866
        if getattr(self, "_supports_executable", osutils.supports_executable)():
867
            return self._is_executable_from_path_and_stat_from_stat(path, stat_result)
868
        else:
869
            return self._is_executable_from_path_and_stat_from_basis(path, stat_result)
0.264.11 by Jelmer Vernooij
Completer implementation of iter_entries_by_dir and list_files.
870
0.264.10 by Jelmer Vernooij
Yield inventory entries.
871
    def list_files(self, include_root=False, from_dir=None, recursive=True):
0.200.1321 by Jelmer Vernooij
More fixes for compatibility with bzr.dev testsuite.
872
        if from_dir is None:
873
            from_dir = ""
0.264.11 by Jelmer Vernooij
Completer implementation of iter_entries_by_dir and list_files.
874
        dir_ids = {}
0.200.1767 by Jelmer Vernooij
Fix references to Tree*.
875
        fk_entries = {'directory': tree.TreeDirectory,
876
                      'file': tree.TreeFile,
877
                      'symlink': tree.TreeLink}
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
878
        with self.lock_read():
879
            root_ie = self._get_dir_ie(u"", None)
880
            if include_root and not from_dir:
881
                yield "", "V", root_ie.kind, root_ie.file_id, root_ie
882
            dir_ids[u""] = root_ie.file_id
883
            if recursive:
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
884
                path_iterator = sorted(self._iter_files_recursive(from_dir, include_dirs=True))
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
885
            else:
886
                if from_dir is None:
887
                    start = self.basedir
888
                else:
889
                    start = os.path.join(self.basedir, from_dir)
890
                path_iterator = sorted([os.path.join(from_dir, name) for name in
891
                    os.listdir(start) if not self.controldir.is_control_filename(name)
892
                    and not self.mapping.is_special_file(name)])
893
            for path in path_iterator:
894
                try:
895
                    value = self.index[path]
896
                except KeyError:
897
                    value = None
898
                path = path.decode("utf-8")
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
899
                kind = osutils.file_kind(self.abspath(path))
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
900
                parent, name = posixpath.split(path)
901
                for dir_path, dir_ie in self._add_missing_parent_ids(parent, dir_ids):
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
902
                    pass
903
                if kind == 'directory':
904
                    if path != from_dir:
905
                        if self._has_dir(path):
906
                            ie = self._get_dir_ie(path, self.path2id(path))
907
                            status = "V"
908
                            file_id = ie.file_id
909
                        elif self.is_ignored(path):
910
                            status = "I"
911
                            ie = fk_entries[kind]()
912
                            file_id = None
913
                        else:
914
                            status = "?"
915
                            ie = fk_entries[kind]()
916
                            file_id = None
917
                        yield posixpath.relpath(path, from_dir), status, kind, file_id, ie
918
                    continue
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
919
                if value is not None:
920
                    ie = self._get_file_ie(name, path, value, dir_ids[parent])
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
921
                    yield posixpath.relpath(path, from_dir), "V", ie.kind, ie.file_id, ie
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
922
                else:
923
                    ie = fk_entries[kind]()
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
924
                    yield posixpath.relpath(path, from_dir), ("I" if self.is_ignored(path) else "?"), kind, None, ie
0.264.10 by Jelmer Vernooij
Yield inventory entries.
925
0.200.1206 by Jelmer Vernooij
Implement GitWorkingTree.all_file_ids.
926
    def all_file_ids(self):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
927
        with self.lock_read():
928
            ids = {u"": self.path2id("")}
929
            for path in self.index:
930
                if self.mapping.is_special_file(path):
931
                    continue
932
                path = path.decode("utf-8")
933
                parent = posixpath.dirname(path).strip("/")
934
                for e in self._add_missing_parent_ids(parent, ids):
935
                    pass
936
                ids[path] = self.path2id(path)
937
            return set(ids.values())
0.200.1206 by Jelmer Vernooij
Implement GitWorkingTree.all_file_ids.
938
0.200.1710 by Jelmer Vernooij
Regenerate xfail.
939
    def all_versioned_paths(self):
940
        with self.lock_read():
941
            paths = {u""}
942
            for path in self.index:
943
                if self.mapping.is_special_file(path):
944
                    continue
945
                path = path.decode("utf-8")
946
                paths.add(path)
947
                while path != "":
948
                    path = posixpath.dirname(path).strip("/")
949
                    if path in paths:
950
                        break
951
                    paths.add(path)
952
            return paths
953
0.200.1374 by Jelmer Vernooij
Implement GitWorkingTree._directory_is_tree_reference.
954
    def _directory_is_tree_reference(self, path):
955
        # FIXME: Check .gitsubmodules for path
956
        return False
957
0.200.1716 by Jelmer Vernooij
Fix some more tests.
958
    def iter_child_entries(self, path, file_id=None):
959
        encoded_path = path.encode('utf-8')
0.200.1739 by Jelmer Vernooij
Fix iteration order for iter_child_entries.
960
        parent_id = self.path2id(path)
0.200.1738 by Jelmer Vernooij
Fix test_does_not_exist.
961
        found_any = False
0.200.1739 by Jelmer Vernooij
Fix iteration order for iter_child_entries.
962
        seen_children = set()
0.200.1716 by Jelmer Vernooij
Fix some more tests.
963
        for item_path, value in self.index.iteritems():
964
            if self.mapping.is_special_file(item_path):
965
                continue
0.200.1739 by Jelmer Vernooij
Fix iteration order for iter_child_entries.
966
            if not osutils.is_inside(encoded_path, item_path):
0.200.1716 by Jelmer Vernooij
Fix some more tests.
967
                continue
0.200.1738 by Jelmer Vernooij
Fix test_does_not_exist.
968
            found_any = True
0.200.1739 by Jelmer Vernooij
Fix iteration order for iter_child_entries.
969
            subpath = posixpath.relpath(item_path, encoded_path)
0.200.1716 by Jelmer Vernooij
Fix some more tests.
970
            if b'/' in subpath:
0.200.1739 by Jelmer Vernooij
Fix iteration order for iter_child_entries.
971
                dirname = subpath.split(b'/', 1)[0]
972
                file_ie = self._get_dir_ie(posixpath.join(path, dirname), parent_id)
973
            else:
974
                (parent, name) = posixpath.split(item_path)
975
                try:
976
                    file_ie = self._get_file_ie(name, item_path, value, parent_id)
977
                except IOError:
978
                    continue
0.200.1716 by Jelmer Vernooij
Fix some more tests.
979
            yield file_ie
0.200.1738 by Jelmer Vernooij
Fix test_does_not_exist.
980
        if not found_any:
981
            raise errors.NoSuchFile(path)
0.200.1716 by Jelmer Vernooij
Fix some more tests.
982
0.264.9 by Jelmer Vernooij
Implement basic GitWorkingTree.iter_entries_by_dir.
983
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
0.200.1252 by Jelmer Vernooij
Support specific_file_ids in GitWorkingTree.iter_entries_by_dir.
984
        if yield_parents:
985
            raise NotImplementedError(self.iter_entries_by_dir)
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
986
        with self.lock_read():
987
            if specific_file_ids is not None:
0.200.1712 by Jelmer Vernooij
Add file_id prefix.
988
                specific_paths = []
989
                for file_id in specific_file_ids:
0.315.1 by Jelmer Vernooij
Allow file ids passed to Tree.iter_entries_by_dir to be None.
990
                    if file_id is None:
991
                        continue
0.309.1 by Jelmer Vernooij
Allow file-ids to Tree.iter_entries_by_dir to be absent.
992
                    try:
993
                        specific_paths.append(self.id2path(file_id))
994
                    except errors.NoSuchId:
995
                        pass
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
996
                if specific_paths in ([u""], []):
997
                    specific_paths = None
998
                else:
999
                    specific_paths = set(specific_paths)
1000
            else:
0.200.1252 by Jelmer Vernooij
Support specific_file_ids in GitWorkingTree.iter_entries_by_dir.
1001
                specific_paths = None
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1002
            root_ie = self._get_dir_ie(u"", None)
0.200.1740 by Jelmer Vernooij
Fix iter_entries_by_dir order.
1003
            ret = {}
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1004
            if specific_paths is None:
0.200.1740 by Jelmer Vernooij
Fix iter_entries_by_dir order.
1005
                ret[(None, u"")] = root_ie
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1006
            dir_ids = {u"": root_ie.file_id}
1007
            for path, value in self.index.iteritems():
1008
                if self.mapping.is_special_file(path):
1009
                    continue
1010
                path = path.decode("utf-8")
1011
                if specific_paths is not None and not path in specific_paths:
1012
                    continue
1013
                (parent, name) = posixpath.split(path)
1014
                try:
1015
                    file_ie = self._get_file_ie(name, path, value, None)
0.319.1 by Jelmer Vernooij
Support falling back on basis for executable bits.
1016
                except errors.NoSuchFile:
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1017
                    continue
0.200.1730 by Jelmer Vernooij
Fix test_is_executable_dir.
1018
                if yield_parents or specific_file_ids is None:
1019
                    for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
1020
                            dir_ids):
0.200.1740 by Jelmer Vernooij
Fix iter_entries_by_dir order.
1021
                        ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1022
                file_ie.parent_id = self.path2id(parent)
0.200.1740 by Jelmer Vernooij
Fix iter_entries_by_dir order.
1023
                ret[(posixpath.dirname(path), path)] = file_ie
1024
            return ((path, ie) for ((_, path), ie) in sorted(ret.items()))
0.264.9 by Jelmer Vernooij
Implement basic GitWorkingTree.iter_entries_by_dir.
1025
0.200.619 by Jelmer Vernooij
Provide dummy WorkingTree.conflicts() implementation rather than spending a lot of time not finding any conflicts.
1026
    def conflicts(self):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1027
        with self.lock_read():
1028
            # FIXME:
1029
            return _mod_conflicts.ConflictList()
0.200.619 by Jelmer Vernooij
Provide dummy WorkingTree.conflicts() implementation rather than spending a lot of time not finding any conflicts.
1030
0.200.1705 by Jelmer Vernooij
Fix walkdirs.
1031
    def walkdirs(self, prefix=""):
0.200.1210 by Jelmer Vernooij
Implement GitWorkingTree._walkdirs.
1032
        if prefix != "":
1033
            prefix += "/"
1034
        per_dir = defaultdict(list)
1035
        for path, value in self.index.iteritems():
0.200.1328 by Jelmer Vernooij
More test fixes.
1036
            if self.mapping.is_special_file(path):
1037
                continue
0.200.1210 by Jelmer Vernooij
Implement GitWorkingTree._walkdirs.
1038
            if not path.startswith(prefix):
1039
                continue
1040
            (dirname, child_name) = posixpath.split(path)
1041
            dirname = dirname.decode("utf-8")
1042
            dir_file_id = self.path2id(dirname)
1043
            assert isinstance(value, tuple) and len(value) == 10
0.293.1 by Jelmer Vernooij
Fix walkdirs handling of unknown entries, mode.
1044
            try:
1045
                actual_stat = os.lstat(self.abspath(path.decode('utf-8')))
1046
            except OSError as e:
1047
                if e.errno == errno.ENOENT:
1048
                    mode = None
1049
                    curkind = 'unknown'
1050
                    actual_stat = None
1051
                else:
1052
                    raise
1053
            else:
1054
                mode = actual_stat.st_mode
1055
                curkind = mode_kind(actual_stat.st_mode)
0.200.1210 by Jelmer Vernooij
Implement GitWorkingTree._walkdirs.
1056
            per_dir[(dirname, dir_file_id)].append(
1057
                (path.decode("utf-8"), child_name.decode("utf-8"),
0.293.1 by Jelmer Vernooij
Fix walkdirs handling of unknown entries, mode.
1058
                curkind, actual_stat,
0.200.1210 by Jelmer Vernooij
Implement GitWorkingTree._walkdirs.
1059
                self.path2id(path.decode("utf-8")),
0.293.1 by Jelmer Vernooij
Fix walkdirs handling of unknown entries, mode.
1060
                mode_kind(value.mode)))
0.200.1210 by Jelmer Vernooij
Implement GitWorkingTree._walkdirs.
1061
        return per_dir.iteritems()
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
1062
0.200.1542 by Jelmer Vernooij
Refactor iter_changes.
1063
    def _lookup_entry(self, path, update_index=False):
0.200.1543 by Jelmer Vernooij
Support symlinks.
1064
        assert type(path) == str
0.200.1542 by Jelmer Vernooij
Refactor iter_changes.
1065
        entry = self.index[path]
1066
        index_mode = entry[-6]
1067
        index_sha = entry[-2]
0.200.1741 by Jelmer Vernooij
Fix opentree tests.
1068
        disk_path = self.abspath(path.decode('utf-8')).encode(
1069
            osutils._fs_enc)
0.284.1 by Jelmer Vernooij
Raise KeyError when file was removed.
1070
        try:
1071
            disk_stat = os.lstat(disk_path)
1072
        except OSError, (num, msg):
1073
            if num in (errno.EISDIR, errno.ENOENT):
1074
                raise KeyError(path)
1075
            raise
0.200.1542 by Jelmer Vernooij
Refactor iter_changes.
1076
        disk_mtime = disk_stat.st_mtime
1077
        if isinstance(entry[1], tuple):
1078
            index_mtime = entry[1][0]
1079
        else:
1080
            index_mtime = int(entry[1])
1081
        mtime_delta = (disk_mtime - index_mtime)
1082
        disk_mode = cleanup_mode(disk_stat.st_mode)
1083
        if mtime_delta > 0 or disk_mode != index_mode:
1084
            if stat.S_ISDIR(disk_mode):
1085
                try:
1086
                    subrepo = Repo(disk_path)
1087
                except NotGitRepository:
1088
                    return (None, None)
1089
                else:
1090
                    disk_mode = S_IFGITLINK
1091
                    git_id = subrepo.head()
0.200.1543 by Jelmer Vernooij
Support symlinks.
1092
            elif stat.S_ISLNK(disk_mode):
0.200.1715 by Jelmer Vernooij
Fix some more tests.
1093
                blob = Blob.from_string(os.readlink(disk_path))
0.200.1543 by Jelmer Vernooij
Support symlinks.
1094
                git_id = blob.id
1095
            elif stat.S_ISREG(disk_mode):
0.200.1542 by Jelmer Vernooij
Refactor iter_changes.
1096
                with open(disk_path, 'r') as f:
1097
                    blob = Blob.from_string(f.read())
1098
                git_id = blob.id
0.200.1543 by Jelmer Vernooij
Support symlinks.
1099
            else:
1100
                raise AssertionError
0.200.1542 by Jelmer Vernooij
Refactor iter_changes.
1101
            if update_index:
1102
                flags = 0 # FIXME
0.200.1545 by Jelmer Vernooij
Some more test fixes.
1103
                self.index[path] = index_entry_from_stat(disk_stat, git_id, flags, disk_mode)
0.200.1542 by Jelmer Vernooij
Refactor iter_changes.
1104
            return (git_id, disk_mode)
1105
        return (index_sha, index_mode)
1106
0.200.1677 by Jelmer Vernooij
Mark shelving as unsupported.
1107
    def get_shelf_manager(self):
0.200.1729 by Jelmer Vernooij
ShelvingUnsupported doesn't take an argument.
1108
        raise workingtree.ShelvingUnsupported()
0.200.1677 by Jelmer Vernooij
Mark shelving as unsupported.
1109
0.200.1678 by Jelmer Vernooij
Fix tests.
1110
    def store_uncommitted(self):
1111
        raise errors.StoringUncommittedNotSupported(self)
1112
0.200.1703 by Jelmer Vernooij
Implement apply_inventory_delta.
1113
    def apply_inventory_delta(self, changes):
1114
        for (old_path, new_path, file_id, ie) in changes:
1115
            if old_path is not None:
1116
                del self.index[old_path.encode('utf-8')]
0.200.1772 by Jelmer Vernooij
Fix handling of unversioned file in get_file_sha1.
1117
                self._versioned_dirs = None
0.200.1703 by Jelmer Vernooij
Implement apply_inventory_delta.
1118
            if new_path is not None and ie.kind != 'directory':
1119
                self._index_add_entry(new_path, ie.kind)
0.316.2 by Jelmer Vernooij
Flush after modifying index.
1120
        self.flush()
0.200.1703 by Jelmer Vernooij
Implement apply_inventory_delta.
1121
0.200.1756 by Jelmer Vernooij
Initial work on annotate support.
1122
    def annotate_iter(self, path, file_id=None,
1123
                      default_revision=_mod_revision.CURRENT_REVISION):
1124
        """See Tree.annotate_iter
1125
1126
        This implementation will use the basis tree implementation if possible.
1127
        Lines not in the basis are attributed to CURRENT_REVISION
1128
1129
        If there are pending merges, lines added by those merges will be
1130
        incorrectly attributed to CURRENT_REVISION (but after committing, the
1131
        attribution will be correct).
1132
        """
1133
        with self.lock_read():
1134
            maybe_file_parent_keys = []
1135
            for parent_id in self.get_parent_ids():
1136
                try:
1137
                    parent_tree = self.revision_tree(parent_id)
1138
                except errors.NoSuchRevisionInTree:
1139
                    parent_tree = self.branch.repository.revision_tree(
1140
                            parent_id)
1141
                with parent_tree.lock_read():
1142
                    # TODO(jelmer): Use rename/copy tracker to find path name in parent
1143
                    parent_path = path
1144
                    try:
1145
                        kind = parent_tree.kind(parent_path)
1146
                    except errors.NoSuchFile:
1147
                        continue
1148
                    if kind != 'file':
1149
                        # Note: this is slightly unnecessary, because symlinks and
1150
                        # directories have a "text" which is the empty text, and we
1151
                        # know that won't mess up annotations. But it seems cleaner
1152
                        continue
1153
                    parent_text_key = (
1154
                        parent_path,
1155
                        parent_tree.get_file_revision(parent_path))
1156
                    if parent_text_key not in maybe_file_parent_keys:
1157
                        maybe_file_parent_keys.append(parent_text_key)
1158
            graph = self.branch.repository.get_file_graph()
1159
            heads = graph.heads(maybe_file_parent_keys)
1160
            file_parent_keys = []
1161
            for key in maybe_file_parent_keys:
1162
                if key in heads:
1163
                    file_parent_keys.append(key)
1164
1165
            # Now we have the parents of this content
1166
            from breezy.annotate import Annotator
1167
            from .annotate import AnnotateProvider
1168
            annotator = Annotator(AnnotateProvider(
1169
                self.branch.repository._file_change_scanner))
1170
            text = self.get_file_text(path)
1171
            this_key = (path, default_revision)
1172
            annotator.add_special_text(this_key, file_parent_keys, text)
1173
            annotations = [(key[-1], line)
1174
                           for key, line in annotator.annotate_flat(this_key)]
1175
            return annotations
1176
0.200.1308 by Jelmer Vernooij
Write index to disk after adding files.
1177
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
1178
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
1179
0.200.1206 by Jelmer Vernooij
Implement GitWorkingTree.all_file_ids.
1180
    _tree_class = GitWorkingTree
1181
0.200.1295 by Jelmer Vernooij
Mark working trees as not supporting directories.
1182
    supports_versioned_directories = False
1183
0.200.1661 by Jelmer Vernooij
Set supports_setting_file_ids to False.
1184
    supports_setting_file_ids = False
1185
0.200.1677 by Jelmer Vernooij
Mark shelving as unsupported.
1186
    supports_store_uncommitted = False
1187
0.200.1723 by Jelmer Vernooij
Set supports_leftmost_parent_id_as_ghost property.
1188
    supports_leftmost_parent_id_as_ghost = False
1189
0.200.1779 by Jelmer Vernooij
Actually store git revision ids rather than bzr revision ids.
1190
    supports_righthand_parent_id_as_ghost = False
1191
0.200.1768 by Jelmer Vernooij
Fix handling of normalized filenames.
1192
    requires_normalized_unicode_filenames = True
1193
0.200.656 by Jelmer Vernooij
Implement GitWorkingTreeFormat._matchingbzrdir.
1194
    @property
0.200.1665 by Jelmer Vernooij
Rename _matchingbzrdir to _matchingcnotroldir.
1195
    def _matchingcontroldir(self):
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
1196
        from .dir import LocalGitControlDirFormat
0.200.1013 by Jelmer Vernooij
More renames.
1197
        return LocalGitControlDirFormat()
0.200.656 by Jelmer Vernooij
Implement GitWorkingTreeFormat._matchingbzrdir.
1198
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
1199
    def get_format_description(self):
1200
        return "Git Working Tree"
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1201
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
1202
    def initialize(self, a_controldir, revision_id=None, from_branch=None,
0.200.1096 by Jelmer Vernooij
Implement GitWorkingTreeFormat.initialize.
1203
                   accelerator_tree=None, hardlink=False):
1204
        """See WorkingTreeFormat.initialize()."""
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
1205
        if not isinstance(a_controldir, LocalGitDir):
1206
            raise errors.IncompatibleFormat(self, a_controldir)
1207
        index = Index(a_controldir.root_transport.local_abspath(".git/index"))
0.200.1096 by Jelmer Vernooij
Implement GitWorkingTreeFormat.initialize.
1208
        index.write()
0.308.1 by Jelmer Vernooij
Set revision id if specified to WorkingTreeFormat.initialize.
1209
        branch = a_controldir.open_branch()
1210
        if revision_id is not None:
1211
            branch.set_last_revision(revision_id)
0.200.1680 by Jelmer Vernooij
Fix repo locks.
1212
        wt = GitWorkingTree(
0.308.1 by Jelmer Vernooij
Set revision id if specified to WorkingTreeFormat.initialize.
1213
                a_controldir, a_controldir.open_repository(), branch, index)
0.200.1680 by Jelmer Vernooij
Fix repo locks.
1214
        for hook in MutableTree.hooks['post_build_tree']:
1215
            hook(wt)
1216
        return wt
0.200.1096 by Jelmer Vernooij
Implement GitWorkingTreeFormat.initialize.
1217
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1218
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1219
class InterIndexGitTree(InterGitTrees):
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1220
    """InterTree that works between a Git revision tree and an index."""
1221
1222
    def __init__(self, source, target):
1223
        super(InterIndexGitTree, self).__init__(source, target)
1224
        self._index = target.index
1225
1226
    @classmethod
1227
    def is_compatible(cls, source, target):
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
1228
        from .repository import GitRevisionTree
0.200.1636 by Jelmer Vernooij
Some formatting fixes.
1229
        return (isinstance(source, GitRevisionTree) and
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1230
                isinstance(target, GitWorkingTree))
1231
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1232
    def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1233
            require_versioned=False, include_root=False):
1234
        # TODO(jelmer): Handle include_root
1235
        # TODO(jelmer): Handle require_versioned
1236
        # TODO(jelmer): Restrict to specific_files, for performance reasons.
1237
        with self.lock_read():
0.200.1754 by Jelmer Vernooij
Avoid updating index when just comparing trees.
1238
            return changes_between_git_tree_and_working_copy(
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1239
                self.source.store, self.source.tree,
1240
                self.target, want_unchanged=want_unchanged)
1241
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1242
    def compare(self, want_unchanged=False, specific_files=None,
1243
                extra_trees=None, require_versioned=False, include_root=False,
1244
                want_unversioned=False):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1245
        with self.lock_read():
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1246
            changes = self._iter_git_changes(
1247
                    want_unchanged=want_unchanged,
1248
                    specific_files=specific_files,
1249
                    require_versioned=require_versioned,
1250
                    include_root=include_root)
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1251
            source_fileid_map = self.source._fileid_map
1252
            target_fileid_map = self.target._fileid_map
1253
            ret = tree_delta_from_git_changes(changes, self.target.mapping,
1254
                (source_fileid_map, target_fileid_map),
0.287.6 by Jelmer Vernooij
Fix some more tests.
1255
                specific_files=specific_files, require_versioned=require_versioned,
1256
                include_root=include_root)
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1257
            if want_unversioned:
1258
                for e in self.target.extras():
0.200.1731 by Jelmer Vernooij
Add support for checking untracked changes.
1259
                    ret.unversioned.append(
0.200.1732 by Jelmer Vernooij
Fix ignore.
1260
                        (osutils.normalized_filename(e)[0], None,
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1261
                        osutils.file_kind(self.target.abspath(e))))
1262
            return ret
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1263
0.200.622 by Jelmer Vernooij
Implement InterTree.iter_changes() as well.
1264
    def iter_changes(self, include_unchanged=False, specific_files=None,
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1265
                     pb=None, extra_trees=[], require_versioned=True,
1266
                     want_unversioned=False):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1267
        with self.lock_read():
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1268
            changes = self._iter_git_changes(
1269
                    want_unchanged=include_unchanged,
1270
                    specific_files=specific_files,
1271
                    require_versioned=require_versioned)
0.200.1731 by Jelmer Vernooij
Add support for checking untracked changes.
1272
            if want_unversioned:
1273
                changes = itertools.chain(
1274
                        changes,
1275
                        untracked_changes(self.target))
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1276
            return changes_from_git_changes(
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1277
                    changes, self.target.mapping,
1278
                    specific_files=specific_files)
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1279
0.200.1179 by Jelmer Vernooij
Avoid using verifiers for natively imported revisions, save a lot of time.
1280
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1281
tree.InterTree.register_optimiser(InterIndexGitTree)
0.200.1529 by Jelmer Vernooij
Add changes_between_tree_and_index.
1282
1283
0.200.1731 by Jelmer Vernooij
Add support for checking untracked changes.
1284
def untracked_changes(tree):
1285
    for e in tree.extras():
1286
        ap = tree.abspath(e)
1287
        st = os.stat(ap)
1288
        try:
1289
            np, accessible  = osutils.normalized_filename(e)
1290
        except UnicodeDecodeError:
1291
            raise errors.BadFilenameEncoding(
1292
                e, osutils._fs_enc)
1293
        yield (np, st.st_mode,
1294
               blob_from_path_and_stat(ap, st).id)
1295
1296
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1297
def changes_between_git_tree_and_index(store, from_tree_sha, target,
0.200.1731 by Jelmer Vernooij
Add support for checking untracked changes.
1298
        want_unchanged=False, update_index=False):
0.200.1529 by Jelmer Vernooij
Add changes_between_tree_and_index.
1299
    """Determine the changes between a git tree and a working tree with index.
1300
1301
    """
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1302
    to_tree_sha = target.index.commit(store)
0.200.1754 by Jelmer Vernooij
Avoid updating index when just comparing trees.
1303
    return store.tree_changes(from_tree_sha, to_tree_sha, include_trees=True,
1304
            want_unchanged=want_unchanged)
1305
1306
1307
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1308
        want_unchanged=False, update_index=False):
1309
    """Determine the changes between a git tree and a working tree with index.
1310
1311
    """
1312
    blobs = iter_fresh_blobs(target.index, target.abspath('.').encode(sys.getfilesystemencoding()))
1313
    to_tree_sha = commit_tree(store, blobs)
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1314
    return store.tree_changes(from_tree_sha, to_tree_sha, include_trees=True,
1315
            want_unchanged=want_unchanged)