/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.323.1 by Jelmer Vernooij
Fix iter_changes of untracked changes.
39
    blob_from_path_and_stat,
0.200.1096 by Jelmer Vernooij
Implement GitWorkingTreeFormat.initialize.
40
    )
0.200.1202 by Jelmer Vernooij
Implement has_or_had_id.
41
from dulwich.object_store import (
42
    tree_lookup_path,
43
    )
0.200.383 by Jelmer Vernooij
Simplify, support rewriting index based on inventory.
44
from dulwich.objects import (
45
    Blob,
0.200.1538 by Jelmer Vernooij
More work on tree-reference support.
46
    S_IFGITLINK,
0.200.948 by Jelmer Vernooij
Cope with empty inventories.
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.336.2 by Jelmer Vernooij
Don't use ZERO_SHA outside of remote communication to indicate empty history.
668
        try:
669
            root_tree = self.store[head].tree
670
        except KeyError:
0.200.1205 by Jelmer Vernooij
Implement GitWorkingTree.stored_kind.
671
            return False
0.200.1202 by Jelmer Vernooij
Implement has_or_had_id.
672
        try:
673
            tree_lookup_path(self.store.__getitem__, root_tree, path)
674
        except KeyError:
675
            return False
676
        else:
677
            return True
678
0.200.1198 by Jelmer Vernooij
Implement GitWorkingTree.has_id.
679
    def has_id(self, file_id):
680
        try:
681
            self.id2path(file_id)
682
        except errors.NoSuchId:
683
            return False
684
        else:
685
            return True
686
0.264.1 by Jelmer Vernooij
Provide stubs using inventory for the moment.:
687
    def id2path(self, file_id):
0.200.1532 by Jelmer Vernooij
Cope with float timestamps.
688
        assert type(file_id) is str, "file id not a string: %r" % file_id
0.200.1411 by Jelmer Vernooij
Fix control files.
689
        file_id = osutils.safe_utf8(file_id)
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
690
        with self.lock_read():
0.200.1712 by Jelmer Vernooij
Add file_id prefix.
691
            try:
692
                path = self._fileid_map.lookup_path(file_id)
693
            except ValueError:
694
                raise errors.NoSuchId(self, file_id)
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
695
            path = path.decode('utf-8')
696
            if self.is_versioned(path):
697
                return path
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
698
            raise errors.NoSuchId(self, file_id)
0.264.1 by Jelmer Vernooij
Provide stubs using inventory for the moment.:
699
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
700
    def get_file_mtime(self, path, file_id=None):
0.200.1200 by Jelmer Vernooij
Support GitWorkingTree.get_file_mtime.
701
        """See Tree.get_file_mtime."""
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
702
        try:
703
            return os.lstat(self.abspath(path)).st_mtime
704
        except OSError, (num, msg):
705
            if num == errno.ENOENT:
706
                raise errors.NoSuchFile(path)
707
            raise
0.200.1200 by Jelmer Vernooij
Support GitWorkingTree.get_file_mtime.
708
0.200.1655 by Jelmer Vernooij
Basic support for git ignores.
709
    def is_ignored(self, filename):
710
        r"""Check whether the filename matches an ignore pattern.
711
712
        If the file is ignored, returns the pattern which caused it to
713
        be ignored, otherwise None.  So this can simply be used as a
714
        boolean if desired."""
715
        if getattr(self, '_global_ignoreglobster', None) is None:
716
            ignore_globs = set()
717
            ignore_globs.update(ignores.get_runtime_ignores())
718
            ignore_globs.update(ignores.get_user_ignores())
719
            self._global_ignoreglobster = globbing.ExceptionGlobster(ignore_globs)
0.200.1656 by Jelmer Vernooij
Report proper patterns, ignore files.
720
        match = self._global_ignoreglobster.match(filename)
721
        if match is not None:
722
            return match
0.200.1716 by Jelmer Vernooij
Fix some more tests.
723
        try:
724
            if self.kind(filename) == 'directory':
725
                filename += b'/'
726
        except errors.NoSuchFile:
727
            pass
728
        filename = filename.lstrip(b'/')
0.200.1658 by Jelmer Vernooij
Fix handling of ignores - return patterns that matched.
729
        ignore_manager = self._get_ignore_manager()
730
        ps = list(ignore_manager.find_matching(filename))
731
        if not ps:
732
            return None
733
        if not ps[-1].is_exclude:
734
            return None
735
        return bytes(ps[-1])
736
737
    def _get_ignore_manager(self):
738
        ignoremanager = getattr(self, '_ignoremanager', None)
739
        if ignoremanager is not None:
740
            return ignoremanager
741
742
        ignore_manager = IgnoreFilterManager.from_repo(self.repository._git)
743
        self._ignoremanager = ignore_manager
744
        return ignore_manager
0.200.409 by Jelmer Vernooij
Support parsing .gitignore.
745
0.200.1716 by Jelmer Vernooij
Fix some more tests.
746
    def _flush_ignore_list_cache(self):
747
        self._ignoremanager = None
748
0.200.508 by Jelmer Vernooij
Skip inventory caching bits.
749
    def set_last_revision(self, revid):
0.200.1720 by Jelmer Vernooij
Fix handling of pending merges.
750
        if _mod_revision.is_null(revid):
751
            self.branch.set_last_revision_info(0, revid)
752
            return False
753
        _mod_revision.check_not_reserved_id(revid)
754
        try:
755
            self.branch.generate_revision_history(revid)
756
        except errors.NoSuchRevision:
757
            raise errors.GhostRevisionUnusableHere(revid)
0.200.508 by Jelmer Vernooij
Skip inventory caching bits.
758
0.200.379 by Jelmer Vernooij
Re-enable working tree support.
759
    def _reset_data(self):
0.248.3 by Jelmer Vernooij
Handle working trees without valid HEAD branch.
760
        try:
761
            head = self.repository._git.head()
0.336.2 by Jelmer Vernooij
Don't use ZERO_SHA outside of remote communication to indicate empty history.
762
        except KeyError:
0.200.1202 by Jelmer Vernooij
Implement has_or_had_id.
763
            self._basis_fileid_map = GitFileIdMap({}, self.mapping)
0.200.948 by Jelmer Vernooij
Cope with empty inventories.
764
        else:
0.336.2 by Jelmer Vernooij
Don't use ZERO_SHA outside of remote communication to indicate empty history.
765
            self._basis_fileid_map = self.mapping.get_fileid_map(
766
                self.store.__getitem__, self.store[head].tree)
0.200.379 by Jelmer Vernooij
Re-enable working tree support.
767
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
768
    def get_file_verifier(self, path, file_id=None, stat_value=None):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
769
        with self.lock_read():
770
            try:
771
                return ("GIT", self.index[path][-2])
772
            except KeyError:
773
                if self._has_dir(path):
774
                    return ("GIT", None)
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
775
                raise errors.NoSuchFile(path)
0.200.1302 by Jelmer Vernooij
Significantly improve performance of WorkingTree.extras().
776
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
777
    def get_file_sha1(self, path, file_id=None, stat_value=None):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
778
        with self.lock_read():
0.200.1772 by Jelmer Vernooij
Fix handling of unversioned file in get_file_sha1.
779
            if not self.is_versioned(path):
780
                raise errors.NoSuchFile(path)
781
            abspath = self.abspath(path)
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
782
            try:
783
                return osutils.sha_file_by_name(abspath)
784
            except OSError, (num, msg):
785
                if num in (errno.EISDIR, errno.ENOENT):
0.200.1772 by Jelmer Vernooij
Fix handling of unversioned file in get_file_sha1.
786
                    return None
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
787
                raise
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
788
0.200.610 by Jelmer Vernooij
Support retrieving basis tree properly.
789
    def revision_tree(self, revid):
790
        return self.repository.revision_tree(revid)
791
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
792
    def is_versioned(self, path):
793
        with self.lock_read():
794
            path = path.rstrip('/').encode('utf-8')
795
            return (path in self.index or self._has_dir(path))
0.200.1242 by Jelmer Vernooij
Support directories better.
796
0.200.1239 by Jelmer Vernooij
Implement GitWorkingTree.filter_unversioned_files.
797
    def filter_unversioned_files(self, files):
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
798
        return set([p for p in files if not self.is_versioned(p)])
0.200.1239 by Jelmer Vernooij
Implement GitWorkingTree.filter_unversioned_files.
799
0.264.11 by Jelmer Vernooij
Completer implementation of iter_entries_by_dir and list_files.
800
    def _get_dir_ie(self, path, parent_id):
0.200.1192 by Jelmer Vernooij
Implement path2id.
801
        file_id = self.path2id(path)
0.264.11 by Jelmer Vernooij
Completer implementation of iter_entries_by_dir and list_files.
802
        return inventory.InventoryDirectory(file_id,
0.200.1190 by Jelmer Vernooij
Fix get_symlink_target call.
803
            posixpath.basename(path).strip("/"), parent_id)
0.264.11 by Jelmer Vernooij
Completer implementation of iter_entries_by_dir and list_files.
804
805
    def _add_missing_parent_ids(self, path, dir_ids):
806
        if path in dir_ids:
807
            return []
808
        parent = posixpath.dirname(path).strip("/")
809
        ret = self._add_missing_parent_ids(parent, dir_ids)
810
        parent_id = dir_ids[parent]
811
        ie = self._get_dir_ie(path, parent_id)
812
        dir_ids[path] = ie.file_id
813
        ret.append((path, ie))
814
        return ret
815
0.200.1321 by Jelmer Vernooij
More fixes for compatibility with bzr.dev testsuite.
816
    def _get_file_ie(self, name, path, value, parent_id):
817
        assert isinstance(name, unicode)
0.200.1192 by Jelmer Vernooij
Implement path2id.
818
        assert isinstance(path, unicode)
0.264.10 by Jelmer Vernooij
Yield inventory entries.
819
        assert isinstance(value, tuple) and len(value) == 10
820
        (ctime, mtime, dev, ino, mode, uid, gid, size, sha, flags) = value
0.200.1192 by Jelmer Vernooij
Implement path2id.
821
        file_id = self.path2id(path)
0.264.10 by Jelmer Vernooij
Yield inventory entries.
822
        if type(file_id) != str:
823
            raise AssertionError
824
        kind = mode_kind(mode)
0.200.1321 by Jelmer Vernooij
More fixes for compatibility with bzr.dev testsuite.
825
        ie = inventory.entry_factory[kind](file_id, name, parent_id)
0.264.10 by Jelmer Vernooij
Yield inventory entries.
826
        if kind == 'symlink':
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
827
            ie.symlink_target = self.get_symlink_target(path, file_id)
0.264.10 by Jelmer Vernooij
Yield inventory entries.
828
        else:
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
829
            data = self.get_file_text(path, file_id)
0.264.10 by Jelmer Vernooij
Yield inventory entries.
830
            ie.text_sha1 = osutils.sha_string(data)
831
            ie.text_size = len(data)
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
832
            ie.executable = self.is_executable(path, file_id)
0.264.10 by Jelmer Vernooij
Yield inventory entries.
833
        ie.revision = None
834
        return ie
835
0.264.11 by Jelmer Vernooij
Completer implementation of iter_entries_by_dir and list_files.
836
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
837
        mode = stat_result.st_mode
838
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
839
0.318.1 by Jelmer Vernooij
Fix executable test.
840
    def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
841
        return self.basis_tree().is_executable(path)
842
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
843
    def stored_kind(self, path, file_id=None):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
844
        with self.lock_read():
845
            try:
846
                return mode_kind(self.index[path.encode("utf-8")][4])
847
            except KeyError:
848
                # Maybe it's a directory?
849
                if self._has_dir(path):
850
                    return "directory"
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
851
                raise errors.NoSuchFile(path)
0.200.1205 by Jelmer Vernooij
Implement GitWorkingTree.stored_kind.
852
0.285.1 by Jelmer Vernooij
Swap arguments for tree methods.
853
    def is_executable(self, path, file_id=None):
0.200.1539 by Jelmer Vernooij
Cope with new is_executable.
854
        if getattr(self, "_supports_executable", osutils.supports_executable)():
855
            mode = os.lstat(self.abspath(path)).st_mode
856
        else:
0.319.1 by Jelmer Vernooij
Support falling back on basis for executable bits.
857
            try:
858
                mode = self.index[path.encode('utf-8')].mode
859
            except KeyError:
860
                mode = 0
861
        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.
862
0.200.1539 by Jelmer Vernooij
Cope with new is_executable.
863
    def _is_executable_from_path_and_stat(self, path, stat_result):
864
        if getattr(self, "_supports_executable", osutils.supports_executable)():
865
            return self._is_executable_from_path_and_stat_from_stat(path, stat_result)
866
        else:
867
            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.
868
0.264.10 by Jelmer Vernooij
Yield inventory entries.
869
    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.
870
        if from_dir is None:
871
            from_dir = ""
0.264.11 by Jelmer Vernooij
Completer implementation of iter_entries_by_dir and list_files.
872
        dir_ids = {}
0.200.1767 by Jelmer Vernooij
Fix references to Tree*.
873
        fk_entries = {'directory': tree.TreeDirectory,
874
                      'file': tree.TreeFile,
875
                      'symlink': tree.TreeLink}
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
876
        with self.lock_read():
877
            root_ie = self._get_dir_ie(u"", None)
878
            if include_root and not from_dir:
879
                yield "", "V", root_ie.kind, root_ie.file_id, root_ie
880
            dir_ids[u""] = root_ie.file_id
881
            if recursive:
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
882
                path_iterator = sorted(self._iter_files_recursive(from_dir, include_dirs=True))
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
883
            else:
884
                if from_dir is None:
885
                    start = self.basedir
886
                else:
887
                    start = os.path.join(self.basedir, from_dir)
888
                path_iterator = sorted([os.path.join(from_dir, name) for name in
889
                    os.listdir(start) if not self.controldir.is_control_filename(name)
890
                    and not self.mapping.is_special_file(name)])
891
            for path in path_iterator:
892
                try:
893
                    value = self.index[path]
894
                except KeyError:
895
                    value = None
896
                path = path.decode("utf-8")
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
897
                kind = osutils.file_kind(self.abspath(path))
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
898
                parent, name = posixpath.split(path)
899
                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.
900
                    pass
901
                if kind == 'directory':
902
                    if path != from_dir:
903
                        if self._has_dir(path):
904
                            ie = self._get_dir_ie(path, self.path2id(path))
905
                            status = "V"
906
                            file_id = ie.file_id
907
                        elif self.is_ignored(path):
908
                            status = "I"
909
                            ie = fk_entries[kind]()
910
                            file_id = None
911
                        else:
912
                            status = "?"
913
                            ie = fk_entries[kind]()
914
                            file_id = None
915
                        yield posixpath.relpath(path, from_dir), status, kind, file_id, ie
916
                    continue
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
917
                if value is not None:
918
                    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.
919
                    yield posixpath.relpath(path, from_dir), "V", ie.kind, ie.file_id, ie
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
920
                else:
921
                    ie = fk_entries[kind]()
0.200.1766 by Jelmer Vernooij
Fix another list_files test, integrate is_versioned.
922
                    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.
923
0.200.1206 by Jelmer Vernooij
Implement GitWorkingTree.all_file_ids.
924
    def all_file_ids(self):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
925
        with self.lock_read():
926
            ids = {u"": self.path2id("")}
927
            for path in self.index:
928
                if self.mapping.is_special_file(path):
929
                    continue
930
                path = path.decode("utf-8")
931
                parent = posixpath.dirname(path).strip("/")
932
                for e in self._add_missing_parent_ids(parent, ids):
933
                    pass
934
                ids[path] = self.path2id(path)
935
            return set(ids.values())
0.200.1206 by Jelmer Vernooij
Implement GitWorkingTree.all_file_ids.
936
0.200.1710 by Jelmer Vernooij
Regenerate xfail.
937
    def all_versioned_paths(self):
938
        with self.lock_read():
939
            paths = {u""}
940
            for path in self.index:
941
                if self.mapping.is_special_file(path):
942
                    continue
943
                path = path.decode("utf-8")
944
                paths.add(path)
945
                while path != "":
946
                    path = posixpath.dirname(path).strip("/")
947
                    if path in paths:
948
                        break
949
                    paths.add(path)
950
            return paths
951
0.200.1374 by Jelmer Vernooij
Implement GitWorkingTree._directory_is_tree_reference.
952
    def _directory_is_tree_reference(self, path):
953
        # FIXME: Check .gitsubmodules for path
954
        return False
955
0.200.1716 by Jelmer Vernooij
Fix some more tests.
956
    def iter_child_entries(self, path, file_id=None):
957
        encoded_path = path.encode('utf-8')
0.200.1739 by Jelmer Vernooij
Fix iteration order for iter_child_entries.
958
        parent_id = self.path2id(path)
0.200.1738 by Jelmer Vernooij
Fix test_does_not_exist.
959
        found_any = False
0.200.1739 by Jelmer Vernooij
Fix iteration order for iter_child_entries.
960
        seen_children = set()
0.200.1716 by Jelmer Vernooij
Fix some more tests.
961
        for item_path, value in self.index.iteritems():
962
            if self.mapping.is_special_file(item_path):
963
                continue
0.200.1739 by Jelmer Vernooij
Fix iteration order for iter_child_entries.
964
            if not osutils.is_inside(encoded_path, item_path):
0.200.1716 by Jelmer Vernooij
Fix some more tests.
965
                continue
0.200.1738 by Jelmer Vernooij
Fix test_does_not_exist.
966
            found_any = True
0.200.1739 by Jelmer Vernooij
Fix iteration order for iter_child_entries.
967
            subpath = posixpath.relpath(item_path, encoded_path)
0.200.1716 by Jelmer Vernooij
Fix some more tests.
968
            if b'/' in subpath:
0.200.1739 by Jelmer Vernooij
Fix iteration order for iter_child_entries.
969
                dirname = subpath.split(b'/', 1)[0]
970
                file_ie = self._get_dir_ie(posixpath.join(path, dirname), parent_id)
971
            else:
972
                (parent, name) = posixpath.split(item_path)
973
                try:
974
                    file_ie = self._get_file_ie(name, item_path, value, parent_id)
975
                except IOError:
976
                    continue
0.200.1716 by Jelmer Vernooij
Fix some more tests.
977
            yield file_ie
0.200.1738 by Jelmer Vernooij
Fix test_does_not_exist.
978
        if not found_any:
979
            raise errors.NoSuchFile(path)
0.200.1716 by Jelmer Vernooij
Fix some more tests.
980
0.264.9 by Jelmer Vernooij
Implement basic GitWorkingTree.iter_entries_by_dir.
981
    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.
982
        if yield_parents:
983
            raise NotImplementedError(self.iter_entries_by_dir)
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
984
        with self.lock_read():
985
            if specific_file_ids is not None:
0.200.1712 by Jelmer Vernooij
Add file_id prefix.
986
                specific_paths = []
987
                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.
988
                    if file_id is None:
989
                        continue
0.309.1 by Jelmer Vernooij
Allow file-ids to Tree.iter_entries_by_dir to be absent.
990
                    try:
991
                        specific_paths.append(self.id2path(file_id))
992
                    except errors.NoSuchId:
993
                        pass
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
994
                if specific_paths in ([u""], []):
995
                    specific_paths = None
996
                else:
997
                    specific_paths = set(specific_paths)
998
            else:
0.200.1252 by Jelmer Vernooij
Support specific_file_ids in GitWorkingTree.iter_entries_by_dir.
999
                specific_paths = None
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1000
            root_ie = self._get_dir_ie(u"", None)
0.200.1740 by Jelmer Vernooij
Fix iter_entries_by_dir order.
1001
            ret = {}
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1002
            if specific_paths is None:
0.200.1740 by Jelmer Vernooij
Fix iter_entries_by_dir order.
1003
                ret[(None, u"")] = root_ie
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1004
            dir_ids = {u"": root_ie.file_id}
1005
            for path, value in self.index.iteritems():
1006
                if self.mapping.is_special_file(path):
1007
                    continue
1008
                path = path.decode("utf-8")
1009
                if specific_paths is not None and not path in specific_paths:
1010
                    continue
1011
                (parent, name) = posixpath.split(path)
1012
                try:
1013
                    file_ie = self._get_file_ie(name, path, value, None)
0.319.1 by Jelmer Vernooij
Support falling back on basis for executable bits.
1014
                except errors.NoSuchFile:
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1015
                    continue
0.200.1730 by Jelmer Vernooij
Fix test_is_executable_dir.
1016
                if yield_parents or specific_file_ids is None:
1017
                    for (dir_path, dir_ie) in self._add_missing_parent_ids(parent,
1018
                            dir_ids):
0.200.1740 by Jelmer Vernooij
Fix iter_entries_by_dir order.
1019
                        ret[(posixpath.dirname(dir_path), dir_path)] = dir_ie
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1020
                file_ie.parent_id = self.path2id(parent)
0.200.1740 by Jelmer Vernooij
Fix iter_entries_by_dir order.
1021
                ret[(posixpath.dirname(path), path)] = file_ie
1022
            return ((path, ie) for ((_, path), ie) in sorted(ret.items()))
0.264.9 by Jelmer Vernooij
Implement basic GitWorkingTree.iter_entries_by_dir.
1023
0.200.619 by Jelmer Vernooij
Provide dummy WorkingTree.conflicts() implementation rather than spending a lot of time not finding any conflicts.
1024
    def conflicts(self):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1025
        with self.lock_read():
1026
            # FIXME:
1027
            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.
1028
0.200.1705 by Jelmer Vernooij
Fix walkdirs.
1029
    def walkdirs(self, prefix=""):
0.324.1 by Jelmer Vernooij
initial work fixing walkdirs.
1030
        """Walk the directories of this tree.
1031
1032
        returns a generator which yields items in the form:
1033
                ((curren_directory_path, fileid),
1034
                 [(file1_path, file1_name, file1_kind, (lstat), file1_id,
1035
                   file1_kind), ... ])
1036
1037
        This API returns a generator, which is only valid during the current
1038
        tree transaction - within a single lock_read or lock_write duration.
1039
1040
        If the tree is not locked, it may cause an error to be raised,
1041
        depending on the tree implementation.
1042
        """
1043
        from bisect import bisect_left
1044
        import operator
1045
        disk_top = self.abspath(prefix)
1046
        if disk_top.endswith('/'):
1047
            disk_top = disk_top[:-1]
1048
        top_strip_len = len(disk_top) + 1
1049
        inventory_iterator = self._walkdirs(prefix)
1050
        disk_iterator = osutils.walkdirs(disk_top, prefix)
1051
        try:
1052
            current_disk = next(disk_iterator)
1053
            disk_finished = False
1054
        except OSError as e:
1055
            if not (e.errno == errno.ENOENT or
1056
                (sys.platform == 'win32' and e.errno == ERROR_PATH_NOT_FOUND)):
1057
                raise
1058
            current_disk = None
1059
            disk_finished = True
1060
        try:
1061
            current_inv = next(inventory_iterator)
1062
            inv_finished = False
1063
        except StopIteration:
1064
            current_inv = None
1065
            inv_finished = True
1066
        while not inv_finished or not disk_finished:
1067
            if current_disk:
1068
                ((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
1069
                    cur_disk_dir_content) = current_disk
1070
            else:
1071
                ((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
1072
                    cur_disk_dir_content) = ((None, None), None)
1073
            if not disk_finished:
1074
                # strip out .bzr dirs
1075
                if (cur_disk_dir_path_from_top[top_strip_len:] == '' and
1076
                    len(cur_disk_dir_content) > 0):
1077
                    # osutils.walkdirs can be made nicer -
1078
                    # yield the path-from-prefix rather than the pathjoined
1079
                    # value.
1080
                    bzrdir_loc = bisect_left(cur_disk_dir_content,
1081
                        ('.git', '.git'))
1082
                    if (bzrdir_loc < len(cur_disk_dir_content)
1083
                        and self.controldir.is_control_filename(
1084
                            cur_disk_dir_content[bzrdir_loc][0])):
1085
                        # we dont yield the contents of, or, .bzr itself.
1086
                        del cur_disk_dir_content[bzrdir_loc]
1087
            if inv_finished:
1088
                # everything is unknown
1089
                direction = 1
1090
            elif disk_finished:
1091
                # everything is missing
1092
                direction = -1
1093
            else:
1094
                direction = cmp(current_inv[0][0], cur_disk_dir_relpath)
1095
            if direction > 0:
1096
                # disk is before inventory - unknown
1097
                dirblock = [(relpath, basename, kind, stat, None, None) for
1098
                    relpath, basename, kind, stat, top_path in
1099
                    cur_disk_dir_content]
1100
                yield (cur_disk_dir_relpath, None), dirblock
1101
                try:
1102
                    current_disk = next(disk_iterator)
1103
                except StopIteration:
1104
                    disk_finished = True
1105
            elif direction < 0:
1106
                # inventory is before disk - missing.
1107
                dirblock = [(relpath, basename, 'unknown', None, fileid, kind)
1108
                    for relpath, basename, dkind, stat, fileid, kind in
1109
                    current_inv[1]]
1110
                yield (current_inv[0][0], current_inv[0][1]), dirblock
1111
                try:
1112
                    current_inv = next(inventory_iterator)
1113
                except StopIteration:
1114
                    inv_finished = True
1115
            else:
1116
                # versioned present directory
1117
                # merge the inventory and disk data together
1118
                dirblock = []
1119
                for relpath, subiterator in itertools.groupby(sorted(
1120
                    current_inv[1] + cur_disk_dir_content,
1121
                    key=operator.itemgetter(0)), operator.itemgetter(1)):
1122
                    path_elements = list(subiterator)
1123
                    if len(path_elements) == 2:
1124
                        inv_row, disk_row = path_elements
1125
                        # versioned, present file
1126
                        dirblock.append((inv_row[0],
1127
                            inv_row[1], disk_row[2],
1128
                            disk_row[3], inv_row[4],
1129
                            inv_row[5]))
1130
                    elif len(path_elements[0]) == 5:
1131
                        # unknown disk file
1132
                        dirblock.append((path_elements[0][0],
1133
                            path_elements[0][1], path_elements[0][2],
1134
                            path_elements[0][3], None, None))
1135
                    elif len(path_elements[0]) == 6:
1136
                        # versioned, absent file.
1137
                        dirblock.append((path_elements[0][0],
1138
                            path_elements[0][1], 'unknown', None,
1139
                            path_elements[0][4], path_elements[0][5]))
1140
                    else:
1141
                        raise NotImplementedError('unreachable code')
1142
                yield current_inv[0], dirblock
1143
                try:
1144
                    current_inv = next(inventory_iterator)
1145
                except StopIteration:
1146
                    inv_finished = True
1147
                try:
1148
                    current_disk = next(disk_iterator)
1149
                except StopIteration:
1150
                    disk_finished = True
1151
1152
    def _walkdirs(self, prefix=""):
0.200.1210 by Jelmer Vernooij
Implement GitWorkingTree._walkdirs.
1153
        if prefix != "":
1154
            prefix += "/"
1155
        per_dir = defaultdict(list)
0.325.2 by Jelmer Vernooij
Handle root in walkdirs.
1156
        if prefix == "":
1157
            per_dir[('', self.get_root_id())] = []
0.200.1210 by Jelmer Vernooij
Implement GitWorkingTree._walkdirs.
1158
        for path, value in self.index.iteritems():
0.200.1328 by Jelmer Vernooij
More test fixes.
1159
            if self.mapping.is_special_file(path):
1160
                continue
0.200.1210 by Jelmer Vernooij
Implement GitWorkingTree._walkdirs.
1161
            if not path.startswith(prefix):
1162
                continue
1163
            (dirname, child_name) = posixpath.split(path)
1164
            dirname = dirname.decode("utf-8")
1165
            dir_file_id = self.path2id(dirname)
1166
            assert isinstance(value, tuple) and len(value) == 10
1167
            per_dir[(dirname, dir_file_id)].append(
1168
                (path.decode("utf-8"), child_name.decode("utf-8"),
0.324.1 by Jelmer Vernooij
initial work fixing walkdirs.
1169
                mode_kind(value.mode), None,
0.200.1210 by Jelmer Vernooij
Implement GitWorkingTree._walkdirs.
1170
                self.path2id(path.decode("utf-8")),
0.293.1 by Jelmer Vernooij
Fix walkdirs handling of unknown entries, mode.
1171
                mode_kind(value.mode)))
0.324.1 by Jelmer Vernooij
initial work fixing walkdirs.
1172
        return ((k, sorted(v)) for (k, v) in per_dir.iteritems())
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
1173
0.200.1542 by Jelmer Vernooij
Refactor iter_changes.
1174
    def _lookup_entry(self, path, update_index=False):
0.200.1543 by Jelmer Vernooij
Support symlinks.
1175
        assert type(path) == str
0.200.1542 by Jelmer Vernooij
Refactor iter_changes.
1176
        entry = self.index[path]
1177
        index_mode = entry[-6]
1178
        index_sha = entry[-2]
0.200.1741 by Jelmer Vernooij
Fix opentree tests.
1179
        disk_path = self.abspath(path.decode('utf-8')).encode(
1180
            osutils._fs_enc)
0.284.1 by Jelmer Vernooij
Raise KeyError when file was removed.
1181
        try:
1182
            disk_stat = os.lstat(disk_path)
1183
        except OSError, (num, msg):
1184
            if num in (errno.EISDIR, errno.ENOENT):
1185
                raise KeyError(path)
1186
            raise
0.200.1542 by Jelmer Vernooij
Refactor iter_changes.
1187
        disk_mtime = disk_stat.st_mtime
1188
        if isinstance(entry[1], tuple):
1189
            index_mtime = entry[1][0]
1190
        else:
1191
            index_mtime = int(entry[1])
1192
        mtime_delta = (disk_mtime - index_mtime)
1193
        disk_mode = cleanup_mode(disk_stat.st_mode)
1194
        if mtime_delta > 0 or disk_mode != index_mode:
1195
            if stat.S_ISDIR(disk_mode):
1196
                try:
1197
                    subrepo = Repo(disk_path)
1198
                except NotGitRepository:
1199
                    return (None, None)
1200
                else:
1201
                    disk_mode = S_IFGITLINK
1202
                    git_id = subrepo.head()
0.200.1543 by Jelmer Vernooij
Support symlinks.
1203
            elif stat.S_ISLNK(disk_mode):
0.200.1715 by Jelmer Vernooij
Fix some more tests.
1204
                blob = Blob.from_string(os.readlink(disk_path))
0.200.1543 by Jelmer Vernooij
Support symlinks.
1205
                git_id = blob.id
1206
            elif stat.S_ISREG(disk_mode):
0.200.1542 by Jelmer Vernooij
Refactor iter_changes.
1207
                with open(disk_path, 'r') as f:
1208
                    blob = Blob.from_string(f.read())
1209
                git_id = blob.id
0.200.1543 by Jelmer Vernooij
Support symlinks.
1210
            else:
1211
                raise AssertionError
0.200.1542 by Jelmer Vernooij
Refactor iter_changes.
1212
            if update_index:
1213
                flags = 0 # FIXME
0.200.1545 by Jelmer Vernooij
Some more test fixes.
1214
                self.index[path] = index_entry_from_stat(disk_stat, git_id, flags, disk_mode)
0.200.1542 by Jelmer Vernooij
Refactor iter_changes.
1215
            return (git_id, disk_mode)
1216
        return (index_sha, index_mode)
1217
0.200.1677 by Jelmer Vernooij
Mark shelving as unsupported.
1218
    def get_shelf_manager(self):
0.200.1729 by Jelmer Vernooij
ShelvingUnsupported doesn't take an argument.
1219
        raise workingtree.ShelvingUnsupported()
0.200.1677 by Jelmer Vernooij
Mark shelving as unsupported.
1220
0.200.1678 by Jelmer Vernooij
Fix tests.
1221
    def store_uncommitted(self):
1222
        raise errors.StoringUncommittedNotSupported(self)
1223
0.200.1703 by Jelmer Vernooij
Implement apply_inventory_delta.
1224
    def apply_inventory_delta(self, changes):
1225
        for (old_path, new_path, file_id, ie) in changes:
1226
            if old_path is not None:
1227
                del self.index[old_path.encode('utf-8')]
0.200.1772 by Jelmer Vernooij
Fix handling of unversioned file in get_file_sha1.
1228
                self._versioned_dirs = None
0.200.1703 by Jelmer Vernooij
Implement apply_inventory_delta.
1229
            if new_path is not None and ie.kind != 'directory':
1230
                self._index_add_entry(new_path, ie.kind)
0.316.2 by Jelmer Vernooij
Flush after modifying index.
1231
        self.flush()
0.200.1703 by Jelmer Vernooij
Implement apply_inventory_delta.
1232
0.200.1756 by Jelmer Vernooij
Initial work on annotate support.
1233
    def annotate_iter(self, path, file_id=None,
1234
                      default_revision=_mod_revision.CURRENT_REVISION):
1235
        """See Tree.annotate_iter
1236
1237
        This implementation will use the basis tree implementation if possible.
1238
        Lines not in the basis are attributed to CURRENT_REVISION
1239
1240
        If there are pending merges, lines added by those merges will be
1241
        incorrectly attributed to CURRENT_REVISION (but after committing, the
1242
        attribution will be correct).
1243
        """
1244
        with self.lock_read():
1245
            maybe_file_parent_keys = []
1246
            for parent_id in self.get_parent_ids():
1247
                try:
1248
                    parent_tree = self.revision_tree(parent_id)
1249
                except errors.NoSuchRevisionInTree:
1250
                    parent_tree = self.branch.repository.revision_tree(
1251
                            parent_id)
1252
                with parent_tree.lock_read():
1253
                    # TODO(jelmer): Use rename/copy tracker to find path name in parent
1254
                    parent_path = path
1255
                    try:
1256
                        kind = parent_tree.kind(parent_path)
1257
                    except errors.NoSuchFile:
1258
                        continue
1259
                    if kind != 'file':
1260
                        # Note: this is slightly unnecessary, because symlinks and
1261
                        # directories have a "text" which is the empty text, and we
1262
                        # know that won't mess up annotations. But it seems cleaner
1263
                        continue
1264
                    parent_text_key = (
1265
                        parent_path,
1266
                        parent_tree.get_file_revision(parent_path))
1267
                    if parent_text_key not in maybe_file_parent_keys:
1268
                        maybe_file_parent_keys.append(parent_text_key)
1269
            graph = self.branch.repository.get_file_graph()
1270
            heads = graph.heads(maybe_file_parent_keys)
1271
            file_parent_keys = []
1272
            for key in maybe_file_parent_keys:
1273
                if key in heads:
1274
                    file_parent_keys.append(key)
1275
1276
            # Now we have the parents of this content
1277
            from breezy.annotate import Annotator
1278
            from .annotate import AnnotateProvider
1279
            annotator = Annotator(AnnotateProvider(
1280
                self.branch.repository._file_change_scanner))
1281
            text = self.get_file_text(path)
1282
            this_key = (path, default_revision)
1283
            annotator.add_special_text(this_key, file_parent_keys, text)
1284
            annotations = [(key[-1], line)
1285
                           for key, line in annotator.annotate_flat(this_key)]
1286
            return annotations
1287
0.200.1308 by Jelmer Vernooij
Write index to disk after adding files.
1288
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
1289
class GitWorkingTreeFormat(workingtree.WorkingTreeFormat):
1290
0.200.1206 by Jelmer Vernooij
Implement GitWorkingTree.all_file_ids.
1291
    _tree_class = GitWorkingTree
1292
0.200.1295 by Jelmer Vernooij
Mark working trees as not supporting directories.
1293
    supports_versioned_directories = False
1294
0.200.1661 by Jelmer Vernooij
Set supports_setting_file_ids to False.
1295
    supports_setting_file_ids = False
1296
0.200.1677 by Jelmer Vernooij
Mark shelving as unsupported.
1297
    supports_store_uncommitted = False
1298
0.200.1723 by Jelmer Vernooij
Set supports_leftmost_parent_id_as_ghost property.
1299
    supports_leftmost_parent_id_as_ghost = False
1300
0.200.1779 by Jelmer Vernooij
Actually store git revision ids rather than bzr revision ids.
1301
    supports_righthand_parent_id_as_ghost = False
1302
0.200.1768 by Jelmer Vernooij
Fix handling of normalized filenames.
1303
    requires_normalized_unicode_filenames = True
1304
0.200.656 by Jelmer Vernooij
Implement GitWorkingTreeFormat._matchingbzrdir.
1305
    @property
0.200.1665 by Jelmer Vernooij
Rename _matchingbzrdir to _matchingcnotroldir.
1306
    def _matchingcontroldir(self):
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
1307
        from .dir import LocalGitControlDirFormat
0.200.1013 by Jelmer Vernooij
More renames.
1308
        return LocalGitControlDirFormat()
0.200.656 by Jelmer Vernooij
Implement GitWorkingTreeFormat._matchingbzrdir.
1309
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
1310
    def get_format_description(self):
1311
        return "Git Working Tree"
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1312
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
1313
    def initialize(self, a_controldir, revision_id=None, from_branch=None,
0.200.1096 by Jelmer Vernooij
Implement GitWorkingTreeFormat.initialize.
1314
                   accelerator_tree=None, hardlink=False):
1315
        """See WorkingTreeFormat.initialize()."""
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
1316
        if not isinstance(a_controldir, LocalGitDir):
1317
            raise errors.IncompatibleFormat(self, a_controldir)
1318
        index = Index(a_controldir.root_transport.local_abspath(".git/index"))
0.200.1096 by Jelmer Vernooij
Implement GitWorkingTreeFormat.initialize.
1319
        index.write()
0.308.1 by Jelmer Vernooij
Set revision id if specified to WorkingTreeFormat.initialize.
1320
        branch = a_controldir.open_branch()
1321
        if revision_id is not None:
1322
            branch.set_last_revision(revision_id)
0.200.1680 by Jelmer Vernooij
Fix repo locks.
1323
        wt = GitWorkingTree(
0.308.1 by Jelmer Vernooij
Set revision id if specified to WorkingTreeFormat.initialize.
1324
                a_controldir, a_controldir.open_repository(), branch, index)
0.200.1680 by Jelmer Vernooij
Fix repo locks.
1325
        for hook in MutableTree.hooks['post_build_tree']:
1326
            hook(wt)
1327
        return wt
0.200.1096 by Jelmer Vernooij
Implement GitWorkingTreeFormat.initialize.
1328
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1329
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1330
class InterIndexGitTree(InterGitTrees):
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1331
    """InterTree that works between a Git revision tree and an index."""
1332
1333
    def __init__(self, source, target):
1334
        super(InterIndexGitTree, self).__init__(source, target)
1335
        self._index = target.index
1336
1337
    @classmethod
1338
    def is_compatible(cls, source, target):
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
1339
        from .repository import GitRevisionTree
0.200.1636 by Jelmer Vernooij
Some formatting fixes.
1340
        return (isinstance(source, GitRevisionTree) and
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1341
                isinstance(target, GitWorkingTree))
1342
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1343
    def _iter_git_changes(self, want_unchanged=False, specific_files=None,
1344
            require_versioned=False, include_root=False):
1345
        # TODO(jelmer): Handle include_root
1346
        # TODO(jelmer): Handle require_versioned
1347
        # TODO(jelmer): Restrict to specific_files, for performance reasons.
1348
        with self.lock_read():
0.200.1754 by Jelmer Vernooij
Avoid updating index when just comparing trees.
1349
            return changes_between_git_tree_and_working_copy(
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1350
                self.source.store, self.source.tree,
1351
                self.target, want_unchanged=want_unchanged)
1352
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1353
    def compare(self, want_unchanged=False, specific_files=None,
1354
                extra_trees=None, require_versioned=False, include_root=False,
1355
                want_unversioned=False):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1356
        with self.lock_read():
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1357
            changes = self._iter_git_changes(
1358
                    want_unchanged=want_unchanged,
1359
                    specific_files=specific_files,
1360
                    require_versioned=require_versioned,
1361
                    include_root=include_root)
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1362
            source_fileid_map = self.source._fileid_map
1363
            target_fileid_map = self.target._fileid_map
1364
            ret = tree_delta_from_git_changes(changes, self.target.mapping,
1365
                (source_fileid_map, target_fileid_map),
0.287.6 by Jelmer Vernooij
Fix some more tests.
1366
                specific_files=specific_files, require_versioned=require_versioned,
1367
                include_root=include_root)
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1368
            if want_unversioned:
1369
                for e in self.target.extras():
0.200.1731 by Jelmer Vernooij
Add support for checking untracked changes.
1370
                    ret.unversioned.append(
0.200.1732 by Jelmer Vernooij
Fix ignore.
1371
                        (osutils.normalized_filename(e)[0], None,
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1372
                        osutils.file_kind(self.target.abspath(e))))
1373
            return ret
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1374
0.200.622 by Jelmer Vernooij
Implement InterTree.iter_changes() as well.
1375
    def iter_changes(self, include_unchanged=False, specific_files=None,
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1376
                     pb=None, extra_trees=[], require_versioned=True,
1377
                     want_unversioned=False):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1378
        with self.lock_read():
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1379
            changes = self._iter_git_changes(
1380
                    want_unchanged=include_unchanged,
1381
                    specific_files=specific_files,
1382
                    require_versioned=require_versioned)
0.200.1731 by Jelmer Vernooij
Add support for checking untracked changes.
1383
            if want_unversioned:
1384
                changes = itertools.chain(
1385
                        changes,
1386
                        untracked_changes(self.target))
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
1387
            return changes_from_git_changes(
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1388
                    changes, self.target.mapping,
1389
                    specific_files=specific_files)
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1390
0.200.1179 by Jelmer Vernooij
Avoid using verifiers for natively imported revisions, save a lot of time.
1391
0.200.616 by Jelmer Vernooij
Provide custom intertree implementation for GitRevisionTree->GitWorkingTree.
1392
tree.InterTree.register_optimiser(InterIndexGitTree)
0.200.1529 by Jelmer Vernooij
Add changes_between_tree_and_index.
1393
1394
0.200.1731 by Jelmer Vernooij
Add support for checking untracked changes.
1395
def untracked_changes(tree):
1396
    for e in tree.extras():
1397
        ap = tree.abspath(e)
1398
        st = os.stat(ap)
1399
        try:
1400
            np, accessible  = osutils.normalized_filename(e)
1401
        except UnicodeDecodeError:
1402
            raise errors.BadFilenameEncoding(
1403
                e, osutils._fs_enc)
0.323.1 by Jelmer Vernooij
Fix iter_changes of untracked changes.
1404
        yield ((None, np), (None, st.st_mode),
1405
               (None, blob_from_path_and_stat(ap.encode('utf-8'), st).id))
0.200.1731 by Jelmer Vernooij
Add support for checking untracked changes.
1406
1407
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1408
def changes_between_git_tree_and_index(store, from_tree_sha, target,
0.200.1731 by Jelmer Vernooij
Add support for checking untracked changes.
1409
        want_unchanged=False, update_index=False):
0.200.1529 by Jelmer Vernooij
Add changes_between_tree_and_index.
1410
    """Determine the changes between a git tree and a working tree with index.
1411
1412
    """
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1413
    to_tree_sha = target.index.commit(store)
0.200.1754 by Jelmer Vernooij
Avoid updating index when just comparing trees.
1414
    return store.tree_changes(from_tree_sha, to_tree_sha, include_trees=True,
0.339.2 by Jelmer Vernooij
Use change_type_same in workingtree.
1415
            want_unchanged=want_unchanged, change_type_same=True)
0.200.1754 by Jelmer Vernooij
Avoid updating index when just comparing trees.
1416
1417
1418
def changes_between_git_tree_and_working_copy(store, from_tree_sha, target,
1419
        want_unchanged=False, update_index=False):
1420
    """Determine the changes between a git tree and a working tree with index.
1421
1422
    """
1423
    blobs = iter_fresh_blobs(target.index, target.abspath('.').encode(sys.getfilesystemencoding()))
1424
    to_tree_sha = commit_tree(store, blobs)
0.287.3 by Jelmer Vernooij
Some improvements to changes iterator.
1425
    return store.tree_changes(from_tree_sha, to_tree_sha, include_trees=True,
0.339.2 by Jelmer Vernooij
Use change_type_same in workingtree.
1426
            want_unchanged=want_unchanged, change_type_same=True)