/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5630.2.2 by John Arbash Meinel
Start fleshing out the design. Something weird is causing my tests to all fail.
1
# Copyright (C) 2005-2011 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
453 by Martin Pool
- Split WorkingTree into its own file
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
453 by Martin Pool
- Split WorkingTree into its own file
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
453 by Martin Pool
- Split WorkingTree into its own file
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
453 by Martin Pool
- Split WorkingTree into its own file
16
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
17
"""WorkingTree object and friends.
18
19
A WorkingTree represents the editable working copy of a branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
20
Operations which represent the WorkingTree are also done here,
21
such as renaming or adding files.  The WorkingTree has an inventory
22
which is updated by these operations.  A commit produces a
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
23
new revision based on the workingtree and its inventory.
24
25
At the moment every WorkingTree has its own branch.  Remote
26
WorkingTrees aren't supported.
27
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
28
To get a WorkingTree, call bzrdir.open_workingtree() or
29
WorkingTree.open(dir).
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
30
"""
31
6379.6.7 by Jelmer Vernooij
Move importing from future until after doc string, otherwise the doc string will disappear.
32
from __future__ import absolute_import
956 by Martin Pool
doc
33
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
34
import errno
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
35
import os
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
36
import re
2423.2.1 by Alexander Belchenko
Fix for walkdirs in missing dir with Py2.4 @ win32
37
import sys
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
38
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
39
import breezy
40
41
from .lazy_import import lazy_import
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
42
lazy_import(globals(), """
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
43
from bisect import bisect_left
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
44
import collections
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
45
import itertools
46
import operator
1398 by Robert Collins
integrate in Gustavos x-bit patch
47
import stat
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
48
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
49
from breezy import (
1731.2.17 by Aaron Bentley
Support extracting with checkouts
50
    branch,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
51
    conflicts as _mod_conflicts,
5363.2.10 by Jelmer Vernooij
base ControlDir on ControlComponent.
52
    controldir,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
53
    errors,
5745.3.2 by Jelmer Vernooij
Add filters to import tariff blacklist.
54
    filters as _mod_filters,
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
55
    generate_ids,
2135.2.7 by Kent Gibson
Implement JAM's review suggestions.
56
    globbing,
4454.3.67 by John Arbash Meinel
Implement RevisionTree.annotate_iter and WT.annotate_iter
57
    graph as _mod_graph,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
58
    ignores,
4496.3.4 by Andrew Bennetts
Tidy up unused and redundant imports in workingtree.py.
59
    inventory,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
60
    merge,
2598.5.1 by Aaron Bentley
Start eliminating the use of None to indicate null revision
61
    revision as _mod_revision,
1908.11.5 by John Arbash Meinel
[merge] bzr.dev 2240
62
    revisiontree,
5753.2.2 by Jelmer Vernooij
Remove some unnecessary imports, clean up lazy imports.
63
    rio as _mod_rio,
6538.1.5 by Aaron Bentley
Implement WorkingTree.store_uncommitted.
64
    shelf,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
65
    transform,
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
66
    transport,
2323.6.2 by Martin Pool
Move responsibility for suggesting upgrades to ui object
67
    ui,
3586.1.3 by Ian Clatworthy
add views attribute to working trees
68
    views,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
69
    xml5,
2100.3.10 by Aaron Bentley
Ensure added references are serialized properly, beef up Workingtreee3
70
    xml7,
1731.2.17 by Aaron Bentley
Support extracting with checkouts
71
    )
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
72
""")
73
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
74
# Explicitly import breezy.bzrdir so that the BzrProber
6379.5.1 by Jelmer Vernooij
Make sure that the bzr probers are always registered when bzrlib.workingtree is imported.
75
# is guaranteed to be registered.
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
76
from . import (
6213.1.35 by Jelmer Vernooij
Simplify importing of bzrdir.
77
    bzrdir,
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
78
    osutils,
6213.1.35 by Jelmer Vernooij
Simplify importing of bzrdir.
79
    symbol_versioning,
80
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
81
from .decorators import needs_read_lock, needs_write_lock
82
from .i18n import gettext
83
from .lock import LogicalLockResult
84
from . import mutabletree
85
from .mutabletree import needs_tree_write_lock
86
from .osutils import (
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
87
    file_kind,
88
    isdir,
2206.1.8 by Marius Kruger
Converted move/rename error messages to show source => target.
89
    normpath,
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
90
    pathjoin,
2206.1.8 by Marius Kruger
Converted move/rename error messages to show source => target.
91
    realpath,
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
92
    safe_unicode,
93
    splitpath,
94
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
95
from .revision import CURRENT_REVISION
96
from .sixish import (
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
97
    BytesIO,
98
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
99
from .trace import mutter, note
100
from .symbol_versioning import (
6313.1.4 by Jelmer Vernooij
Fix tests.
101
    deprecated_passed,
102
    DEPRECATED_PARAMETER,
103
    )
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
104
105
106
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
4597.3.48 by Vincent Ladeuil
Start cleaning BRANCH.TODO by pushing changes to either the python modules or the documentation.
107
# TODO: Modifying the conflict objects or their type is currently nearly
108
# impossible as there is no clear relationship between the working tree format
109
# and the conflict list file format.
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
110
CONFLICT_HEADER_1 = "BZR conflict list format 1"
1685.1.30 by John Arbash Meinel
PEP8 for workingtree.py
111
2423.2.1 by Alexander Belchenko
Fix for walkdirs in missing dir with Py2.4 @ win32
112
ERROR_PATH_NOT_FOUND = 3    # WindowsError errno code, equivalent to ENOENT
113
2116.4.1 by John Arbash Meinel
Update file and revision id generators.
114
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
115
class TreeEntry(object):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
116
    """An entry that implements the minimum interface used by commands.
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
117
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
118
    This needs further inspection, it may be better to have
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
119
    InventoryEntries without ids - though that seems wrong. For now,
120
    this is a parallel hierarchy to InventoryEntry, and needs to become
121
    one of several things: decorates to that hierarchy, children of, or
122
    parents of it.
1399.1.3 by Robert Collins
move change detection for text and metadata from delta to entry.detect_changes
123
    Another note is that these objects are currently only used when there is
124
    no InventoryEntry available - i.e. for unversioned objects.
125
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
126
    """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
127
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
128
    def __eq__(self, other):
129
        # yes, this us ugly, TODO: best practice __eq__ style.
130
        return (isinstance(other, TreeEntry)
131
                and other.__class__ == self.__class__)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
132
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
133
    def kind_character(self):
134
        return "???"
135
136
137
class TreeDirectory(TreeEntry):
138
    """See TreeEntry. This is a directory in a working tree."""
139
140
    def __eq__(self, other):
141
        return (isinstance(other, TreeDirectory)
142
                and other.__class__ == self.__class__)
143
144
    def kind_character(self):
145
        return "/"
146
147
148
class TreeFile(TreeEntry):
149
    """See TreeEntry. This is a regular file in a working tree."""
150
151
    def __eq__(self, other):
152
        return (isinstance(other, TreeFile)
153
                and other.__class__ == self.__class__)
154
155
    def kind_character(self):
156
        return ''
157
158
159
class TreeLink(TreeEntry):
160
    """See TreeEntry. This is a symlink in a working tree."""
161
162
    def __eq__(self, other):
163
        return (isinstance(other, TreeLink)
164
                and other.__class__ == self.__class__)
165
166
    def kind_character(self):
167
        return ''
168
169
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
170
class WorkingTree(mutabletree.MutableTree,
5363.2.10 by Jelmer Vernooij
base ControlDir on ControlComponent.
171
    controldir.ControlComponent):
453 by Martin Pool
- Split WorkingTree into its own file
172
    """Working copy tree.
173
5335.1.2 by Robert Collins
Add note that basedir is a unicode object as per John's review.
174
    :ivar basedir: The root of the tree on disk. This is a unicode path object
175
        (as opposed to a URL).
453 by Martin Pool
- Split WorkingTree into its own file
176
    """
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
177
3586.1.3 by Ian Clatworthy
add views attribute to working trees
178
    # override this to set the strategy for storing views
179
    def _make_views(self):
180
        return views.DisabledViews(self)
181
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
182
    def __init__(self, basedir='.',
6313.1.4 by Jelmer Vernooij
Fix tests.
183
                 branch=DEPRECATED_PARAMETER,
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
184
                 _internal=False,
6313.1.1 by Jelmer Vernooij
Move bzr-specific functionality to InventoryWorkingTree.
185
                 _transport=None,
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
186
                 _format=None,
187
                 _bzrdir=None):
2367.2.1 by Robert Collins
Remove bzrlib 0.8 compatability where it was making the code unclear or messy. (Robert Collins)
188
        """Construct a WorkingTree instance. This is not a public API.
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
189
2367.2.1 by Robert Collins
Remove bzrlib 0.8 compatability where it was making the code unclear or messy. (Robert Collins)
190
        :param branch: A branch to override probing for the branch.
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
191
        """
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
192
        self._format = _format
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
193
        self.bzrdir = _bzrdir
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
194
        if not _internal:
2367.2.1 by Robert Collins
Remove bzrlib 0.8 compatability where it was making the code unclear or messy. (Robert Collins)
195
            raise errors.BzrError("Please use bzrdir.open_workingtree or "
196
                "WorkingTree.open() to obtain a WorkingTree.")
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
197
        basedir = safe_unicode(basedir)
1534.5.3 by Robert Collins
Make format 4/5/6 branches share a single LockableFiles instance across wt/branch/repository.
198
        mutter("opening working tree %r", basedir)
6313.1.4 by Jelmer Vernooij
Fix tests.
199
        if deprecated_passed(branch):
200
            self._branch = branch
201
        else:
202
            self._branch = self.bzrdir.open_branch()
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
203
        self.basedir = realpath(basedir)
6313.1.1 by Jelmer Vernooij
Move bzr-specific functionality to InventoryWorkingTree.
204
        self._transport = _transport
3398.1.24 by Ian Clatworthy
make iter_search_rules a tree method
205
        self._rules_searcher = None
3586.1.3 by Ian Clatworthy
add views attribute to working trees
206
        self.views = self._make_views()
3034.4.3 by Aaron Bentley
Add case-sensitivity handling to WorkingTree
207
5158.6.5 by Martin Pool
Implement ControlComponent on WorkingTree
208
    @property
209
    def user_transport(self):
210
        return self.bzrdir.user_transport
211
212
    @property
213
    def control_transport(self):
214
        return self._transport
215
5699.2.1 by Jelmer Vernooij
Move is_control_filename() from Tree to MutableTree.
216
    def is_control_filename(self, filename):
217
        """True if filename is the name of a control file in this tree.
218
219
        :param filename: A filename within the tree. This is a relative path
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
220
            from the root of this tree.
5699.2.1 by Jelmer Vernooij
Move is_control_filename() from Tree to MutableTree.
221
222
        This is true IF and ONLY IF the filename is part of the meta data
223
        that bzr controls in this tree. I.E. a random .bzr directory placed
224
        on disk will not be a control file for this tree.
225
        """
226
        return self.bzrdir.is_control_filename(filename)
227
1681.1.1 by Robert Collins
Make WorkingTree.branch a read only property. (Robert Collins)
228
    branch = property(
229
        fget=lambda self: self._branch,
230
        doc="""The branch this WorkingTree is connected to.
231
232
            This cannot be set - it is reflective of the actual disk structure
233
            the working tree has been constructed from.
234
            """)
235
6110.6.1 by Jelmer Vernooij
Add Tree.has_versioned_directories.
236
    def has_versioned_directories(self):
237
        """See `Tree.has_versioned_directories`."""
238
        return self._format.supports_versioned_directories
239
6379.7.2 by Jelmer Vernooij
Deprecate supports_executable, move check to working tree.
240
    def _supports_executable(self):
241
        if sys.platform == 'win32':
242
            return False
243
        # FIXME: Ideally this should check the file system
244
        return True
245
1687.1.9 by Robert Collins
Teach WorkingTree about break-lock.
246
    def break_lock(self):
247
        """Break a lock if one is present from another instance.
248
249
        Uses the ui factory to ask for confirmation if the lock may be from
250
        an active process.
251
252
        This will probe the repository for its lock as well.
253
        """
6313.1.1 by Jelmer Vernooij
Move bzr-specific functionality to InventoryWorkingTree.
254
        raise NotImplementedError(self.break_lock)
1687.1.9 by Robert Collins
Teach WorkingTree about break-lock.
255
2100.3.14 by Aaron Bentley
Test workingtree4 format, prevent use with old repos
256
    def requires_rich_root(self):
257
        return self._format.requires_rich_root
258
2100.3.20 by Aaron Bentley
Implement tree comparison for tree references
259
    def supports_tree_reference(self):
2255.2.232 by Robert Collins
Make WorkingTree4 report support for references based on the repositories capabilities.
260
        return False
2100.3.20 by Aaron Bentley
Implement tree comparison for tree references
261
3907.2.1 by Ian Clatworthy
WorkingTreeFormat5 supporting content filtering and views
262
    def supports_content_filtering(self):
263
        return self._format.supports_content_filtering()
264
3586.1.3 by Ian Clatworthy
add views attribute to working trees
265
    def supports_views(self):
266
        return self.views.supports_views()
267
6449.4.1 by Jelmer Vernooij
Add convenience method WorkingTree.get_config_stack().
268
    def get_config_stack(self):
6449.4.5 by Jelmer Vernooij
Review feedback from vila.
269
        """Retrieve the config stack for this tree.
270
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
271
        :return: A ``breezy.config.Stack``
6449.4.5 by Jelmer Vernooij
Review feedback from vila.
272
        """
273
        # For the moment, just provide the branch config stack.
6449.4.1 by Jelmer Vernooij
Add convenience method WorkingTree.get_config_stack().
274
        return self.branch.get_config_stack()
275
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
276
    @staticmethod
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
277
    def open(path=None, _unsupported=False):
278
        """Open an existing working tree at path.
279
280
        """
281
        if path is None:
3753.1.1 by John Arbash Meinel
Add some simple direct tests for WT.open and WT.open_containing.
282
            path = osutils.getcwd()
6402.3.3 by Jelmer Vernooij
Simplify safe open a bit more.
283
        control = controldir.ControlDir.open(path, _unsupported=_unsupported)
6402.1.1 by Jelmer Vernooij
Simplify probing.
284
        return control.open_workingtree(unsupported=_unsupported)
3753.1.1 by John Arbash Meinel
Add some simple direct tests for WT.open and WT.open_containing.
285
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
286
    @staticmethod
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
287
    def open_containing(path=None):
288
        """Open an existing working tree which has its root about path.
3753.1.1 by John Arbash Meinel
Add some simple direct tests for WT.open and WT.open_containing.
289
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
290
        This probes for a working tree at path and searches upwards from there.
291
292
        Basically we keep looking up until we find the control directory or
293
        run into /.  If there isn't one, raises NotBranchError.
294
        TODO: give this a new exception.
295
        If there is one, it is returned, along with the unused portion of path.
1685.1.27 by John Arbash Meinel
BzrDir works in URLs, but WorkingTree works in unicode paths
296
297
        :return: The WorkingTree that contains 'path', and the rest of path
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
298
        """
299
        if path is None:
1830.3.14 by John Arbash Meinel
WorkingTree.open_containing() was directly calling os.getcwdu(), which on mac returns the wrong normalization, and on win32 would have the wrong slashes
300
            path = osutils.getcwd()
6207.3.3 by jelmer at samba
Fix tests and the like.
301
        control, relpath = controldir.ControlDir.open_containing(path)
1685.1.28 by John Arbash Meinel
Changing open_containing to always return a unicode path.
302
        return control.open_workingtree(), relpath
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
303
304
    @staticmethod
5521.1.1 by Vincent Ladeuil
Handle --directory when paths are also provided to shelve and restore.
305
    def open_containing_paths(file_list, default_directory=None,
306
                              canonicalize=True, apply_view=True):
5346.4.2 by Martin Pool
Move internal_tree_files and safe_relpath_files onto WorkingTree
307
        """Open the WorkingTree that contains a set of paths.
308
309
        Fail if the paths given are not all in a single tree.
310
311
        This is used for the many command-line interfaces that take a list of
312
        any number of files and that require they all be in the same tree.
313
        """
5521.1.1 by Vincent Ladeuil
Handle --directory when paths are also provided to shelve and restore.
314
        if default_directory is None:
315
            default_directory = u'.'
5346.4.2 by Martin Pool
Move internal_tree_files and safe_relpath_files onto WorkingTree
316
        # recommended replacement for builtins.internal_tree_files
317
        if file_list is None or len(file_list) == 0:
318
            tree = WorkingTree.open_containing(default_directory)[0]
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
319
            # XXX: doesn't really belong here, and seems to have the strange
320
            # side effect of making it return a bunch of files, not the whole
321
            # tree -- mbp 20100716
5346.4.2 by Martin Pool
Move internal_tree_files and safe_relpath_files onto WorkingTree
322
            if tree.supports_views() and apply_view:
323
                view_files = tree.views.lookup_view()
324
                if view_files:
325
                    file_list = view_files
326
                    view_str = views.view_display_str(view_files)
6138.3.4 by Jonathan Riddell
add gettext() to uses of trace.note()
327
                    note(gettext("Ignoring files outside view. View is %s") % view_str)
5346.4.2 by Martin Pool
Move internal_tree_files and safe_relpath_files onto WorkingTree
328
            return tree, file_list
5521.1.1 by Vincent Ladeuil
Handle --directory when paths are also provided to shelve and restore.
329
        if default_directory == u'.':
330
            seed = file_list[0]
331
        else:
332
            seed = default_directory
333
            file_list = [osutils.pathjoin(default_directory, f)
334
                         for f in file_list]
335
        tree = WorkingTree.open_containing(seed)[0]
5346.4.2 by Martin Pool
Move internal_tree_files and safe_relpath_files onto WorkingTree
336
        return tree, tree.safe_relpath_files(file_list, canonicalize,
5521.1.1 by Vincent Ladeuil
Handle --directory when paths are also provided to shelve and restore.
337
                                             apply_view=apply_view)
5346.4.2 by Martin Pool
Move internal_tree_files and safe_relpath_files onto WorkingTree
338
339
    def safe_relpath_files(self, file_list, canonicalize=True, apply_view=True):
340
        """Convert file_list into a list of relpaths in tree.
341
342
        :param self: A tree to operate on.
343
        :param file_list: A list of user provided paths or None.
344
        :param apply_view: if True and a view is set, apply it or check that
345
            specified files are within it
346
        :return: A list of relative paths.
347
        :raises errors.PathNotChild: When a provided path is in a different self
348
            than self.
349
        """
350
        if file_list is None:
351
            return None
352
        if self.supports_views() and apply_view:
353
            view_files = self.views.lookup_view()
354
        else:
355
            view_files = []
356
        new_list = []
357
        # self.relpath exists as a "thunk" to osutils, but canonical_relpath
358
        # doesn't - fix that up here before we enter the loop.
359
        if canonicalize:
360
            fixer = lambda p: osutils.canonical_relpath(self.basedir, p)
361
        else:
362
            fixer = self.relpath
363
        for filename in file_list:
5346.4.3 by Martin Pool
PathNotChild should not give a traceback.
364
            relpath = fixer(osutils.dereference_path(filename))
365
            if view_files and not osutils.is_inside_any(view_files, relpath):
366
                raise errors.FileOutsideView(filename, view_files)
367
            new_list.append(relpath)
5346.4.2 by Martin Pool
Move internal_tree_files and safe_relpath_files onto WorkingTree
368
        return new_list
369
370
    @staticmethod
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
371
    def open_downlevel(path=None):
372
        """Open an unsupported working tree.
373
374
        Only intended for advanced situations like upgrading part of a bzrdir.
375
        """
376
        return WorkingTree.open(path, _unsupported=True)
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
377
3140.1.4 by Aaron Bentley
Add WorkingTree.find_trees
378
    @staticmethod
379
    def find_trees(location):
380
        def list_current(transport):
381
            return [d for d in transport.list_dir('') if d != '.bzr']
382
        def evaluate(bzrdir):
383
            try:
384
                tree = bzrdir.open_workingtree()
385
            except errors.NoWorkingTree:
386
                return True, None
387
            else:
388
                return True, tree
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
389
        t = transport.get_transport(location)
6207.3.3 by jelmer at samba
Fix tests and the like.
390
        iterator = controldir.ControlDir.find_bzrdirs(t, evaluate=evaluate,
3140.1.4 by Aaron Bentley
Add WorkingTree.find_trees
391
                                              list_current=list_current)
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
392
        return [tr for tr in iterator if tr is not None]
3140.1.4 by Aaron Bentley
Add WorkingTree.find_trees
393
453 by Martin Pool
- Split WorkingTree into its own file
394
    def __repr__(self):
395
        return "<%s of %s>" % (self.__class__.__name__,
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
396
                               getattr(self, 'basedir', None))
453 by Martin Pool
- Split WorkingTree into its own file
397
398
    def abspath(self, filename):
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
399
        return pathjoin(self.basedir, filename)
2292.1.30 by Marius Kruger
* Minor text fixes.
400
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
401
    def basis_tree(self):
1927.2.3 by Robert Collins
review comment application - paired with Martin.
402
        """Return RevisionTree for the current last revision.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
403
1927.2.3 by Robert Collins
review comment application - paired with Martin.
404
        If the left most parent is a ghost then the returned tree will be an
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
405
        empty tree - one obtained by calling
3668.5.1 by Jelmer Vernooij
Use NULL_REVISION rather than None for Repository.revision_tree().
406
        repository.revision_tree(NULL_REVISION).
1927.2.3 by Robert Collins
review comment application - paired with Martin.
407
        """
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
408
        try:
409
            revision_id = self.get_parent_ids()[0]
410
        except IndexError:
411
            # no parents, return an empty revision tree.
412
            # in the future this should return the tree for
413
            # 'empty:' - the implicit root empty tree.
3668.5.1 by Jelmer Vernooij
Use NULL_REVISION rather than None for Repository.revision_tree().
414
            return self.branch.repository.revision_tree(
415
                       _mod_revision.NULL_REVISION)
1908.11.2 by Robert Collins
Implement WorkingTree interface conformance tests for
416
        try:
417
            return self.revision_tree(revision_id)
418
        except errors.NoSuchRevision:
419
            pass
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
420
        # No cached copy available, retrieve from the repository.
421
        # FIXME? RBC 20060403 should we cache the inventory locally
422
        # at this point ?
1927.2.1 by Robert Collins
Alter set_pending_merges to shove the left most merge into the trees last-revision if that is not set. Related bugfixes include basis_tree handling ghosts, de-duping the merges with the last-revision and update changing where and how it adds its pending merge.
423
        try:
424
            return self.branch.repository.revision_tree(revision_id)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
425
        except (errors.RevisionNotPresent, errors.NoSuchRevision):
1927.2.1 by Robert Collins
Alter set_pending_merges to shove the left most merge into the trees last-revision if that is not set. Related bugfixes include basis_tree handling ghosts, de-duping the merges with the last-revision and update changing where and how it adds its pending merge.
426
            # the basis tree *may* be a ghost or a low level error may have
4031.3.1 by Frank Aspell
Fixing various typos
427
            # occurred. If the revision is present, its a problem, if its not
1927.2.1 by Robert Collins
Alter set_pending_merges to shove the left most merge into the trees last-revision if that is not set. Related bugfixes include basis_tree handling ghosts, de-duping the merges with the last-revision and update changing where and how it adds its pending merge.
428
            # its a ghost.
429
            if self.branch.repository.has_revision(revision_id):
430
                raise
1927.2.3 by Robert Collins
review comment application - paired with Martin.
431
            # the basis tree is a ghost so return an empty tree.
3668.5.1 by Jelmer Vernooij
Use NULL_REVISION rather than None for Repository.revision_tree().
432
            return self.branch.repository.revision_tree(
433
                       _mod_revision.NULL_REVISION)
453 by Martin Pool
- Split WorkingTree into its own file
434
2665.3.2 by Daniel Watkins
Created _cleanup() method in WorkingTree.
435
    def _cleanup(self):
436
        self._flush_ignore_list_cache()
437
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
438
    def relpath(self, path):
439
        """Return the local path portion from a given path.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
440
441
        The path may be absolute or relative. If its a relative path it is
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
442
        interpreted relative to the python current working directory.
443
        """
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
444
        return osutils.relpath(self.basedir, path)
1457.1.3 by Robert Collins
make Branch.relpath delegate to the working tree.
445
453 by Martin Pool
- Split WorkingTree into its own file
446
    def has_filename(self, filename):
1836.1.22 by John Arbash Meinel
[merge] bzr.dev 1861
447
        return osutils.lexists(self.abspath(filename))
453 by Martin Pool
- Split WorkingTree into its own file
448
3368.2.11 by Ian Clatworthy
add filtered option to get_file and get_file_byname in workingtree.py
449
    def get_file(self, file_id, path=None, filtered=True):
3368.2.45 by Ian Clatworthy
add and use supports_content_filtering API
450
        return self.get_file_with_stat(file_id, path, filtered=filtered)[0]
3709.3.2 by Robert Collins
Race-free stat-fingerprint updating during commit via a new method get_file_with_stat.
451
3368.2.45 by Ian Clatworthy
add and use supports_content_filtering API
452
    def get_file_with_stat(self, file_id, path=None, filtered=True,
5609.29.5 by John Arbash Meinel
Fix bug #740932. Transform should update the sha cache.
453
                           _fstat=osutils.fstat):
4354.4.7 by Aaron Bentley
Move MutableTree.get_file_with_stat to Tree.get_file_with_stat.
454
        """See Tree.get_file_with_stat."""
2743.3.3 by Ian Clatworthy
Skip path lookup for tree.get_file() when we already know the path
455
        if path is None:
456
            path = self.id2path(file_id)
3368.2.41 by Ian Clatworthy
1st cut merge of bzr.dev r3907
457
        file_obj = self.get_file_byname(path, filtered=False)
3368.2.45 by Ian Clatworthy
add and use supports_content_filtering API
458
        stat_value = _fstat(file_obj.fileno())
4413.4.3 by John Arbash Meinel
Move the boolean check to the first part of the if statement
459
        if filtered and self.supports_content_filtering():
3368.2.46 by Ian Clatworthy
minor fix
460
            filters = self._content_filter_stack(path)
5745.3.2 by Jelmer Vernooij
Add filters to import tariff blacklist.
461
            file_obj = _mod_filters.filtered_input_file(file_obj, filters)
3368.2.45 by Ian Clatworthy
add and use supports_content_filtering API
462
        return (file_obj, stat_value)
453 by Martin Pool
- Split WorkingTree into its own file
463
3368.2.41 by Ian Clatworthy
1st cut merge of bzr.dev r3907
464
    def get_file_text(self, file_id, path=None, filtered=True):
5236.1.1 by Tim Penhey
Close the file after read.
465
        my_file = self.get_file(file_id, path=path, filtered=filtered)
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
466
        try:
5236.1.1 by Tim Penhey
Close the file after read.
467
            return my_file.read()
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
468
        finally:
5236.1.1 by Tim Penhey
Close the file after read.
469
            my_file.close()
1852.6.9 by Robert Collins
Add more test trees to the tree-implementations tests.
470
3368.2.11 by Ian Clatworthy
add filtered option to get_file and get_file_byname in workingtree.py
471
    def get_file_byname(self, filename, filtered=True):
3368.2.1 by Ian Clatworthy
first cut at working tree content filtering
472
        path = self.abspath(filename)
3368.2.11 by Ian Clatworthy
add filtered option to get_file and get_file_byname in workingtree.py
473
        f = file(path, 'rb')
4413.4.3 by John Arbash Meinel
Move the boolean check to the first part of the if statement
474
        if filtered and self.supports_content_filtering():
3368.2.11 by Ian Clatworthy
add filtered option to get_file and get_file_byname in workingtree.py
475
            filters = self._content_filter_stack(filename)
5745.3.2 by Jelmer Vernooij
Add filters to import tariff blacklist.
476
            return _mod_filters.filtered_input_file(f, filters)
3368.2.11 by Ian Clatworthy
add filtered option to get_file and get_file_byname in workingtree.py
477
        else:
478
            return f
453 by Martin Pool
- Split WorkingTree into its own file
479
3368.2.45 by Ian Clatworthy
add and use supports_content_filtering API
480
    def get_file_lines(self, file_id, path=None, filtered=True):
3774.1.4 by Aaron Bentley
Use file.readlines on working trees.
481
        """See Tree.get_file_lines()"""
3368.2.45 by Ian Clatworthy
add and use supports_content_filtering API
482
        file = self.get_file(file_id, path, filtered=filtered)
3774.1.4 by Aaron Bentley
Use file.readlines on working trees.
483
        try:
484
            return file.readlines()
485
        finally:
486
            file.close()
487
1773.2.1 by Robert Collins
Teach all trees about unknowns, conflicts and get_parent_ids.
488
    def get_parent_ids(self):
489
        """See Tree.get_parent_ids.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
490
1773.2.1 by Robert Collins
Teach all trees about unknowns, conflicts and get_parent_ids.
491
        This implementation reads the pending merges list and last_revision
492
        value and uses that to decide what the parents list should be.
493
        """
2598.5.3 by Aaron Bentley
Push NULL_REVISION deeper
494
        last_rev = _mod_revision.ensure_null(self._last_revision())
2598.5.7 by Aaron Bentley
Updates from review
495
        if _mod_revision.NULL_REVISION == last_rev:
1773.2.1 by Robert Collins
Teach all trees about unknowns, conflicts and get_parent_ids.
496
            parents = []
497
        else:
498
            parents = [last_rev]
1908.6.10 by Robert Collins
forward to get_parent_ids in pending_merges.
499
        try:
4852.1.7 by John Arbash Meinel
Lots of tweaks in WorkingTree.
500
            merges_bytes = self._transport.get_bytes('pending-merges')
2206.1.7 by Marius Kruger
* errors
501
        except errors.NoSuchFile:
1908.6.10 by Robert Collins
forward to get_parent_ids in pending_merges.
502
            pass
503
        else:
4852.1.9 by John Arbash Meinel
Minor typo fix.
504
            for l in osutils.split_lines(merges_bytes):
2858.2.1 by Martin Pool
Remove most calls to safe_file_id and safe_revision_id.
505
                revision_id = l.rstrip('\n')
2249.5.9 by John Arbash Meinel
Update WorkingTree to use safe_revision_id when appropriate
506
                parents.append(revision_id)
1908.6.10 by Robert Collins
forward to get_parent_ids in pending_merges.
507
        return parents
1773.2.1 by Robert Collins
Teach all trees about unknowns, conflicts and get_parent_ids.
508
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
509
    def get_root_id(self):
510
        """Return the id of this trees root"""
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
511
        raise NotImplementedError(self.get_root_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
512
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
513
    @needs_read_lock
6207.3.5 by Jelmer Vernooij
Use controldir rather than bzrdir.
514
    def clone(self, to_controldir, revision_id=None):
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
515
        """Duplicate this working tree into to_bzr, including all state.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
516
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
517
        Specifically modified files are kept as modified, but
518
        ignored and unknown files are discarded.
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
519
6207.3.5 by Jelmer Vernooij
Use controldir rather than bzrdir.
520
        If you want to make a new line of development, see ControlDir.sprout()
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
521
522
        revision
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
523
            If not None, the cloned tree will have its last revision set to
4031.3.1 by Frank Aspell
Fixing various typos
524
            revision, and difference between the source trees last revision
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
525
            and this one merged in.
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
526
        """
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
527
        # assumes the target bzr dir format is compatible.
6207.3.5 by Jelmer Vernooij
Use controldir rather than bzrdir.
528
        result = to_controldir.create_workingtree()
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
529
        self.copy_content_into(result, revision_id)
530
        return result
531
532
    @needs_read_lock
533
    def copy_content_into(self, tree, revision_id=None):
534
        """Copy the current content and user files of this tree into tree."""
1731.1.33 by Aaron Bentley
Revert no-special-root changes
535
        tree.set_root_id(self.get_root_id())
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
536
        if revision_id is None:
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
537
            merge.transform_tree(tree, self)
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
538
        else:
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
539
            # TODO now merge from tree.last_revision to revision (to preserve
540
            # user local changes)
6519.3.4 by Neil Martinsen-Burrell
try looking up revision in tree first
541
            try:
542
                other_tree = self.revision_tree(revision_id)
543
            except errors.NoSuchRevision:
544
                other_tree = self.branch.repository.revision_tree(revision_id)
545
546
            merge.transform_tree(tree, other_tree)
6241.3.1 by Jelmer Vernooij
Support WorkingTree.clone() having its revision argument set to the NULL revision.
547
            if revision_id == _mod_revision.NULL_REVISION:
548
                new_parents = []
549
            else:
550
                new_parents = [revision_id]
551
            tree.set_parent_ids(new_parents)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
552
1248 by Martin Pool
- new weave based cleanup [broken]
553
    def id2abspath(self, file_id):
554
        return self.abspath(self.id2path(file_id))
555
5786.1.5 by John Arbash Meinel
Move the logic about InventoryDirectory => TreeReference into iter_entries
556
    def _check_for_tree_references(self, iterator):
557
        """See if directories have become tree-references."""
558
        blocked_parent_ids = set()
559
        for path, ie in iterator:
560
            if ie.parent_id in blocked_parent_ids:
561
                # This entry was pruned because one of its parents became a
562
                # TreeReference. If this is a directory, mark it as blocked.
563
                if ie.kind == 'directory':
564
                    blocked_parent_ids.add(ie.file_id)
565
                continue
566
            if ie.kind == 'directory' and self._directory_is_tree_reference(path):
567
                # This InventoryDirectory needs to be a TreeReference
568
                ie = inventory.TreeReference(ie.file_id, ie.name, ie.parent_id)
569
                blocked_parent_ids.add(ie.file_id)
570
            yield path, ie
571
572
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
573
        """See Tree.iter_entries_by_dir()"""
574
        # The only trick here is that if we supports_tree_reference then we
575
        # need to detect if a directory becomes a tree-reference.
576
        iterator = super(WorkingTree, self).iter_entries_by_dir(
577
                specific_file_ids=specific_file_ids,
578
                yield_parents=yield_parents)
579
        if not self.supports_tree_reference():
580
            return iterator
581
        else:
582
            return self._check_for_tree_references(iterator)
583
453 by Martin Pool
- Split WorkingTree into its own file
584
    def get_file_size(self, file_id):
3363.3.4 by Aaron Bentley
Add get_file_size to Tree interface
585
        """See Tree.get_file_size"""
4595.11.11 by Martin Pool
Split out _file_content_summary from path_content_summary and let it return None for size
586
        # XXX: this returns the on-disk size; it should probably return the
587
        # canonical size
3363.2.7 by Aaron Bentley
Implement alterntative-to-inventory tests
588
        try:
589
            return os.path.getsize(self.id2abspath(file_id))
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
590
        except OSError as e:
3363.2.7 by Aaron Bentley
Implement alterntative-to-inventory tests
591
            if e.errno != errno.ENOENT:
592
                raise
593
            else:
594
                return None
453 by Martin Pool
- Split WorkingTree into its own file
595
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
596
    @needs_tree_write_lock
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
597
    def _gather_kinds(self, files, kinds):
598
        """See MutableTree._gather_kinds."""
599
        for pos, f in enumerate(files):
600
            if kinds[pos] is None:
601
                fullpath = normpath(self.abspath(f))
602
                try:
603
                    kinds[pos] = file_kind(fullpath)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
604
                except OSError as e:
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
605
                    if e.errno == errno.ENOENT:
2206.1.7 by Marius Kruger
* errors
606
                        raise errors.NoSuchFile(fullpath)
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
607
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
608
    @needs_write_lock
1908.5.9 by Robert Collins
Add a guard against setting the tree last-revision value to a ghost in the new tree parent management api.
609
    def add_parent_tree_id(self, revision_id, allow_leftmost_as_ghost=False):
1908.5.4 by Robert Collins
Add add_parent_tree_id WorkingTree helper api.
610
        """Add revision_id as a parent.
611
612
        This is equivalent to retrieving the current list of parent ids
613
        and setting the list to its value plus revision_id.
614
615
        :param revision_id: The revision id to add to the parent list. It may
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
616
            be a ghost revision as long as its not the first parent to be
617
            added, or the allow_leftmost_as_ghost parameter is set True.
1908.5.12 by Robert Collins
Apply review feedback - paired with Martin.
618
        :param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
1908.5.4 by Robert Collins
Add add_parent_tree_id WorkingTree helper api.
619
        """
1908.5.13 by Robert Collins
Adding a parent when the first is a ghost already should not require forcing it.
620
        parents = self.get_parent_ids() + [revision_id]
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
621
        self.set_parent_ids(parents, allow_leftmost_as_ghost=len(parents) > 1
2206.1.7 by Marius Kruger
* errors
622
            or allow_leftmost_as_ghost)
1908.5.4 by Robert Collins
Add add_parent_tree_id WorkingTree helper api.
623
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
624
    @needs_tree_write_lock
1908.5.9 by Robert Collins
Add a guard against setting the tree last-revision value to a ghost in the new tree parent management api.
625
    def add_parent_tree(self, parent_tuple, allow_leftmost_as_ghost=False):
1908.5.6 by Robert Collins
Add add_parent_tree to WorkingTree.
626
        """Add revision_id, tree tuple as a parent.
627
628
        This is equivalent to retrieving the current list of parent trees
629
        and setting the list to its value plus parent_tuple. See also
630
        add_parent_tree_id - if you only have a parent id available it will be
631
        simpler to use that api. If you have the parent already available, using
632
        this api is preferred.
633
1908.5.12 by Robert Collins
Apply review feedback - paired with Martin.
634
        :param parent_tuple: The (revision id, tree) to add to the parent list.
635
            If the revision_id is a ghost, pass None for the tree.
636
        :param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
1908.5.6 by Robert Collins
Add add_parent_tree to WorkingTree.
637
        """
1979.2.1 by Robert Collins
(robertc) adds a convenience method "merge_from_branch" to WorkingTree.
638
        parent_ids = self.get_parent_ids() + [parent_tuple[0]]
639
        if len(parent_ids) > 1:
640
            # the leftmost may have already been a ghost, preserve that if it
641
            # was.
642
            allow_leftmost_as_ghost = True
643
        self.set_parent_ids(parent_ids,
1908.5.9 by Robert Collins
Add a guard against setting the tree last-revision value to a ghost in the new tree parent management api.
644
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
1908.5.6 by Robert Collins
Add add_parent_tree to WorkingTree.
645
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
646
    @needs_tree_write_lock
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
647
    def add_pending_merge(self, *revision_ids):
648
        # TODO: Perhaps should check at this point that the
649
        # history of the revision is actually present?
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
650
        parents = self.get_parent_ids()
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
651
        updated = False
652
        for rev_id in revision_ids:
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
653
            if rev_id in parents:
654
                continue
655
            parents.append(rev_id)
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
656
            updated = True
657
        if updated:
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
658
            self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
659
2949.6.2 by Alexander Belchenko
more changes osutils.lstat -> os.lstat
660
    def path_content_summary(self, path, _lstat=os.lstat,
2776.1.7 by Robert Collins
* New method on ``bzrlib.tree.Tree`` ``path_content_summary`` provides a
661
        _mapper=osutils.file_kind_from_stat_mode):
662
        """See Tree.path_content_summary."""
663
        abspath = self.abspath(path)
664
        try:
665
            stat_result = _lstat(abspath)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
666
        except OSError as e:
2776.1.7 by Robert Collins
* New method on ``bzrlib.tree.Tree`` ``path_content_summary`` provides a
667
            if getattr(e, 'errno', None) == errno.ENOENT:
668
                # no file.
669
                return ('missing', None, None, None)
2776.1.9 by Robert Collins
Review feedback.
670
            # propagate other errors
2776.1.7 by Robert Collins
* New method on ``bzrlib.tree.Tree`` ``path_content_summary`` provides a
671
            raise
672
        kind = _mapper(stat_result.st_mode)
673
        if kind == 'file':
4595.11.11 by Martin Pool
Split out _file_content_summary from path_content_summary and let it return None for size
674
            return self._file_content_summary(path, stat_result)
2776.1.7 by Robert Collins
* New method on ``bzrlib.tree.Tree`` ``path_content_summary`` provides a
675
        elif kind == 'directory':
676
            # perhaps it looks like a plain directory, but it's really a
677
            # reference.
678
            if self._directory_is_tree_reference(path):
679
                kind = 'tree-reference'
680
            return kind, None, None, None
681
        elif kind == 'symlink':
4241.14.18 by Vincent Ladeuil
Use better fixes for unicode symlinks handling in WTs.
682
            target = osutils.readlink(abspath)
4241.14.12 by Vincent Ladeuil
Far too many modifications for a single commit, need to restart.
683
            return ('symlink', None, None, target)
2776.1.7 by Robert Collins
* New method on ``bzrlib.tree.Tree`` ``path_content_summary`` provides a
684
        else:
685
            return (kind, None, None, None)
686
4595.11.11 by Martin Pool
Split out _file_content_summary from path_content_summary and let it return None for size
687
    def _file_content_summary(self, path, stat_result):
688
        size = stat_result.st_size
689
        executable = self._is_executable_from_path_and_stat(path, stat_result)
690
        # try for a stat cache lookup
691
        return ('file', size, executable, self._sha_from_stat(
692
            path, stat_result))
693
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
694
    def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
695
        """Common ghost checking functionality from set_parent_*.
696
697
        This checks that the left hand-parent exists if there are any
698
        revisions present.
699
        """
700
        if len(revision_ids) > 0:
701
            leftmost_id = revision_ids[0]
702
            if (not allow_leftmost_as_ghost and not
703
                self.branch.repository.has_revision(leftmost_id)):
704
                raise errors.GhostRevisionUnusableHere(leftmost_id)
705
706
    def _set_merges_from_parent_ids(self, parent_ids):
707
        merges = parent_ids[1:]
3407.2.7 by Martin Pool
Deprecate LockableFiles.put_utf8 and put_bytes.
708
        self._transport.put_bytes('pending-merges', '\n'.join(merges),
3407.2.18 by Martin Pool
BzrDir takes responsibility for default file/dir modes
709
            mode=self.bzrdir._get_file_mode())
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
710
3462.1.2 by John Arbash Meinel
Change WT.set_parent_(ids/trees) to filter out ancestors.
711
    def _filter_parent_ids_by_ancestry(self, revision_ids):
712
        """Check that all merged revisions are proper 'heads'.
713
714
        This will always return the first revision_id, and any merged revisions
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
715
        which are
3462.1.2 by John Arbash Meinel
Change WT.set_parent_(ids/trees) to filter out ancestors.
716
        """
717
        if len(revision_ids) == 0:
718
            return revision_ids
719
        graph = self.branch.repository.get_graph()
720
        heads = graph.heads(revision_ids)
721
        new_revision_ids = revision_ids[:1]
722
        for revision_id in revision_ids[1:]:
723
            if revision_id in heads and revision_id not in new_revision_ids:
724
                new_revision_ids.append(revision_id)
725
        if new_revision_ids != revision_ids:
5753.2.2 by Jelmer Vernooij
Remove some unnecessary imports, clean up lazy imports.
726
            mutter('requested to set revision_ids = %s,'
3462.1.2 by John Arbash Meinel
Change WT.set_parent_(ids/trees) to filter out ancestors.
727
                         ' but filtered to %s', revision_ids, new_revision_ids)
728
        return new_revision_ids
729
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
730
    @needs_tree_write_lock
1908.5.9 by Robert Collins
Add a guard against setting the tree last-revision value to a ghost in the new tree parent management api.
731
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
1908.5.5 by Robert Collins
Add WorkingTree.set_parent_ids.
732
        """Set the parent ids to revision_ids.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
733
1908.5.5 by Robert Collins
Add WorkingTree.set_parent_ids.
734
        See also set_parent_trees. This api will try to retrieve the tree data
735
        for each element of revision_ids from the trees repository. If you have
736
        tree data already available, it is more efficient to use
737
        set_parent_trees rather than set_parent_ids. set_parent_ids is however
738
        an easier API to use.
739
740
        :param revision_ids: The revision_ids to set as the parent ids of this
741
            working tree. Any of these may be ghosts.
742
        """
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
743
        self._check_parents_for_ghosts(revision_ids,
744
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
2598.5.2 by Aaron Bentley
Got all tests passing with Branch returning 'null:' for null revision
745
        for revision_id in revision_ids:
746
            _mod_revision.check_not_reserved_id(revision_id)
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
747
3462.1.2 by John Arbash Meinel
Change WT.set_parent_(ids/trees) to filter out ancestors.
748
        revision_ids = self._filter_parent_ids_by_ancestry(revision_ids)
749
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
750
        if len(revision_ids) > 0:
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
751
            self.set_last_revision(revision_ids[0])
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
752
        else:
2598.5.3 by Aaron Bentley
Push NULL_REVISION deeper
753
            self.set_last_revision(_mod_revision.NULL_REVISION)
2041.1.2 by John Arbash Meinel
Update WorkingTree.set_parent_trees() to directly cache inv.
754
755
        self._set_merges_from_parent_ids(revision_ids)
1908.5.5 by Robert Collins
Add WorkingTree.set_parent_ids.
756
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
757
    @needs_tree_write_lock
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
758
    def set_pending_merges(self, rev_list):
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
759
        parents = self.get_parent_ids()
760
        leftmost = parents[:1]
761
        new_parents = leftmost + rev_list
762
        self.set_parent_ids(new_parents)
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
763
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
764
    @needs_tree_write_lock
1534.7.192 by Aaron Bentley
Record hashes produced by merges
765
    def set_merge_modified(self, modified_hashes):
6313.1.1 by Jelmer Vernooij
Move bzr-specific functionality to InventoryWorkingTree.
766
        """Set the merge modified hashes."""
767
        raise NotImplementedError(self.set_merge_modified)
1534.10.3 by Aaron Bentley
Simplify set_merge_modified with rio_file
768
2776.1.8 by Robert Collins
Retrieve the sha from the dirstate for path_content_summary on hash cache hits; slight performance hit but a big win for incremental commits.
769
    def _sha_from_stat(self, path, stat_result):
770
        """Get a sha digest from the tree's stat cache.
771
772
        The default implementation assumes no stat cache is present.
773
774
        :param path: The path.
775
        :param stat_result: The stat result being looked up.
776
        """
777
        return None
778
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
779
    @needs_write_lock # because merge pulls data into the branch.
1551.15.69 by Aaron Bentley
Add merge_type to merge_from_branch
780
    def merge_from_branch(self, branch, to_revision=None, from_revision=None,
4721.3.2 by Vincent Ladeuil
Simplify mutable_tree.has_changes() and update call sites.
781
                          merge_type=None, force=False):
1979.2.1 by Robert Collins
(robertc) adds a convenience method "merge_from_branch" to WorkingTree.
782
        """Merge from a branch into this working tree.
783
784
        :param branch: The branch to merge from.
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
785
        :param to_revision: If non-None, the merge will merge to to_revision,
786
            but not beyond it. to_revision does not need to be in the history
2206.1.7 by Marius Kruger
* errors
787
            of the branch when it is supplied. If None, to_revision defaults to
1979.2.1 by Robert Collins
(robertc) adds a convenience method "merge_from_branch" to WorkingTree.
788
            branch.last_revision().
789
        """
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
790
        from .merge import Merger, Merge3Merger
4961.2.10 by Martin Pool
No longer need to pass pb in to Merger
791
        merger = Merger(self.branch, this_tree=self)
792
        # check that there are no local alterations
793
        if not force and self.has_changes():
794
            raise errors.UncommittedChanges(self)
795
        if to_revision is None:
796
            to_revision = _mod_revision.ensure_null(branch.last_revision())
797
        merger.other_rev_id = to_revision
798
        if _mod_revision.is_null(merger.other_rev_id):
799
            raise errors.NoCommits(branch)
800
        self.branch.fetch(branch, last_revision=merger.other_rev_id)
801
        merger.other_basis = merger.other_rev_id
802
        merger.other_tree = self.branch.repository.revision_tree(
803
            merger.other_rev_id)
804
        merger.other_branch = branch
805
        if from_revision is None:
806
            merger.find_base()
807
        else:
808
            merger.set_base_revision(from_revision, branch)
809
        if merger.base_rev_id == merger.other_rev_id:
810
            raise errors.PointlessMerge
811
        merger.backup_files = False
812
        if merge_type is None:
813
            merger.merge_type = Merge3Merger
814
        else:
815
            merger.merge_type = merge_type
816
        merger.set_interesting_files(None)
817
        merger.show_base = False
818
        merger.reprocess = False
819
        conflicts = merger.do_merge()
820
        merger.set_pending()
1979.2.1 by Robert Collins
(robertc) adds a convenience method "merge_from_branch" to WorkingTree.
821
        return conflicts
822
2255.2.156 by Martin Pool
Merge WorkingTree implementation back from trunk
823
    def merge_modified(self):
2298.1.1 by Martin Pool
Add test for merge_modified
824
        """Return a dictionary of files modified by a merge.
825
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
826
        The list is initialized by WorkingTree.set_merge_modified, which is
2298.1.1 by Martin Pool
Add test for merge_modified
827
        typically called after we make some automatic updates to the tree
828
        because of a merge.
829
830
        This returns a map of file_id->sha1, containing only files which are
831
        still in the working inventory and have that text hash.
832
        """
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
833
        raise NotImplementedError(self.merge_modified)
2255.2.156 by Martin Pool
Merge WorkingTree implementation back from trunk
834
835
    @needs_write_lock
836
    def mkdir(self, path, file_id=None):
837
        """See MutableTree.mkdir()."""
838
        if file_id is None:
839
            file_id = generate_ids.gen_file_id(os.path.basename(path))
840
        os.mkdir(self.abspath(path))
841
        self.add(path, file_id, 'directory')
842
        return file_id
843
5858.1.1 by Jelmer Vernooij
Support optional path argument to Tree.get_symlink_target.
844
    def get_symlink_target(self, file_id, path=None):
845
        if path is not None:
846
            abspath = self.abspath(path)
847
        else:
848
            abspath = self.id2abspath(file_id)
4241.14.18 by Vincent Ladeuil
Use better fixes for unicode symlinks handling in WTs.
849
        target = osutils.readlink(abspath)
4241.14.12 by Vincent Ladeuil
Far too many modifications for a single commit, need to restart.
850
        return target
2255.2.156 by Martin Pool
Merge WorkingTree implementation back from trunk
851
1731.2.1 by Aaron Bentley
Initial subsume implementation
852
    def subsume(self, other_tree):
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
853
        raise NotImplementedError(self.subsume)
1731.2.1 by Aaron Bentley
Initial subsume implementation
854
2974.2.2 by John Arbash Meinel
Only one test failed, because it was incorrectly succeeding.
855
    def _setup_directory_is_tree_reference(self):
856
        if self._branch.repository._format.supports_tree_reference:
857
            self._directory_is_tree_reference = \
858
                self._directory_may_be_tree_reference
859
        else:
860
            self._directory_is_tree_reference = \
861
                self._directory_is_never_tree_reference
862
863
    def _directory_is_never_tree_reference(self, relpath):
864
        return False
865
866
    def _directory_may_be_tree_reference(self, relpath):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
867
        # as a special case, if a directory contains control files then
2776.1.7 by Robert Collins
* New method on ``bzrlib.tree.Tree`` ``path_content_summary`` provides a
868
        # it's a tree reference, except that the root of the tree is not
869
        return relpath and osutils.isdir(self.abspath(relpath) + u"/.bzr")
870
        # TODO: We could ask all the control formats whether they
871
        # recognize this directory, but at the moment there's no cheap api
872
        # to do that.  Since we probably can only nest bzr checkouts and
873
        # they always use this name it's ok for now.  -- mbp 20060306
874
        #
875
        # FIXME: There is an unhandled case here of a subdirectory
876
        # containing .bzr but not a branch; that will probably blow up
877
        # when you try to commit it.  It might happen if there is a
878
        # checkout in a subdirectory.  This can be avoided by not adding
879
        # it.  mbp 20070306
880
1731.2.17 by Aaron Bentley
Support extracting with checkouts
881
    def extract(self, file_id, format=None):
1731.2.16 by Aaron Bentley
Get extract working for standalone trees
882
        """Extract a subtree from this tree.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
883
1731.2.16 by Aaron Bentley
Get extract working for standalone trees
884
        A new branch will be created, relative to the path for this tree.
885
        """
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
886
        raise NotImplementedError(self.extract)
453 by Martin Pool
- Split WorkingTree into its own file
887
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
888
    def flush(self):
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
889
        """Write the in memory meta data to disk."""
890
        raise NotImplementedError(self.flush)
1986.5.3 by Robert Collins
New method ``WorkingTree.flush()`` which will write the current memory
891
1551.10.29 by Aaron Bentley
Fix tree.list_files when file kind changes
892
    def _kind(self, relpath):
893
        return osutils.file_kind(self.abspath(relpath))
894
4370.5.2 by Ian Clatworthy
extend list_files() with from_dir and recursive parameters
895
    def list_files(self, include_root=False, from_dir=None, recursive=True):
896
        """List all files as (path, class, kind, id, entry).
453 by Martin Pool
- Split WorkingTree into its own file
897
898
        Lists, but does not descend into unversioned directories.
899
        This does not include files that have been deleted in this
4370.5.2 by Ian Clatworthy
extend list_files() with from_dir and recursive parameters
900
        tree. Skips the control directory.
453 by Martin Pool
- Split WorkingTree into its own file
901
5128.1.1 by Vincent Ladeuil
Uncontroversial cleanups, mostly comments
902
        :param include_root: if True, return an entry for the root
4370.5.2 by Ian Clatworthy
extend list_files() with from_dir and recursive parameters
903
        :param from_dir: start from this directory or None for the root
904
        :param recursive: whether to recurse into subdirectories or not
453 by Martin Pool
- Split WorkingTree into its own file
905
        """
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
906
        raise NotImplementedError(self.list_files)
907
5346.1.5 by Vincent Ladeuil
Delete the to_name parameter from WorkingTree.move()
908
    def move(self, from_paths, to_dir=None, after=False):
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
909
        """Rename files.
910
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
911
        to_dir must be known to the working tree.
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
912
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
913
        If to_dir exists and is a directory, the files are moved into
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
914
        it, keeping their old names.
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
915
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
916
        Note that to_dir is only the last component of the new name;
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
917
        this doesn't change the directory.
918
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
919
        For each entry in from_paths the move mode will be determined
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
920
        independently.
921
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
922
        The first mode moves the file in the filesystem and updates the
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
923
        working tree metadata. The second mode only updates the working tree
924
        metadata without touching the file on the filesystem.
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
925
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
926
        move uses the second mode if 'after == True' and the target is not
927
        versioned but present in the working tree.
928
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
929
        move uses the second mode if 'after == False' and the source is
930
        versioned but no longer in the working tree, and the target is not
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
931
        versioned but present in the working tree.
932
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
933
        move uses the first mode if 'after == False' and the source is
934
        versioned and present in the working tree, and the target is not
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
935
        versioned and not present in the working tree.
936
937
        Everything else results in an error.
938
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
939
        This returns a list of (from_path, to_path) pairs for each
2220.1.6 by Marius Kruger
* change error message telling user about --after option sightly
940
        entry that is moved.
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
941
        """
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
942
        raise NotImplementedError(self.move)
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
943
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
944
    @needs_tree_write_lock
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
945
    def rename_one(self, from_rel, to_rel, after=False):
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
946
        """Rename one file.
947
948
        This can change the directory or the filename or both.
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
949
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
950
        rename_one has several 'modes' to work. First, it can rename a physical
951
        file and change the file_id. That is the normal mode. Second, it can
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
952
        only change the file_id without touching any physical file.
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
953
5911.1.4 by Benoît Pierre
Update docstrings for WorkingTree.move() and WorkingTree.rename_one().
954
        rename_one uses the second mode if 'after == True' and 'to_rel' is
955
        either not versioned or newly added, and present in the working tree.
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
956
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
957
        rename_one uses the second mode if 'after == False' and 'from_rel' is
958
        versioned but no longer in the working tree, and 'to_rel' is not
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
959
        versioned but present in the working tree.
960
2220.1.9 by Marius Kruger
Remove all trailing white space this bundle would have
961
        rename_one uses the first mode if 'after == False' and 'from_rel' is
962
        versioned and present in the working tree, and 'to_rel' is not
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
963
        versioned and not present in the working tree.
964
965
        Everything else results in an error.
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
966
        """
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
967
        raise NotImplementedError(self.rename_one)
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
968
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
969
    @needs_read_lock
453 by Martin Pool
- Split WorkingTree into its own file
970
    def unknowns(self):
1508.1.6 by Robert Collins
Move Branch.unknowns() to WorkingTree.
971
        """Return all unknown files.
972
973
        These are files in the working directory that are not versioned or
974
        control files or ignored.
975
        """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
976
        # force the extras method to be fully executed before returning, to
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
977
        # prevent race conditions with the lock
978
        return iter(
979
            [subp for subp in self.extras() if not self.is_ignored(subp)])
2323.6.1 by Martin Pool
(broken) Give a message when opening old workingtree formats suggesting upgrade
980
1988.2.1 by Robert Collins
WorkingTree has a new api ``unversion`` which allow the unversioning of
981
    def unversion(self, file_ids):
982
        """Remove the file ids in file_ids from the current versioned set.
983
984
        When a file_id is unversioned, all of its children are automatically
985
        unversioned.
986
987
        :param file_ids: The file ids to stop versioning.
988
        :raises: NoSuchId if any fileid is not currently versioned.
989
        """
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
990
        raise NotImplementedError(self.unversion)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
991
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
992
    @needs_write_lock
1551.11.10 by Aaron Bentley
Add change reporting to pull
993
    def pull(self, source, overwrite=False, stop_revision=None,
5430.7.1 by Rory Yorke
Added --show-base to pull and update (bug 202374).
994
             change_reporter=None, possible_transports=None, local=False,
995
             show_base=False):
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
996
        source.lock_read()
997
        try:
2249.4.2 by Wouter van Heyst
Convert callers of Branch.revision_history() to Branch.last_revision_info() where sensible.
998
            old_revision_info = self.branch.last_revision_info()
1563.1.4 by Robert Collins
Fix 'bzr pull' on metadir trees.
999
            basis_tree = self.basis_tree()
2817.4.3 by Vincent Ladeuil
Add tests for commit, reuse master branch transport.
1000
            count = self.branch.pull(source, overwrite, stop_revision,
4056.6.4 by Gary van der Merwe
Implement pull --local.
1001
                                     possible_transports=possible_transports,
1002
                                     local=local)
2249.4.2 by Wouter van Heyst
Convert callers of Branch.revision_history() to Branch.last_revision_info() where sensible.
1003
            new_revision_info = self.branch.last_revision_info()
1004
            if new_revision_info != old_revision_info:
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1005
                repository = self.branch.repository
5847.2.1 by John Arbash Meinel
Bug #780677, use a RevisionTree for pull
1006
                if repository._format.fast_deltas:
5847.2.2 by John Arbash Meinel
Forgot that sometimes we don't have any parents during pull.
1007
                    parent_ids = self.get_parent_ids()
1008
                    if parent_ids:
1009
                        basis_id = parent_ids[0]
1010
                        basis_tree = repository.revision_tree(basis_id)
2255.2.38 by Robert Collins
Fix WorkingTree4.pull to work.
1011
                basis_tree.lock_read()
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
1012
                try:
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
1013
                    new_basis_tree = self.branch.basis_tree()
1996.3.6 by John Arbash Meinel
Find a few places that weren't importing their dependencies.
1014
                    merge.merge_inner(
1015
                                self.branch,
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
1016
                                new_basis_tree,
1017
                                basis_tree,
1018
                                this_tree=self,
4961.2.11 by Martin Pool
Pull out pbs and ProgressPhases stored in object state; just use them in single functions
1019
                                pb=None,
5430.7.1 by Rory Yorke
Added --show-base to pull and update (bug 202374).
1020
                                change_reporter=change_reporter,
1021
                                show_base=show_base)
4634.123.11 by John Arbash Meinel
fix 'pull' to also set the root id.
1022
                    basis_root_id = basis_tree.get_root_id()
1023
                    new_root_id = new_basis_tree.get_root_id()
6243.1.1 by Jelmer Vernooij
Fix WorkingTree.pull(stop_revision='null:', overwrite=True).
1024
                    if new_root_id is not None and basis_root_id != new_root_id:
4634.123.11 by John Arbash Meinel
fix 'pull' to also set the root id.
1025
                        self.set_root_id(new_root_id)
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
1026
                finally:
2255.2.38 by Robert Collins
Fix WorkingTree4.pull to work.
1027
                    basis_tree.unlock()
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
1028
                # TODO - dedup parents list with things merged by pull ?
1908.6.3 by Robert Collins
Tidy up the last_revision_id and add_pending_merge conversion to use cleaner apis.
1029
                # reuse the revisiontree we merged against to set the new
1030
                # tree data.
6243.1.1 by Jelmer Vernooij
Fix WorkingTree.pull(stop_revision='null:', overwrite=True).
1031
                parent_trees = []
1032
                if self.branch.last_revision() != _mod_revision.NULL_REVISION:
1033
                    parent_trees.append(
1034
                        (self.branch.last_revision(), new_basis_tree))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1035
                # we have to pull the merge trees out again, because
1036
                # merge_inner has set the ids. - this corner is not yet
1908.6.3 by Robert Collins
Tidy up the last_revision_id and add_pending_merge conversion to use cleaner apis.
1037
                # layered well enough to prevent double handling.
2255.2.38 by Robert Collins
Fix WorkingTree4.pull to work.
1038
                # XXX TODO: Fix the double handling: telling the tree about
1039
                # the already known parent data is wasteful.
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
1040
                merges = self.get_parent_ids()[1:]
1041
                parent_trees.extend([
1042
                    (parent, repository.revision_tree(parent)) for
1043
                     parent in merges])
1044
                self.set_parent_trees(parent_trees)
1185.33.44 by Martin Pool
[patch] show number of revisions pushed/pulled/merged (Robey Pointer)
1045
            return count
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
1046
        finally:
1047
            source.unlock()
1048
1986.1.2 by Robert Collins
Various changes to allow non-workingtree specific tests to run entirely
1049
    @needs_write_lock
1050
    def put_file_bytes_non_atomic(self, file_id, bytes):
1051
        """See MutableTree.put_file_bytes_non_atomic."""
1052
        stream = file(self.id2abspath(file_id), 'wb')
1053
        try:
1054
            stream.write(bytes)
1055
        finally:
1056
            stream.close()
1057
453 by Martin Pool
- Split WorkingTree into its own file
1058
    def extras(self):
2255.7.85 by Robert Collins
Teach _iter_changes to gather unversioned path details upon request.
1059
        """Yield all unversioned files in this WorkingTree.
453 by Martin Pool
- Split WorkingTree into its own file
1060
2255.7.85 by Robert Collins
Teach _iter_changes to gather unversioned path details upon request.
1061
        If there are any unversioned directories then only the directory is
1062
        returned, not all its children.  But if there are unversioned files
453 by Martin Pool
- Split WorkingTree into its own file
1063
        under a versioned subdirectory, they are returned.
1064
1065
        Currently returned depth-first, sorted by name within directories.
2255.7.85 by Robert Collins
Teach _iter_changes to gather unversioned path details upon request.
1066
        This is the same order used by 'osutils.walkdirs'.
453 by Martin Pool
- Split WorkingTree into its own file
1067
        """
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1068
        raise NotImplementedError(self.extras)
453 by Martin Pool
- Split WorkingTree into its own file
1069
1070
    def ignored_files(self):
1071
        """Yield list of PATH, IGNORE_PATTERN"""
1072
        for subp in self.extras():
1073
            pat = self.is_ignored(subp)
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1074
            if pat is not None:
453 by Martin Pool
- Split WorkingTree into its own file
1075
                yield subp, pat
1076
1077
    def get_ignore_list(self):
1078
        """Return list of ignore patterns.
1079
1080
        Cached in the Tree object after the first call.
1081
        """
1836.1.30 by John Arbash Meinel
Change ignore functions to use sets instead of lists.
1082
        ignoreset = getattr(self, '_ignoreset', None)
1083
        if ignoreset is not None:
1084
            return ignoreset
1085
2696.1.1 by Martin Pool
Remove things deprecated in 0.11 and earlier
1086
        ignore_globs = set()
1836.1.30 by John Arbash Meinel
Change ignore functions to use sets instead of lists.
1087
        ignore_globs.update(ignores.get_runtime_ignores())
1088
        ignore_globs.update(ignores.get_user_ignores())
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1089
        if self.has_filename(breezy.IGNORE_FILENAME):
1090
            f = self.get_file_byname(breezy.IGNORE_FILENAME)
1836.1.4 by John Arbash Meinel
Cleanup is_ignored to handle comment lines, and a global ignore pattern
1091
            try:
1836.1.30 by John Arbash Meinel
Change ignore functions to use sets instead of lists.
1092
                ignore_globs.update(ignores.parse_ignore_file(f))
1836.1.4 by John Arbash Meinel
Cleanup is_ignored to handle comment lines, and a global ignore pattern
1093
            finally:
1094
                f.close()
1836.1.30 by John Arbash Meinel
Change ignore functions to use sets instead of lists.
1095
        self._ignoreset = ignore_globs
1836.1.4 by John Arbash Meinel
Cleanup is_ignored to handle comment lines, and a global ignore pattern
1096
        return ignore_globs
453 by Martin Pool
- Split WorkingTree into its own file
1097
2135.2.7 by Kent Gibson
Implement JAM's review suggestions.
1098
    def _flush_ignore_list_cache(self):
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
1099
        """Resets the cached ignore list to force a cache rebuild."""
1100
        self._ignoreset = None
1101
        self._ignoreglobster = None
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
1102
453 by Martin Pool
- Split WorkingTree into its own file
1103
    def is_ignored(self, filename):
1104
        r"""Check whether the filename matches an ignore pattern.
1105
1106
        Patterns containing '/' or '\' need to match the whole path;
4948.5.1 by John Whitley
Implementation of ignore exclusions and basic tests for same.
1107
        others match against only the last component.  Patterns starting
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
1108
        with '!' are ignore exceptions.  Exceptions take precedence
4948.5.1 by John Whitley
Implementation of ignore exclusions and basic tests for same.
1109
        over regular patterns and cause the filename to not be ignored.
453 by Martin Pool
- Split WorkingTree into its own file
1110
1111
        If the file is ignored, returns the pattern which caused it to
1112
        be ignored, otherwise None.  So this can simply be used as a
1113
        boolean if desired."""
2135.2.1 by Kent Gibson
Added glob module to replace broken fnmatch based ignore pattern matching (#57637)
1114
        if getattr(self, '_ignoreglobster', None) is None:
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
1115
            self._ignoreglobster = globbing.ExceptionGlobster(self.get_ignore_list())
4948.5.3 by John Whitley
Refactor the exclusion handling functionality out of
1116
        return self._ignoreglobster.match(filename)
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
1117
1185.12.28 by Aaron Bentley
Removed use of readonly path for executability test
1118
    def kind(self, file_id):
1119
        return file_kind(self.id2abspath(file_id))
1120
3146.8.4 by Aaron Bentley
Eliminate direct use of inventory from transform application
1121
    def stored_kind(self, file_id):
1122
        """See Tree.stored_kind"""
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1123
        raise NotImplementedError(self.stored_kind)
3146.8.4 by Aaron Bentley
Eliminate direct use of inventory from transform application
1124
2012.1.7 by Aaron Bentley
Get tree._iter_changed down to ~ 1 stat per file
1125
    def _comparison_data(self, entry, path):
1126
        abspath = self.abspath(path)
1127
        try:
1128
            stat_value = os.lstat(abspath)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1129
        except OSError as e:
2012.1.7 by Aaron Bentley
Get tree._iter_changed down to ~ 1 stat per file
1130
            if getattr(e, 'errno', None) == errno.ENOENT:
1131
                stat_value = None
1132
                kind = None
1133
                executable = False
1134
            else:
1135
                raise
1136
        else:
1137
            mode = stat_value.st_mode
1138
            kind = osutils.file_kind_from_stat_mode(mode)
6379.7.1 by Jelmer Vernooij
Add and use WorkingTree._supports_executable.
1139
            if not self._supports_executable():
2409.1.2 by Dmitry Vasiliev
Used one-line conditional expression instead of the multi-line one
1140
                executable = entry is not None and entry.executable
2012.1.7 by Aaron Bentley
Get tree._iter_changed down to ~ 1 stat per file
1141
            else:
1142
                executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1143
        return kind, executable, stat_value
1144
1145
    def _file_size(self, entry, stat_value):
1146
        return stat_value.st_size
1147
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1148
    def last_revision(self):
1986.1.6 by Robert Collins
Add MemoryTree.last_revision.
1149
        """Return the last revision of the branch for this tree.
1150
1151
        This format tree does not support a separate marker for last-revision
1152
        compared to the branch.
1153
1154
        See MutableTree.last_revision
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1155
        """
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
1156
        return self._last_revision()
1157
1158
    @needs_read_lock
1159
    def _last_revision(self):
1160
        """helper for get_parent_ids."""
2598.5.10 by Aaron Bentley
Return NULL_REVISION instead of None for the null revision
1161
        return _mod_revision.ensure_null(self.branch.last_revision())
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1162
1694.2.6 by Martin Pool
[merge] bzr.dev
1163
    def is_locked(self):
6313.1.1 by Jelmer Vernooij
Move bzr-specific functionality to InventoryWorkingTree.
1164
        """Check if this tree is locked."""
1165
        raise NotImplementedError(self.is_locked)
2298.1.1 by Martin Pool
Add test for merge_modified
1166
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1167
    def lock_read(self):
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1168
        """Lock the tree for reading.
1169
1170
        This also locks the branch, and can be unlocked via self.unlock().
1171
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1172
        :return: A breezy.lock.LogicalLockResult.
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1173
        """
6313.1.1 by Jelmer Vernooij
Move bzr-specific functionality to InventoryWorkingTree.
1174
        raise NotImplementedError(self.lock_read)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1175
1997.1.1 by Robert Collins
Add WorkingTree.lock_tree_write.
1176
    def lock_tree_write(self):
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1177
        """See MutableTree.lock_tree_write, and WorkingTree.unlock.
1178
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1179
        :return: A breezy.lock.LogicalLockResult.
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1180
        """
6313.1.1 by Jelmer Vernooij
Move bzr-specific functionality to InventoryWorkingTree.
1181
        raise NotImplementedError(self.lock_tree_write)
1997.1.1 by Robert Collins
Add WorkingTree.lock_tree_write.
1182
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1183
    def lock_write(self):
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1184
        """See MutableTree.lock_write, and WorkingTree.unlock.
1185
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1186
        :return: A breezy.lock.LogicalLockResult.
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1187
        """
6313.1.1 by Jelmer Vernooij
Move bzr-specific functionality to InventoryWorkingTree.
1188
        raise NotImplementedError(self.lock_write)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1189
1694.2.6 by Martin Pool
[merge] bzr.dev
1190
    def get_physical_lock_status(self):
6313.1.1 by Jelmer Vernooij
Move bzr-specific functionality to InventoryWorkingTree.
1191
        raise NotImplementedError(self.get_physical_lock_status)
2255.2.204 by Robert Collins
Fix info and status again.
1192
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1193
    def set_last_revision(self, new_revision):
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1194
        """Change the last revision in the working tree."""
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1195
        raise NotImplementedError(self.set_last_revision)
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1196
1197
    def _change_last_revision(self, new_revision):
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1198
        """Template method part of set_last_revision to perform the change.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1199
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1200
        This is used to allow WorkingTree3 instances to not affect branch
1201
        when their last revision is set.
1202
        """
2598.5.1 by Aaron Bentley
Start eliminating the use of None to indicate null revision
1203
        if _mod_revision.is_null(new_revision):
5718.7.13 by Jelmer Vernooij
Avoid using set_revision_history.
1204
            self.branch.set_last_revision_info(0, new_revision)
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1205
            return False
5718.8.14 by Jelmer Vernooij
Check for reserved revids.
1206
        _mod_revision.check_not_reserved_id(new_revision)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1207
        try:
1908.1.1 by Robert Collins
Relax WorkingTree.set_last-revision to allow any revision to be set.
1208
            self.branch.generate_revision_history(new_revision)
1209
        except errors.NoSuchRevision:
1210
            # not present in the repo - dont try to set it deeper than the tip
5807.6.1 by Jelmer Vernooij
Use undeprecated wrappers.
1211
            self.branch._set_revision_history([new_revision])
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1212
        return True
1213
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
1214
    @needs_tree_write_lock
2292.1.22 by Marius Kruger
Implement TODO: Normalize names.
1215
    def remove(self, files, verbose=False, to_file=None, keep_files=True,
2292.1.10 by Marius Kruger
* workingtree.remove
1216
        force=False):
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1217
        """Remove nominated files from the working tree metadata.
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1218
2292.1.22 by Marius Kruger
Implement TODO: Normalize names.
1219
        :files: File paths relative to the basedir.
2292.1.7 by Marius Kruger
First pass at only deleting files on 'bzr remove' when
1220
        :keep_files: If true, the files will also be kept.
2292.1.10 by Marius Kruger
* workingtree.remove
1221
        :force: Delete files and directories, even if they are changed and
1222
            even if the directories are not empty.
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1223
        """
1224
        if isinstance(files, basestring):
1225
            files = [files]
1226
1551.15.12 by Aaron Bentley
Stop using inventory directly in WorkingTree.remove
1227
        inv_delta = []
2292.1.25 by Marius Kruger
* Add utility method delta.get_changes_as_text to get the output of .show()
1228
5340.8.3 by Marius Kruger
new_files => all_files
1229
        all_files = set() # specified and nested files 
2655.2.16 by Marius Kruger
* Rename `unknown_files_in_directory` to `unknown_nested_files`, which
1230
        unknown_nested_files=set()
4792.5.2 by Martin Pool
Move stubby show_status from bzrlib.textui into remove(), its only user
1231
        if to_file is None:
1232
            to_file = sys.stdout
2292.1.25 by Marius Kruger
* Add utility method delta.get_changes_as_text to get the output of .show()
1233
5340.8.1 by Marius Kruger
* make the backup file name generator in bzrdir available to others
1234
        files_to_backup = []
1235
2292.1.25 by Marius Kruger
* Add utility method delta.get_changes_as_text to get the output of .show()
1236
        def recurse_directory_to_add_files(directory):
2655.2.16 by Marius Kruger
* Rename `unknown_files_in_directory` to `unknown_nested_files`, which
1237
            # Recurse directory and add all files
2292.1.25 by Marius Kruger
* Add utility method delta.get_changes_as_text to get the output of .show()
1238
            # so we can check if they have changed.
5160.2.2 by Marius Kruger
check if changed file isStillInDirToBeRemoved before bailing out
1239
            for parent_info, file_infos in self.walkdirs(directory):
3585.2.4 by Robert Collins
* Deleting directories by hand before running ``bzr rm`` will not
1240
                for relpath, basename, kind, lstat, fileid, kind in file_infos:
2655.2.16 by Marius Kruger
* Rename `unknown_files_in_directory` to `unknown_nested_files`, which
1241
                    # Is it versioned or ignored?
5340.8.1 by Marius Kruger
* make the backup file name generator in bzrdir available to others
1242
                    if self.path2id(relpath):
2655.2.16 by Marius Kruger
* Rename `unknown_files_in_directory` to `unknown_nested_files`, which
1243
                        # Add nested content for deletion.
5340.8.3 by Marius Kruger
new_files => all_files
1244
                        all_files.add(relpath)
2655.2.16 by Marius Kruger
* Rename `unknown_files_in_directory` to `unknown_nested_files`, which
1245
                    else:
5340.8.1 by Marius Kruger
* make the backup file name generator in bzrdir available to others
1246
                        # Files which are not versioned
2655.2.16 by Marius Kruger
* Rename `unknown_files_in_directory` to `unknown_nested_files`, which
1247
                        # should be treated as unknown.
5340.8.1 by Marius Kruger
* make the backup file name generator in bzrdir available to others
1248
                        files_to_backup.append(relpath)
2292.1.25 by Marius Kruger
* Add utility method delta.get_changes_as_text to get the output of .show()
1249
1250
        for filename in files:
1251
            # Get file name into canonical form.
1551.15.11 by Aaron Bentley
Bugfix WorkingTree.remove to handle subtrees, and non-cwd trees
1252
            abspath = self.abspath(filename)
1253
            filename = self.relpath(abspath)
2292.1.25 by Marius Kruger
* Add utility method delta.get_changes_as_text to get the output of .show()
1254
            if len(filename) > 0:
5340.8.3 by Marius Kruger
new_files => all_files
1255
                all_files.add(filename)
3585.2.4 by Robert Collins
* Deleting directories by hand before running ``bzr rm`` will not
1256
                recurse_directory_to_add_files(filename)
2655.2.4 by Marius Kruger
* workingtree.remove
1257
5340.8.3 by Marius Kruger
new_files => all_files
1258
        files = list(all_files)
2292.1.22 by Marius Kruger
Implement TODO: Normalize names.
1259
2475.5.2 by Marius Kruger
* blackbox/test_remove
1260
        if len(files) == 0:
1261
            return # nothing to do
1262
2292.1.22 by Marius Kruger
Implement TODO: Normalize names.
1263
        # Sort needed to first handle directory content before the directory
1264
        files.sort(reverse=True)
2655.2.6 by Marius Kruger
* workingtree.remove
1265
2655.2.4 by Marius Kruger
* workingtree.remove
1266
        # Bail out if we are going to delete files we shouldn't
2292.1.11 by Marius Kruger
* workingtree.remove
1267
        if not keep_files and not force:
5340.8.1 by Marius Kruger
* make the backup file name generator in bzrdir available to others
1268
            for (file_id, path, content_change, versioned, parent_id, name,
1269
                 kind, executable) in self.iter_changes(self.basis_tree(),
1270
                     include_unchanged=True, require_versioned=False,
1271
                     want_unversioned=True, specific_files=files):
1272
                if versioned[0] == False:
1273
                    # The record is unknown or newly added
1274
                    files_to_backup.append(path[1])
1275
                elif (content_change and (kind[1] is not None) and
1276
                        osutils.is_inside_any(files, path[1])):
1277
                    # Versioned and changed, but not deleted, and still
1278
                    # in one of the dirs to be deleted.
1279
                    files_to_backup.append(path[1])
2475.5.2 by Marius Kruger
* blackbox/test_remove
1280
5340.8.5 by Marius Kruger
* extract backup_files
1281
        def backup(file_to_backup):
5409.5.4 by Vincent Ladeuil
Deprecate BzrDir.generate_backup_name and use osutils.available_backup_name.
1282
            backup_name = self.bzrdir._available_backup_name(file_to_backup)
5340.8.5 by Marius Kruger
* extract backup_files
1283
            osutils.rename(abs_path, self.abspath(backup_name))
5409.5.4 by Vincent Ladeuil
Deprecate BzrDir.generate_backup_name and use osutils.available_backup_name.
1284
            return "removed %s (but kept a copy: %s)" % (file_to_backup,
1285
                                                         backup_name)
5340.8.5 by Marius Kruger
* extract backup_files
1286
4031.3.1 by Frank Aspell
Fixing various typos
1287
        # Build inv_delta and delete files where applicable,
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1288
        # do this before any modifications to meta data.
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1289
        for f in files:
1551.15.12 by Aaron Bentley
Stop using inventory directly in WorkingTree.remove
1290
            fid = self.path2id(f)
2655.2.4 by Marius Kruger
* workingtree.remove
1291
            message = None
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1292
            if not fid:
2655.2.4 by Marius Kruger
* workingtree.remove
1293
                message = "%s is not versioned." % (f,)
2245.5.1 by Marius Kruger
Let bzr rm rather give a warning than an error when trying to remove a non-versioned file.
1294
            else:
1295
                if verbose:
2292.1.10 by Marius Kruger
* workingtree.remove
1296
                    # having removed it, it must be either ignored or unknown
2245.5.1 by Marius Kruger
Let bzr rm rather give a warning than an error when trying to remove a non-versioned file.
1297
                    if self.is_ignored(f):
1298
                        new_status = 'I'
1299
                    else:
1300
                        new_status = '?'
4792.5.2 by Martin Pool
Move stubby show_status from bzrlib.textui into remove(), its only user
1301
                    # XXX: Really should be a more abstract reporter interface
4792.5.3 by Martin Pool
Further cleanup of removal reporting code
1302
                    kind_ch = osutils.kind_marker(self.kind(fid))
1303
                    to_file.write(new_status + '       ' + f + kind_ch + '\n')
2655.2.17 by Marius Kruger
Minor doc and spacing updates.
1304
                # Unversion file
1551.15.12 by Aaron Bentley
Stop using inventory directly in WorkingTree.remove
1305
                inv_delta.append((f, None, fid, None))
2655.2.4 by Marius Kruger
* workingtree.remove
1306
                message = "removed %s" % (f,)
2292.1.7 by Marius Kruger
First pass at only deleting files on 'bzr remove' when
1307
2292.1.13 by Marius Kruger
* merge the unversion command back into the remove command,
1308
            if not keep_files:
2292.1.30 by Marius Kruger
* Minor text fixes.
1309
                abs_path = self.abspath(f)
1310
                if osutils.lexists(abs_path):
1311
                    if (osutils.isdir(abs_path) and
1312
                        len(os.listdir(abs_path)) > 0):
2655.2.4 by Marius Kruger
* workingtree.remove
1313
                        if force:
1314
                            osutils.rmtree(abs_path)
5340.8.1 by Marius Kruger
* make the backup file name generator in bzrdir available to others
1315
                            message = "deleted %s" % (f,)
2655.2.4 by Marius Kruger
* workingtree.remove
1316
                        else:
5340.8.5 by Marius Kruger
* extract backup_files
1317
                            message = backup(f)
2292.1.25 by Marius Kruger
* Add utility method delta.get_changes_as_text to get the output of .show()
1318
                    else:
5340.8.1 by Marius Kruger
* make the backup file name generator in bzrdir available to others
1319
                        if f in files_to_backup:
5340.8.5 by Marius Kruger
* extract backup_files
1320
                            message = backup(f)
5340.8.1 by Marius Kruger
* make the backup file name generator in bzrdir available to others
1321
                        else:
1322
                            osutils.delete_any(abs_path)
1323
                            message = "deleted %s" % (f,)
2292.1.13 by Marius Kruger
* merge the unversion command back into the remove command,
1324
                elif message is not None:
2655.2.17 by Marius Kruger
Minor doc and spacing updates.
1325
                    # Only care if we haven't done anything yet.
1326
                    message = "%s does not exist." % (f,)
2292.1.25 by Marius Kruger
* Add utility method delta.get_changes_as_text to get the output of .show()
1327
2655.2.17 by Marius Kruger
Minor doc and spacing updates.
1328
            # Print only one message (if any) per file.
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
1329
            if message is not None:
1330
                note(message)
1551.15.12 by Aaron Bentley
Stop using inventory directly in WorkingTree.remove
1331
        self.apply_inventory_delta(inv_delta)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1332
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
1333
    @needs_tree_write_lock
2748.3.2 by Aaron Bentley
Fix revert, remove-tree, and various tests to use None for 'no files specified'
1334
    def revert(self, filenames=None, old_tree=None, backups=True,
4961.2.9 by Martin Pool
Rip out most remaining uses of DummyProgressBar
1335
               pb=None, report_changes=False):
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1336
        from .conflicts import resolve
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1337
        if old_tree is None:
2949.2.1 by Robert Collins
* Revert takes out an appropriate lock when reverting to a basis tree, and
1338
            basis_tree = self.basis_tree()
1339
            basis_tree.lock_read()
1340
            old_tree = basis_tree
1534.10.14 by Aaron Bentley
Made revert clear conflicts
1341
        else:
2949.2.1 by Robert Collins
* Revert takes out an appropriate lock when reverting to a basis tree, and
1342
            basis_tree = None
1343
        try:
1344
            conflicts = transform.revert(self, old_tree, filenames, backups, pb,
1345
                                         report_changes)
2949.2.2 by Robert Collins
Avoid dirstate parent resetting when it is not needed during revert.
1346
            if filenames is None and len(self.get_parent_ids()) > 1:
2949.2.1 by Robert Collins
* Revert takes out an appropriate lock when reverting to a basis tree, and
1347
                parent_trees = []
1348
                last_revision = self.last_revision()
4496.3.4 by Andrew Bennetts
Tidy up unused and redundant imports in workingtree.py.
1349
                if last_revision != _mod_revision.NULL_REVISION:
2949.2.1 by Robert Collins
* Revert takes out an appropriate lock when reverting to a basis tree, and
1350
                    if basis_tree is None:
1351
                        basis_tree = self.basis_tree()
1352
                        basis_tree.lock_read()
1353
                    parent_trees.append((last_revision, basis_tree))
1354
                self.set_parent_trees(parent_trees)
1355
                resolve(self)
1356
            else:
3017.2.1 by Aaron Bentley
Revert now resolves conflicts recursively (#102739)
1357
                resolve(self, filenames, ignore_misses=True, recursive=True)
2949.2.1 by Robert Collins
* Revert takes out an appropriate lock when reverting to a basis tree, and
1358
        finally:
1359
            if basis_tree is not None:
1360
                basis_tree.unlock()
1558.7.13 by Aaron Bentley
WorkingTree.revert returns conflicts
1361
        return conflicts
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1362
6538.1.20 by Aaron Bentley
Cleanup
1363
    @needs_write_lock
6538.1.5 by Aaron Bentley
Implement WorkingTree.store_uncommitted.
1364
    def store_uncommitted(self):
6538.1.20 by Aaron Bentley
Cleanup
1365
        """Store uncommitted changes from the tree in the branch."""
1366
        target_tree = self.basis_tree()
1367
        shelf_creator = shelf.ShelfCreator(self, target_tree)
6538.1.5 by Aaron Bentley
Implement WorkingTree.store_uncommitted.
1368
        try:
6538.1.20 by Aaron Bentley
Cleanup
1369
            if not shelf_creator.shelve_all():
1370
                return
1371
            self.branch.store_uncommitted(shelf_creator)
1372
            shelf_creator.transform()
6538.1.5 by Aaron Bentley
Implement WorkingTree.store_uncommitted.
1373
        finally:
6538.1.20 by Aaron Bentley
Cleanup
1374
            shelf_creator.finalize()
6538.1.7 by Aaron Bentley
Move to shelve_all and improve it.
1375
        note('Uncommitted changes stored in branch "%s".', self.branch.nick)
6538.1.5 by Aaron Bentley
Implement WorkingTree.store_uncommitted.
1376
6538.1.20 by Aaron Bentley
Cleanup
1377
    @needs_write_lock
1378
    def restore_uncommitted(self):
1379
        """Restore uncommitted changes from the branch into the tree."""
6538.1.12 by Aaron Bentley
Move unshelver construction to Branch.
1380
        unshelver = self.branch.get_unshelver(self)
1381
        if unshelver is None:
6538.1.11 by Aaron Bentley
Switch to much simpler implementation of restore_uncommitted.
1382
            return
6538.1.10 by Aaron Bentley
Implement WorkingTree.get_uncommitted_data
1383
        try:
6538.1.11 by Aaron Bentley
Switch to much simpler implementation of restore_uncommitted.
1384
            merger = unshelver.make_merger()
1385
            merger.ignore_zero = True
1386
            merger.do_merge()
6538.1.21 by Aaron Bentley
Ensure shelves are deleted when restored.
1387
            self.branch.store_uncommitted(None)
6538.1.11 by Aaron Bentley
Switch to much simpler implementation of restore_uncommitted.
1388
        finally:
1389
            unshelver.finalize()
6538.1.10 by Aaron Bentley
Implement WorkingTree.get_uncommitted_data
1390
1908.11.2 by Robert Collins
Implement WorkingTree interface conformance tests for
1391
    def revision_tree(self, revision_id):
1392
        """See Tree.revision_tree.
1393
1394
        WorkingTree can supply revision_trees for the basis revision only
1395
        because there is only one cached inventory in the bzr directory.
1396
        """
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1397
        raise NotImplementedError(self.revision_tree)
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1398
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
1399
    @needs_tree_write_lock
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1400
    def set_root_id(self, file_id):
1401
        """Set the root id for this tree."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1402
        # for compatability
2858.2.4 by Martin Pool
Restore deprecated behaviour of accepting None for WorkingTree.set_root_id (thanks igc)
1403
        if file_id is None:
3400.3.6 by Martin Pool
Remove code deprecated prior to 1.1 and its tests
1404
            raise ValueError(
1405
                'WorkingTree.set_root_id with fileid=None')
1406
        file_id = osutils.safe_file_id(file_id)
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
1407
        self._set_root_id(file_id)
1408
1409
    def _set_root_id(self, file_id):
1410
        """Set the root id for this tree, in a format specific manner.
1411
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1412
        :param file_id: The file id to assign to the root. It must not be
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
1413
            present in the current inventory or an error will occur. It must
1414
            not be None, but rather a valid file id.
1415
        """
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1416
        raise NotImplementedError(self._set_root_id)
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1417
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1418
    def unlock(self):
1419
        """See Branch.unlock.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1420
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1421
        WorkingTree locking just uses the Branch locking facilities.
1422
        This is current because all working trees have an embedded branch
1423
        within them. IF in the future, we were to make branch data shareable
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1424
        between multiple working trees, i.e. via shared storage, then we
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1425
        would probably want to lock both the local tree, and the branch.
1426
        """
1852.4.2 by Robert Collins
Refactor workingtree.unlock to be cleaner, adding a trivial test for unlock. Introduces an explicit Format2 tree type, making the base WorkingTree cleaner to derive from.
1427
        raise NotImplementedError(self.unlock)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1428
1907.5.7 by Matthieu Moy
Coding style fixes thanks to jam.
1429
    _marker = object()
1430
2009.1.4 by Mark Hammond
First attempt to merge .dev and resolve the conflicts (but tests are
1431
    def update(self, change_reporter=None, possible_transports=None,
5430.7.1 by Rory Yorke
Added --show-base to pull and update (bug 202374).
1432
               revision=None, old_tip=_marker, show_base=False):
1587.1.11 by Robert Collins
Local commits appear to be working properly.
1433
        """Update a working tree along its branch.
1434
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1435
        This will update the branch if its bound too, which means we have
1436
        multiple trees involved:
1437
1438
        - The new basis tree of the master.
1439
        - The old basis tree of the branch.
1440
        - The old basis tree of the working tree.
1441
        - The current working tree state.
1442
1443
        Pathologically, all three may be different, and non-ancestors of each
1444
        other.  Conceptually we want to:
1445
1446
        - Preserve the wt.basis->wt.state changes
1447
        - Transform the wt.basis to the new master basis.
1448
        - Apply a merge of the old branch basis to get any 'local' changes from
1449
          it into the tree.
1450
        - Restore the wt.basis->wt.state changes.
1587.1.11 by Robert Collins
Local commits appear to be working properly.
1451
1452
        There isn't a single operation at the moment to do that, so we:
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
1453
1731.1.33 by Aaron Bentley
Revert no-special-root changes
1454
        - Merge current state -> basis tree of the master w.r.t. the old tree
1455
          basis.
1456
        - Do a 'normal' merge of the old branch basis if it is relevant.
1907.5.4 by Matthieu Moy
Added test-cases for update -r. Tweaked the implementation too.
1457
2009.1.2 by John Arbash Meinel
minor whitespace cleanup.
1458
        :param revision: The target revision to update to. Must be in the
1459
            revision history.
1460
        :param old_tip: If branch.update() has already been run, the value it
1461
            returned (old tip of the branch or None). _marker is used
1462
            otherwise.
1587.1.11 by Robert Collins
Local commits appear to be working properly.
1463
        """
3280.5.1 by John Arbash Meinel
Avoid opening the master branch when we won't use it.
1464
        if self.branch.get_bound_location() is not None:
2084.2.1 by Aaron Bentley
Support updating lightweight checkouts of readonly branches
1465
            self.lock_write()
2009.1.6 by Mark Hammond
more tweaks of the merge to get the tests passing.
1466
            update_branch = (old_tip is self._marker)
2084.2.1 by Aaron Bentley
Support updating lightweight checkouts of readonly branches
1467
        else:
1468
            self.lock_tree_write()
1469
            update_branch = False
1470
        try:
1471
            if update_branch:
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
1472
                old_tip = self.branch.update(possible_transports)
2084.2.1 by Aaron Bentley
Support updating lightweight checkouts of readonly branches
1473
            else:
2009.1.6 by Mark Hammond
more tweaks of the merge to get the tests passing.
1474
                if old_tip is self._marker:
1475
                    old_tip = None
5430.7.1 by Rory Yorke
Added --show-base to pull and update (bug 202374).
1476
            return self._update_tree(old_tip, change_reporter, revision, show_base)
2084.2.1 by Aaron Bentley
Support updating lightweight checkouts of readonly branches
1477
        finally:
1478
            self.unlock()
1479
1480
    @needs_tree_write_lock
5430.7.1 by Rory Yorke
Added --show-base to pull and update (bug 202374).
1481
    def _update_tree(self, old_tip=None, change_reporter=None, revision=None,
1482
                     show_base=False):
2084.2.1 by Aaron Bentley
Support updating lightweight checkouts of readonly branches
1483
        """Update a tree to the master branch.
1484
1485
        :param old_tip: if supplied, the previous tip revision the branch,
1486
            before it was changed to the master branch's tip.
1487
        """
1927.2.3 by Robert Collins
review comment application - paired with Martin.
1488
        # here if old_tip is not None, it is the old tip of the branch before
1489
        # it was updated from the master branch. This should become a pending
1490
        # merge in the working tree to preserve the user existing work.  we
1491
        # cant set that until we update the working trees last revision to be
1492
        # one from the new branch, because it will just get absorbed by the
1493
        # parent de-duplication logic.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1494
        #
1927.2.3 by Robert Collins
review comment application - paired with Martin.
1495
        # We MUST save it even if an error occurs, because otherwise the users
1496
        # local work is unreferenced and will appear to have been lost.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1497
        #
4985.3.17 by Vincent Ladeuil
Some cleanup.
1498
        nb_conflicts = 0
1907.5.13 by Matthieu Moy
Fixed bad conflict resolution.
1499
        try:
1500
            last_rev = self.get_parent_ids()[0]
1501
        except IndexError:
2598.5.1 by Aaron Bentley
Start eliminating the use of None to indicate null revision
1502
            last_rev = _mod_revision.NULL_REVISION
1907.5.8 by Matthieu Moy
merge (with conflicts)
1503
        if revision is None:
1907.5.13 by Matthieu Moy
Fixed bad conflict resolution.
1504
            revision = self.branch.last_revision()
4985.3.17 by Vincent Ladeuil
Some cleanup.
1505
4985.3.14 by Gerard Krol
Don't compare old_tip to revision, just do the merge.
1506
        old_tip = old_tip or _mod_revision.NULL_REVISION
4985.3.17 by Vincent Ladeuil
Some cleanup.
1507
4985.3.15 by Gerard Krol
Now correctly determine the branch point (instead of some lucky guesses)
1508
        if not _mod_revision.is_null(old_tip) and old_tip != last_rev:
4985.3.14 by Gerard Krol
Don't compare old_tip to revision, just do the merge.
1509
            # the branch we are bound to was updated
1510
            # merge those changes in first
1511
            base_tree  = self.basis_tree()
4985.3.1 by Gerard Krol
Werkt wel ok
1512
            other_tree = self.branch.repository.revision_tree(old_tip)
4985.3.17 by Vincent Ladeuil
Some cleanup.
1513
            nb_conflicts = merge.merge_inner(self.branch, other_tree,
1514
                                             base_tree, this_tree=self,
5430.7.1 by Rory Yorke
Added --show-base to pull and update (bug 202374).
1515
                                             change_reporter=change_reporter,
1516
                                             show_base=show_base)
4985.3.17 by Vincent Ladeuil
Some cleanup.
1517
            if nb_conflicts:
4985.3.14 by Gerard Krol
Don't compare old_tip to revision, just do the merge.
1518
                self.add_parent_tree((old_tip, other_tree))
6138.3.4 by Jonathan Riddell
add gettext() to uses of trace.note()
1519
                note(gettext('Rerun update after fixing the conflicts.'))
4985.3.17 by Vincent Ladeuil
Some cleanup.
1520
                return nb_conflicts
4985.3.1 by Gerard Krol
Werkt wel ok
1521
2009.1.4 by Mark Hammond
First attempt to merge .dev and resolve the conflicts (but tests are
1522
        if last_rev != _mod_revision.ensure_null(revision):
4985.3.15 by Gerard Krol
Now correctly determine the branch point (instead of some lucky guesses)
1523
            # the working tree is up to date with the branch
1524
            # we can merge the specified revision from master
1525
            to_tree = self.branch.repository.revision_tree(revision)
1526
            to_root_id = to_tree.get_root_id()
1527
1927.2.3 by Robert Collins
review comment application - paired with Martin.
1528
            basis = self.basis_tree()
2255.2.44 by Robert Collins
Fix tree unlock on readonly Format4 trees with dirty hashcache.
1529
            basis.lock_read()
1530
            try:
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1531
                if (basis.get_root_id() is None or basis.get_root_id() != to_root_id):
4634.123.10 by John Arbash Meinel
update now properly handles root-id changes.
1532
                    self.set_root_id(to_root_id)
2255.6.6 by Aaron Bentley
Fix update to set unique roots, and work with dirstate
1533
                    self.flush()
2255.2.44 by Robert Collins
Fix tree unlock on readonly Format4 trees with dirty hashcache.
1534
            finally:
1535
                basis.unlock()
4985.3.15 by Gerard Krol
Now correctly determine the branch point (instead of some lucky guesses)
1536
1537
            # determine the branch point
1538
            graph = self.branch.repository.get_graph()
4985.3.17 by Vincent Ladeuil
Some cleanup.
1539
            base_rev_id = graph.find_unique_lca(self.branch.last_revision(),
1540
                                                last_rev)
4985.3.15 by Gerard Krol
Now correctly determine the branch point (instead of some lucky guesses)
1541
            base_tree = self.branch.repository.revision_tree(base_rev_id)
1542
4985.3.17 by Vincent Ladeuil
Some cleanup.
1543
            nb_conflicts = merge.merge_inner(self.branch, to_tree, base_tree,
1544
                                             this_tree=self,
5430.7.1 by Rory Yorke
Added --show-base to pull and update (bug 202374).
1545
                                             change_reporter=change_reporter,
1546
                                             show_base=show_base)
4985.3.15 by Gerard Krol
Now correctly determine the branch point (instead of some lucky guesses)
1547
            self.set_last_revision(revision)
1908.6.6 by Robert Collins
Merge updated set_parents api.
1548
            # TODO - dedup parents list with things merged by pull ?
1549
            # reuse the tree we've updated to to set the basis:
1907.5.11 by Matthieu Moy
Simple fixes (deprecation warning, use revision where needed)
1550
            parent_trees = [(revision, to_tree)]
1908.6.6 by Robert Collins
Merge updated set_parents api.
1551
            merges = self.get_parent_ids()[1:]
1552
            # Ideally we ask the tree for the trees here, that way the working
1907.5.12 by Matthieu Moy
Manage InvalidRevisionSpec in update command.
1553
            # tree can decide whether to give us the entire tree or give us a
1908.6.6 by Robert Collins
Merge updated set_parents api.
1554
            # lazy initialised tree. dirstate for instance will have the trees
1555
            # in ram already, whereas a last-revision + basis-inventory tree
1556
            # will not, but also does not need them when setting parents.
1557
            for parent in merges:
1558
                parent_trees.append(
1559
                    (parent, self.branch.repository.revision_tree(parent)))
4985.3.14 by Gerard Krol
Don't compare old_tip to revision, just do the merge.
1560
            if not _mod_revision.is_null(old_tip):
1561
                parent_trees.append(
1562
                    (old_tip, self.branch.repository.revision_tree(old_tip)))
1908.6.6 by Robert Collins
Merge updated set_parents api.
1563
            self.set_parent_trees(parent_trees)
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
1564
            last_rev = parent_trees[0][0]
4985.3.17 by Vincent Ladeuil
Some cleanup.
1565
        return nb_conflicts
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1566
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1567
    def set_conflicts(self, arg):
2206.1.7 by Marius Kruger
* errors
1568
        raise errors.UnsupportedOperation(self.set_conflicts, self)
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
1569
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
1570
    def add_conflicts(self, arg):
2206.1.7 by Marius Kruger
* errors
1571
        raise errors.UnsupportedOperation(self.add_conflicts, self)
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
1572
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1573
    def conflicts(self):
5582.10.47 by Jelmer Vernooij
Move some upgrade tests that rely on bzrdirformat 0.0.4.
1574
        raise NotImplementedError(self.conflicts)
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1575
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
1576
    def walkdirs(self, prefix=""):
2255.2.18 by Robert Collins
Dirstate: all tree_implementation tests passing.
1577
        """Walk the directories of this tree.
1578
2292.1.25 by Marius Kruger
* Add utility method delta.get_changes_as_text to get the output of .show()
1579
        returns a generator which yields items in the form:
2292.1.30 by Marius Kruger
* Minor text fixes.
1580
                ((curren_directory_path, fileid),
2292.1.25 by Marius Kruger
* Add utility method delta.get_changes_as_text to get the output of .show()
1581
                 [(file1_path, file1_name, file1_kind, (lstat), file1_id,
1582
                   file1_kind), ... ])
1583
2255.2.18 by Robert Collins
Dirstate: all tree_implementation tests passing.
1584
        This API returns a generator, which is only valid during the current
1585
        tree transaction - within a single lock_read or lock_write duration.
1586
2292.1.25 by Marius Kruger
* Add utility method delta.get_changes_as_text to get the output of .show()
1587
        If the tree is not locked, it may cause an error to be raised,
1588
        depending on the tree implementation.
2255.2.18 by Robert Collins
Dirstate: all tree_implementation tests passing.
1589
        """
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1590
        disk_top = self.abspath(prefix)
1591
        if disk_top.endswith('/'):
1592
            disk_top = disk_top[:-1]
1593
        top_strip_len = len(disk_top) + 1
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1594
        inventory_iterator = self._walkdirs(prefix)
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1595
        disk_iterator = osutils.walkdirs(disk_top, prefix)
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1596
        try:
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1597
            current_disk = disk_iterator.next()
1598
            disk_finished = False
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1599
        except OSError as e:
2423.2.1 by Alexander Belchenko
Fix for walkdirs in missing dir with Py2.4 @ win32
1600
            if not (e.errno == errno.ENOENT or
1601
                (sys.platform == 'win32' and e.errno == ERROR_PATH_NOT_FOUND)):
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1602
                raise
1603
            current_disk = None
1604
            disk_finished = True
1605
        try:
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1606
            current_inv = inventory_iterator.next()
1607
            inv_finished = False
1608
        except StopIteration:
1609
            current_inv = None
1610
            inv_finished = True
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1611
        while not inv_finished or not disk_finished:
2457.2.3 by Marius Kruger
factor out tuples into better readable variables
1612
            if current_disk:
1613
                ((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
1614
                    cur_disk_dir_content) = current_disk
1615
            else:
1616
                ((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
1617
                    cur_disk_dir_content) = ((None, None), None)
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1618
            if not disk_finished:
1619
                # strip out .bzr dirs
2457.2.3 by Marius Kruger
factor out tuples into better readable variables
1620
                if (cur_disk_dir_path_from_top[top_strip_len:] == '' and
1621
                    len(cur_disk_dir_content) > 0):
1622
                    # osutils.walkdirs can be made nicer -
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1623
                    # yield the path-from-prefix rather than the pathjoined
1624
                    # value.
2457.2.3 by Marius Kruger
factor out tuples into better readable variables
1625
                    bzrdir_loc = bisect_left(cur_disk_dir_content,
1626
                        ('.bzr', '.bzr'))
3719.1.1 by Vincent Ladeuil
Fix bug #272648
1627
                    if (bzrdir_loc < len(cur_disk_dir_content)
4324.5.1 by Jelmer Vernooij
Use utility function to check for control filename rather than assuming it is '.bzr.'
1628
                        and self.bzrdir.is_control_filename(
1629
                            cur_disk_dir_content[bzrdir_loc][0])):
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1630
                        # we dont yield the contents of, or, .bzr itself.
2457.2.3 by Marius Kruger
factor out tuples into better readable variables
1631
                        del cur_disk_dir_content[bzrdir_loc]
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1632
            if inv_finished:
1633
                # everything is unknown
1852.15.12 by Robert Collins
WorkingTree.walkdirs handling of changing file kinds, and multi-directory with missing and unknown ordering bugfix.
1634
                direction = 1
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1635
            elif disk_finished:
1636
                # everything is missing
1852.15.12 by Robert Collins
WorkingTree.walkdirs handling of changing file kinds, and multi-directory with missing and unknown ordering bugfix.
1637
                direction = -1
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1638
            else:
2457.2.3 by Marius Kruger
factor out tuples into better readable variables
1639
                direction = cmp(current_inv[0][0], cur_disk_dir_relpath)
1852.15.12 by Robert Collins
WorkingTree.walkdirs handling of changing file kinds, and multi-directory with missing and unknown ordering bugfix.
1640
            if direction > 0:
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1641
                # disk is before inventory - unknown
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1642
                dirblock = [(relpath, basename, kind, stat, None, None) for
2457.2.7 by Marius Kruger
extract method as per review request
1643
                    relpath, basename, kind, stat, top_path in
2457.2.3 by Marius Kruger
factor out tuples into better readable variables
1644
                    cur_disk_dir_content]
1645
                yield (cur_disk_dir_relpath, None), dirblock
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1646
                try:
1647
                    current_disk = disk_iterator.next()
1648
                except StopIteration:
1649
                    disk_finished = True
1852.15.12 by Robert Collins
WorkingTree.walkdirs handling of changing file kinds, and multi-directory with missing and unknown ordering bugfix.
1650
            elif direction < 0:
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1651
                # inventory is before disk - missing.
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1652
                dirblock = [(relpath, basename, 'unknown', None, fileid, kind)
2457.2.7 by Marius Kruger
extract method as per review request
1653
                    for relpath, basename, dkind, stat, fileid, kind in
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1654
                    current_inv[1]]
1655
                yield (current_inv[0][0], current_inv[0][1]), dirblock
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1656
                try:
1657
                    current_inv = inventory_iterator.next()
1658
                except StopIteration:
1659
                    inv_finished = True
1660
            else:
1661
                # versioned present directory
1662
                # merge the inventory and disk data together
1663
                dirblock = []
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1664
                for relpath, subiterator in itertools.groupby(sorted(
2457.2.7 by Marius Kruger
extract method as per review request
1665
                    current_inv[1] + cur_disk_dir_content,
2457.2.3 by Marius Kruger
factor out tuples into better readable variables
1666
                    key=operator.itemgetter(0)), operator.itemgetter(1)):
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1667
                    path_elements = list(subiterator)
1668
                    if len(path_elements) == 2:
1852.15.12 by Robert Collins
WorkingTree.walkdirs handling of changing file kinds, and multi-directory with missing and unknown ordering bugfix.
1669
                        inv_row, disk_row = path_elements
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1670
                        # versioned, present file
1852.15.12 by Robert Collins
WorkingTree.walkdirs handling of changing file kinds, and multi-directory with missing and unknown ordering bugfix.
1671
                        dirblock.append((inv_row[0],
1672
                            inv_row[1], disk_row[2],
1673
                            disk_row[3], inv_row[4],
1674
                            inv_row[5]))
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1675
                    elif len(path_elements[0]) == 5:
1676
                        # unknown disk file
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1677
                        dirblock.append((path_elements[0][0],
1678
                            path_elements[0][1], path_elements[0][2],
1679
                            path_elements[0][3], None, None))
1680
                    elif len(path_elements[0]) == 6:
1681
                        # versioned, absent file.
1682
                        dirblock.append((path_elements[0][0],
1683
                            path_elements[0][1], 'unknown', None,
1684
                            path_elements[0][4], path_elements[0][5]))
1685
                    else:
1686
                        raise NotImplementedError('unreachable code')
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1687
                yield current_inv[0], dirblock
1688
                try:
1689
                    current_inv = inventory_iterator.next()
1690
                except StopIteration:
1691
                    inv_finished = True
1692
                try:
1693
                    current_disk = disk_iterator.next()
1694
                except StopIteration:
1695
                    disk_finished = True
1696
1697
    def _walkdirs(self, prefix=""):
2292.1.25 by Marius Kruger
* Add utility method delta.get_changes_as_text to get the output of .show()
1698
        """Walk the directories of this tree.
1699
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
1700
        :param prefix: is used as the directrory to start with.
1701
        :returns: a generator which yields items in the form::
1702
1703
            ((curren_directory_path, fileid),
1704
             [(file1_path, file1_name, file1_kind, None, file1_id,
1705
               file1_kind), ... ])
2292.1.25 by Marius Kruger
* Add utility method delta.get_changes_as_text to get the output of .show()
1706
        """
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1707
        raise NotImplementedError(self._walkdirs)
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
1708
2120.7.2 by Aaron Bentley
Move autoresolve functionality to workingtree
1709
    @needs_tree_write_lock
1710
    def auto_resolve(self):
1711
        """Automatically resolve text conflicts according to contents.
1712
1713
        Only text conflicts are auto_resolvable. Files with no conflict markers
1714
        are considered 'resolved', because bzr always puts conflict markers
1715
        into files that have text conflicts.  The corresponding .THIS .BASE and
1716
        .OTHER files are deleted, as per 'resolve'.
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
1717
2120.7.2 by Aaron Bentley
Move autoresolve functionality to workingtree
1718
        :return: a tuple of ConflictLists: (un_resolved, resolved).
1719
        """
1720
        un_resolved = _mod_conflicts.ConflictList()
1721
        resolved = _mod_conflicts.ConflictList()
1722
        conflict_re = re.compile('^(<{7}|={7}|>{7})')
1723
        for conflict in self.conflicts():
2120.7.3 by Aaron Bentley
Update resolve command to automatically mark conflicts as resolved
1724
            if (conflict.typestring != 'text conflict' or
1725
                self.kind(conflict.file_id) != 'file'):
2120.7.2 by Aaron Bentley
Move autoresolve functionality to workingtree
1726
                un_resolved.append(conflict)
1727
                continue
1728
            my_file = open(self.id2abspath(conflict.file_id), 'rb')
1729
            try:
1730
                for line in my_file:
1731
                    if conflict_re.search(line):
1732
                        un_resolved.append(conflict)
1733
                        break
1734
                else:
1735
                    resolved.append(conflict)
1736
            finally:
1737
                my_file.close()
1738
        resolved.remove_files(self)
1739
        self.set_conflicts(un_resolved)
1740
        return un_resolved, resolved
1741
2371.2.1 by John Arbash Meinel
Update DirState._validate() to detect rename errors.
1742
    def _validate(self):
1743
        """Validate internal structures.
1744
1745
        This is meant mostly for the test suite. To give it a chance to detect
1746
        corruption after actions have occurred. The default implementation is a
1747
        just a no-op.
1748
1749
        :return: None. An exception should be raised if there is an error.
1750
        """
1751
        return
1752
5630.2.3 by John Arbash Meinel
Looks like it was a stale experimental .pyd file causing trouble. Tests pass again now.
1753
    def check_state(self):
1754
        """Check that the working state is/isn't valid."""
5850.1.2 by Jelmer Vernooij
Move inventory tree specific check implementation to InventoryWorkingTree.
1755
        raise NotImplementedError(self.check_state)
5630.2.4 by John Arbash Meinel
Basically works in the case where the dirstate isn't corrupted.
1756
1757
    def reset_state(self, revision_ids=None):
1758
        """Reset the state of the working tree.
1759
1760
        This does a hard-reset to a last-known-good state. This is a way to
1761
        fix if something got corrupted (like the .bzr/checkout/dirstate file)
1762
        """
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1763
        raise NotImplementedError(self.reset_state)
5630.2.2 by John Arbash Meinel
Start fleshing out the design. Something weird is causing my tests to all fail.
1764
3398.1.24 by Ian Clatworthy
make iter_search_rules a tree method
1765
    def _get_rules_searcher(self, default_searcher):
1766
        """See Tree._get_rules_searcher."""
1767
        if self._rules_searcher is None:
1768
            self._rules_searcher = super(WorkingTree,
1769
                self)._get_rules_searcher(default_searcher)
1770
        return self._rules_searcher
1771
0.12.68 by Aaron Bentley
Update docs, move items to proper files.
1772
    def get_shelf_manager(self):
1773
        """Return the ShelfManager for this WorkingTree."""
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1774
        from .shelf import ShelfManager
0.12.68 by Aaron Bentley
Update docs, move items to proper files.
1775
        return ShelfManager(self, self._transport)
1776
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1777
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1778
class InventoryWorkingTree(WorkingTree,
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1779
        mutabletree.MutableInventoryTree):
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1780
    """Base class for working trees that are inventory-oriented.
1781
1782
    The inventory is held in the `Branch` working-inventory, and the
1783
    files are in a directory on disk.
1784
1785
    It is possible for a `WorkingTree` to have a filename which is
1786
    not listed in the Inventory and vice versa.
1787
    """
1788
1789
    def __init__(self, basedir='.',
6313.1.4 by Jelmer Vernooij
Fix tests.
1790
                 branch=DEPRECATED_PARAMETER,
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1791
                 _inventory=None,
1792
                 _control_files=None,
1793
                 _internal=False,
1794
                 _format=None,
1795
                 _bzrdir=None):
1796
        """Construct a InventoryWorkingTree instance. This is not a public API.
1797
1798
        :param branch: A branch to override probing for the branch.
1799
        """
1800
        super(InventoryWorkingTree, self).__init__(basedir=basedir,
6313.1.4 by Jelmer Vernooij
Fix tests.
1801
            branch=branch, _transport=_control_files._transport,
6313.1.1 by Jelmer Vernooij
Move bzr-specific functionality to InventoryWorkingTree.
1802
            _internal=_internal, _format=_format, _bzrdir=_bzrdir)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1803
6313.1.2 by Jelmer Vernooij
Fix tests.
1804
        self._control_files = _control_files
6110.4.1 by Jelmer Vernooij
Move hashcache to InventoryWorkingTree.
1805
        self._detect_case_handling()
1806
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1807
        if _inventory is None:
1808
            # This will be acquired on lock_read() or lock_write()
1809
            self._inventory_is_modified = False
1810
            self._inventory = None
1811
        else:
1812
            # the caller of __init__ has provided an inventory,
1813
            # we assume they know what they are doing - as its only
1814
            # the Format factory and creation methods that are
1815
            # permitted to do this.
1816
            self._set_inventory(_inventory, dirty=False)
1817
1818
    def _set_inventory(self, inv, dirty):
1819
        """Set the internal cached inventory.
1820
1821
        :param inv: The inventory to set.
1822
        :param dirty: A boolean indicating whether the inventory is the same
1823
            logical inventory as whats on disk. If True the inventory is not
1824
            the same and should be written to disk or data will be lost, if
1825
            False then the inventory is the same as that on disk and any
1826
            serialisation would be unneeded overhead.
1827
        """
1828
        self._inventory = inv
1829
        self._inventory_is_modified = dirty
1830
6110.4.1 by Jelmer Vernooij
Move hashcache to InventoryWorkingTree.
1831
    def _detect_case_handling(self):
1832
        wt_trans = self.bzrdir.get_workingtree_transport(None)
1833
        try:
1834
            wt_trans.stat(self._format.case_sensitive_filename)
1835
        except errors.NoSuchFile:
1836
            self.case_sensitive = True
1837
        else:
1838
            self.case_sensitive = False
1839
1840
        self._setup_directory_is_tree_reference()
1841
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1842
    def _serialize(self, inventory, out_file):
1843
        xml5.serializer_v5.write_inventory(self._inventory, out_file,
1844
            working=True)
1845
1846
    def _deserialize(selt, in_file):
1847
        return xml5.serializer_v5.read_inventory(in_file)
1848
6313.1.1 by Jelmer Vernooij
Move bzr-specific functionality to InventoryWorkingTree.
1849
    def break_lock(self):
1850
        """Break a lock if one is present from another instance.
1851
1852
        Uses the ui factory to ask for confirmation if the lock may be from
1853
        an active process.
1854
1855
        This will probe the repository for its lock as well.
1856
        """
1857
        self._control_files.break_lock()
1858
        self.branch.break_lock()
1859
1860
    def is_locked(self):
1861
        return self._control_files.is_locked()
1862
1863
    def _must_be_locked(self):
1864
        if not self.is_locked():
1865
            raise errors.ObjectNotLocked(self)
1866
1867
    def lock_read(self):
1868
        """Lock the tree for reading.
1869
1870
        This also locks the branch, and can be unlocked via self.unlock().
1871
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1872
        :return: A breezy.lock.LogicalLockResult.
6313.1.1 by Jelmer Vernooij
Move bzr-specific functionality to InventoryWorkingTree.
1873
        """
1874
        if not self.is_locked():
1875
            self._reset_data()
1876
        self.branch.lock_read()
1877
        try:
1878
            self._control_files.lock_read()
1879
            return LogicalLockResult(self.unlock)
1880
        except:
1881
            self.branch.unlock()
1882
            raise
1883
1884
    def lock_tree_write(self):
1885
        """See MutableTree.lock_tree_write, and WorkingTree.unlock.
1886
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1887
        :return: A breezy.lock.LogicalLockResult.
6313.1.1 by Jelmer Vernooij
Move bzr-specific functionality to InventoryWorkingTree.
1888
        """
1889
        if not self.is_locked():
1890
            self._reset_data()
1891
        self.branch.lock_read()
1892
        try:
1893
            self._control_files.lock_write()
1894
            return LogicalLockResult(self.unlock)
1895
        except:
1896
            self.branch.unlock()
1897
            raise
1898
1899
    def lock_write(self):
1900
        """See MutableTree.lock_write, and WorkingTree.unlock.
1901
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1902
        :return: A breezy.lock.LogicalLockResult.
6313.1.1 by Jelmer Vernooij
Move bzr-specific functionality to InventoryWorkingTree.
1903
        """
1904
        if not self.is_locked():
1905
            self._reset_data()
1906
        self.branch.lock_write()
1907
        try:
1908
            self._control_files.lock_write()
1909
            return LogicalLockResult(self.unlock)
1910
        except:
1911
            self.branch.unlock()
1912
            raise
1913
1914
    def get_physical_lock_status(self):
1915
        return self._control_files.get_physical_lock_status()
1916
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1917
    @needs_tree_write_lock
1918
    def _write_inventory(self, inv):
1919
        """Write inventory as the current inventory."""
1920
        self._set_inventory(inv, dirty=True)
1921
        self.flush()
1922
1923
    # XXX: This method should be deprecated in favour of taking in a proper
1924
    # new Inventory object.
1925
    @needs_tree_write_lock
1926
    def set_inventory(self, new_inventory_list):
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1927
        from .inventory import (
1928
            Inventory,
1929
            InventoryDirectory,
1930
            InventoryFile,
1931
            InventoryLink)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1932
        inv = Inventory(self.get_root_id())
1933
        for path, file_id, parent, kind in new_inventory_list:
1934
            name = os.path.basename(path)
1935
            if name == "":
1936
                continue
1937
            # fixme, there should be a factory function inv,add_??
1938
            if kind == 'directory':
1939
                inv.add(InventoryDirectory(file_id, name, parent))
1940
            elif kind == 'file':
1941
                inv.add(InventoryFile(file_id, name, parent))
1942
            elif kind == 'symlink':
1943
                inv.add(InventoryLink(file_id, name, parent))
1944
            else:
1945
                raise errors.BzrError("unknown kind %r" % kind)
1946
        self._write_inventory(inv)
1947
1948
    def _write_basis_inventory(self, xml):
1949
        """Write the basis inventory XML to the basis-inventory file"""
1950
        path = self._basis_inventory_name()
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
1951
        sio = BytesIO(xml)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
1952
        self._transport.put_file(path, sio,
1953
            mode=self.bzrdir._get_file_mode())
1954
1955
    def _reset_data(self):
1956
        """Reset transient data that cannot be revalidated."""
1957
        self._inventory_is_modified = False
1958
        f = self._transport.get('inventory')
1959
        try:
1960
            result = self._deserialize(f)
1961
        finally:
1962
            f.close()
1963
        self._set_inventory(result, dirty=False)
1964
1965
    def _set_root_id(self, file_id):
1966
        """Set the root id for this tree, in a format specific manner.
1967
1968
        :param file_id: The file id to assign to the root. It must not be
1969
            present in the current inventory or an error will occur. It must
1970
            not be None, but rather a valid file id.
1971
        """
1972
        inv = self._inventory
1973
        orig_root_id = inv.root.file_id
1974
        # TODO: it might be nice to exit early if there was nothing
1975
        # to do, saving us from trigger a sync on unlock.
1976
        self._inventory_is_modified = True
1977
        # we preserve the root inventory entry object, but
1978
        # unlinkit from the byid index
1979
        del inv._byid[inv.root.file_id]
1980
        inv.root.file_id = file_id
1981
        # and link it into the index with the new changed id.
1982
        inv._byid[inv.root.file_id] = inv.root
1983
        # and finally update all children to reference the new id.
1984
        # XXX: this should be safe to just look at the root.children
1985
        # list, not the WHOLE INVENTORY.
1986
        for fid in inv:
1987
            entry = inv[fid]
1988
            if entry.parent_id == orig_root_id:
1989
                entry.parent_id = inv.root.file_id
1990
5807.1.1 by Jelmer Vernooij
Move inventory-specific method to InventoryWorkingTree.
1991
    @needs_tree_write_lock
1992
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
1993
        """See MutableTree.set_parent_trees."""
1994
        parent_ids = [rev for (rev, tree) in parents_list]
1995
        for revision_id in parent_ids:
1996
            _mod_revision.check_not_reserved_id(revision_id)
1997
1998
        self._check_parents_for_ghosts(parent_ids,
1999
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
2000
2001
        parent_ids = self._filter_parent_ids_by_ancestry(parent_ids)
2002
2003
        if len(parent_ids) == 0:
2004
            leftmost_parent_id = _mod_revision.NULL_REVISION
2005
            leftmost_parent_tree = None
2006
        else:
2007
            leftmost_parent_id, leftmost_parent_tree = parents_list[0]
2008
2009
        if self._change_last_revision(leftmost_parent_id):
2010
            if leftmost_parent_tree is None:
2011
                # If we don't have a tree, fall back to reading the
2012
                # parent tree from the repository.
2013
                self._cache_basis_inventory(leftmost_parent_id)
2014
            else:
6405.2.7 by Jelmer Vernooij
Fix more tests.
2015
                inv = leftmost_parent_tree.root_inventory
5807.1.1 by Jelmer Vernooij
Move inventory-specific method to InventoryWorkingTree.
2016
                xml = self._create_basis_xml_from_inventory(
2017
                                        leftmost_parent_id, inv)
2018
                self._write_basis_inventory(xml)
2019
        self._set_merges_from_parent_ids(parent_ids)
2020
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2021
    def _cache_basis_inventory(self, new_revision):
2022
        """Cache new_revision as the basis inventory."""
2023
        # TODO: this should allow the ready-to-use inventory to be passed in,
2024
        # as commit already has that ready-to-use [while the format is the
2025
        # same, that is].
2026
        try:
2027
            # this double handles the inventory - unpack and repack -
2028
            # but is easier to understand. We can/should put a conditional
2029
            # in here based on whether the inventory is in the latest format
2030
            # - perhaps we should repack all inventories on a repository
2031
            # upgrade ?
2032
            # the fast path is to copy the raw xml from the repository. If the
2033
            # xml contains 'revision_id="', then we assume the right
2034
            # revision_id is set. We must check for this full string, because a
2035
            # root node id can legitimately look like 'revision_id' but cannot
2036
            # contain a '"'.
2037
            xml = self.branch.repository._get_inventory_xml(new_revision)
2038
            firstline = xml.split('\n', 1)[0]
2039
            if (not 'revision_id="' in firstline or
2040
                'format="7"' not in firstline):
2041
                inv = self.branch.repository._serializer.read_inventory_from_string(
2042
                    xml, new_revision)
2043
                xml = self._create_basis_xml_from_inventory(new_revision, inv)
2044
            self._write_basis_inventory(xml)
2045
        except (errors.NoSuchRevision, errors.RevisionNotPresent):
2046
            pass
2047
2048
    def _basis_inventory_name(self):
2049
        return 'basis-inventory-cache'
2050
2051
    def _create_basis_xml_from_inventory(self, revision_id, inventory):
2052
        """Create the text that will be saved in basis-inventory"""
2053
        inventory.revision_id = revision_id
2054
        return xml7.serializer_v7.write_inventory_to_string(inventory)
2055
5816.5.1 by Jelmer Vernooij
Move WorkingTree3 to bzrlib.workingtree_3.
2056
    @needs_tree_write_lock
2057
    def set_conflicts(self, conflicts):
2058
        self._put_rio('conflicts', conflicts.to_stanzas(),
2059
                      CONFLICT_HEADER_1)
2060
2061
    @needs_tree_write_lock
2062
    def add_conflicts(self, new_conflicts):
2063
        conflict_set = set(self.conflicts())
2064
        conflict_set.update(set(list(new_conflicts)))
2065
        self.set_conflicts(_mod_conflicts.ConflictList(sorted(conflict_set,
2066
                                       key=_mod_conflicts.Conflict.sort_key)))
2067
2068
    @needs_read_lock
2069
    def conflicts(self):
2070
        try:
2071
            confile = self._transport.get('conflicts')
2072
        except errors.NoSuchFile:
2073
            return _mod_conflicts.ConflictList()
2074
        try:
2075
            try:
2076
                if confile.next() != CONFLICT_HEADER_1 + '\n':
2077
                    raise errors.ConflictFormatError()
2078
            except StopIteration:
2079
                raise errors.ConflictFormatError()
2080
            reader = _mod_rio.RioReader(confile)
2081
            return _mod_conflicts.ConflictList.from_stanzas(reader)
2082
        finally:
2083
            confile.close()
2084
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2085
    def read_basis_inventory(self):
2086
        """Read the cached basis inventory."""
2087
        path = self._basis_inventory_name()
2088
        return self._transport.get_bytes(path)
2089
2090
    @needs_read_lock
2091
    def read_working_inventory(self):
2092
        """Read the working inventory.
2093
2094
        :raises errors.InventoryModified: read_working_inventory will fail
2095
            when the current in memory inventory has been modified.
2096
        """
2097
        # conceptually this should be an implementation detail of the tree.
2098
        # XXX: Deprecate this.
2099
        # ElementTree does its own conversion from UTF-8, so open in
2100
        # binary.
2101
        if self._inventory_is_modified:
2102
            raise errors.InventoryModified(self)
2103
        f = self._transport.get('inventory')
2104
        try:
2105
            result = self._deserialize(f)
2106
        finally:
2107
            f.close()
2108
        self._set_inventory(result, dirty=False)
2109
        return result
2110
2111
    @needs_read_lock
2112
    def get_root_id(self):
2113
        """Return the id of this trees root"""
2114
        return self._inventory.root.file_id
2115
2116
    def has_id(self, file_id):
2117
        # files that have been deleted are excluded
6405.2.3 by Jelmer Vernooij
Use unpack functions.
2118
        inv, inv_file_id = self._unpack_file_id(file_id)
2119
        if not inv.has_id(inv_file_id):
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2120
            return False
6405.2.3 by Jelmer Vernooij
Use unpack functions.
2121
        path = inv.id2path(inv_file_id)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2122
        return osutils.lexists(self.abspath(path))
2123
2124
    def has_or_had_id(self, file_id):
6468.2.3 by Jelmer Vernooij
Use Tree.get_root_id.
2125
        if file_id == self.get_root_id():
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2126
            return True
6405.2.3 by Jelmer Vernooij
Use unpack functions.
2127
        inv, inv_file_id = self._unpack_file_id(file_id)
2128
        return inv.has_id(inv_file_id)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2129
6405.2.6 by Jelmer Vernooij
Lots of test fixes.
2130
    def all_file_ids(self):
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2131
        """Iterate through file_ids for this tree.
2132
2133
        file_ids are in a WorkingTree if they are in the working inventory
2134
        and the working file exists.
2135
        """
6405.2.6 by Jelmer Vernooij
Lots of test fixes.
2136
        ret = set()
2137
        for path, ie in self.iter_entries_by_dir():
6405.2.8 by Jelmer Vernooij
Fix remaining (?) tests.
2138
            ret.add(ie.file_id)
6405.2.6 by Jelmer Vernooij
Lots of test fixes.
2139
        return ret
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2140
2141
    @needs_tree_write_lock
2142
    def set_last_revision(self, new_revision):
2143
        """Change the last revision in the working tree."""
2144
        if self._change_last_revision(new_revision):
2145
            self._cache_basis_inventory(new_revision)
2146
5850.1.2 by Jelmer Vernooij
Move inventory tree specific check implementation to InventoryWorkingTree.
2147
    def _get_check_refs(self):
2148
        """Return the references needed to perform a check of this tree.
2149
        
2150
        The default implementation returns no refs, and is only suitable for
2151
        trees that have no local caching and can commit on ghosts at any time.
2152
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2153
        :seealso: breezy.check for details about check_refs.
5850.1.2 by Jelmer Vernooij
Move inventory tree specific check implementation to InventoryWorkingTree.
2154
        """
2155
        return []
2156
2157
    @needs_read_lock
2158
    def _check(self, references):
2159
        """Check the tree for consistency.
2160
2161
        :param references: A dict with keys matching the items returned by
2162
            self._get_check_refs(), and values from looking those keys up in
2163
            the repository.
2164
        """
2165
        tree_basis = self.basis_tree()
2166
        tree_basis.lock_read()
2167
        try:
2168
            repo_basis = references[('trees', self.last_revision())]
2169
            if len(list(repo_basis.iter_changes(tree_basis))) > 0:
2170
                raise errors.BzrCheckError(
2171
                    "Mismatched basis inventory content.")
2172
            self._validate()
2173
        finally:
2174
            tree_basis.unlock()
2175
2176
    @needs_read_lock
2177
    def check_state(self):
2178
        """Check that the working state is/isn't valid."""
2179
        check_refs = self._get_check_refs()
2180
        refs = {}
2181
        for ref in check_refs:
2182
            kind, value = ref
2183
            if kind == 'trees':
2184
                refs[ref] = self.branch.repository.revision_tree(value)
2185
        self._check(refs)
2186
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2187
    @needs_tree_write_lock
2188
    def reset_state(self, revision_ids=None):
2189
        """Reset the state of the working tree.
2190
2191
        This does a hard-reset to a last-known-good state. This is a way to
2192
        fix if something got corrupted (like the .bzr/checkout/dirstate file)
2193
        """
2194
        if revision_ids is None:
2195
            revision_ids = self.get_parent_ids()
2196
        if not revision_ids:
2197
            rt = self.branch.repository.revision_tree(
2198
                _mod_revision.NULL_REVISION)
2199
        else:
2200
            rt = self.branch.repository.revision_tree(revision_ids[0])
6405.2.6 by Jelmer Vernooij
Lots of test fixes.
2201
        self._write_inventory(rt.root_inventory)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2202
        self.set_parent_ids(revision_ids)
2203
2204
    def flush(self):
2205
        """Write the in memory inventory to disk."""
2206
        # TODO: Maybe this should only write on dirty ?
2207
        if self._control_files._lock_mode != 'w':
2208
            raise errors.NotWriteLocked(self)
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
2209
        sio = BytesIO()
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2210
        self._serialize(self._inventory, sio)
2211
        sio.seek(0)
2212
        self._transport.put_file('inventory', sio,
2213
            mode=self.bzrdir._get_file_mode())
2214
        self._inventory_is_modified = False
2215
2216
    def get_file_mtime(self, file_id, path=None):
2217
        """See Tree.get_file_mtime."""
2218
        if not path:
6405.2.2 by Jelmer Vernooij
Use _path2inv_file_id.
2219
            path = self.id2path(file_id)
6153.1.1 by Jelmer Vernooij
Raise FileTimestampUnavailable.
2220
        try:
2221
            return os.lstat(self.abspath(path)).st_mtime
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2222
        except OSError as e:
6153.1.1 by Jelmer Vernooij
Raise FileTimestampUnavailable.
2223
            if e.errno == errno.ENOENT:
2224
                raise errors.FileTimestampUnavailable(path)
2225
            raise
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2226
2227
    def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
6405.2.1 by Jelmer Vernooij
Allow passing in tuples as file ids in various places.
2228
        inv, file_id = self._path2inv_file_id(path)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2229
        if file_id is None:
2230
            # For unversioned files on win32, we just assume they are not
2231
            # executable
2232
            return False
6405.2.1 by Jelmer Vernooij
Allow passing in tuples as file ids in various places.
2233
        return inv[file_id].executable
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2234
2235
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
2236
        mode = stat_result.st_mode
2237
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
2238
6379.7.1 by Jelmer Vernooij
Add and use WorkingTree._supports_executable.
2239
    def is_executable(self, file_id, path=None):
2240
        if not self._supports_executable():
6405.2.1 by Jelmer Vernooij
Allow passing in tuples as file ids in various places.
2241
            inv, inv_file_id = self._unpack_file_id(file_id)
2242
            return inv[inv_file_id].executable
6379.7.1 by Jelmer Vernooij
Add and use WorkingTree._supports_executable.
2243
        else:
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2244
            if not path:
2245
                path = self.id2path(file_id)
2246
            mode = os.lstat(self.abspath(path)).st_mode
2247
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
2248
6379.7.1 by Jelmer Vernooij
Add and use WorkingTree._supports_executable.
2249
    def _is_executable_from_path_and_stat(self, path, stat_result):
2250
        if not self._supports_executable():
2251
            return self._is_executable_from_path_and_stat_from_basis(path, stat_result)
2252
        else:
2253
            return self._is_executable_from_path_and_stat_from_stat(path, stat_result)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2254
2255
    @needs_tree_write_lock
2256
    def _add(self, files, ids, kinds):
2257
        """See MutableTree._add."""
2258
        # TODO: Re-adding a file that is removed in the working copy
2259
        # should probably put it back with the previous ID.
2260
        # the read and write working inventory should not occur in this
2261
        # function - they should be part of lock_write and unlock.
6405.2.5 by Jelmer Vernooij
Add root_inventory.
2262
        # FIXME: nested trees
2263
        inv = self.root_inventory
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2264
        for f, file_id, kind in zip(files, ids, kinds):
2265
            if file_id is None:
2266
                inv.add_path(f, kind=kind)
2267
            else:
2268
                inv.add_path(f, kind=kind, file_id=file_id)
2269
            self._inventory_is_modified = True
2270
2271
    def revision_tree(self, revision_id):
2272
        """See WorkingTree.revision_id."""
2273
        if revision_id == self.last_revision():
2274
            try:
2275
                xml = self.read_basis_inventory()
2276
            except errors.NoSuchFile:
2277
                pass
2278
            else:
2279
                try:
2280
                    inv = xml7.serializer_v7.read_inventory_from_string(xml)
2281
                    # dont use the repository revision_tree api because we want
2282
                    # to supply the inventory.
2283
                    if inv.revision_id == revision_id:
5793.2.2 by Jelmer Vernooij
Split inventory-specific code out of RevisionTree into InventoryRevisionTree.
2284
                        return revisiontree.InventoryRevisionTree(
2285
                            self.branch.repository, inv, revision_id)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2286
                except errors.BadInventoryFormat:
2287
                    pass
2288
        # raise if there was no inventory, or if we read the wrong inventory.
2289
        raise errors.NoSuchRevisionInTree(self, revision_id)
2290
2291
    @needs_read_lock
2292
    def annotate_iter(self, file_id, default_revision=CURRENT_REVISION):
2293
        """See Tree.annotate_iter
2294
2295
        This implementation will use the basis tree implementation if possible.
2296
        Lines not in the basis are attributed to CURRENT_REVISION
2297
2298
        If there are pending merges, lines added by those merges will be
2299
        incorrectly attributed to CURRENT_REVISION (but after committing, the
2300
        attribution will be correct).
2301
        """
2302
        maybe_file_parent_keys = []
2303
        for parent_id in self.get_parent_ids():
2304
            try:
2305
                parent_tree = self.revision_tree(parent_id)
2306
            except errors.NoSuchRevisionInTree:
2307
                parent_tree = self.branch.repository.revision_tree(parent_id)
2308
            parent_tree.lock_read()
2309
            try:
6405.2.7 by Jelmer Vernooij
Fix more tests.
2310
                try:
2311
                    kind = parent_tree.kind(file_id)
2312
                except errors.NoSuchId:
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2313
                    continue
6405.2.7 by Jelmer Vernooij
Fix more tests.
2314
                if kind != 'file':
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2315
                    # Note: this is slightly unnecessary, because symlinks and
2316
                    # directories have a "text" which is the empty text, and we
2317
                    # know that won't mess up annotations. But it seems cleaner
2318
                    continue
6405.2.7 by Jelmer Vernooij
Fix more tests.
2319
                parent_text_key = (
2320
                    file_id, parent_tree.get_file_revision(file_id))
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2321
                if parent_text_key not in maybe_file_parent_keys:
2322
                    maybe_file_parent_keys.append(parent_text_key)
2323
            finally:
2324
                parent_tree.unlock()
2325
        graph = _mod_graph.Graph(self.branch.repository.texts)
2326
        heads = graph.heads(maybe_file_parent_keys)
2327
        file_parent_keys = []
2328
        for key in maybe_file_parent_keys:
2329
            if key in heads:
2330
                file_parent_keys.append(key)
2331
2332
        # Now we have the parents of this content
2333
        annotator = self.branch.repository.texts.get_annotator()
2334
        text = self.get_file_text(file_id)
2335
        this_key =(file_id, default_revision)
2336
        annotator.add_special_text(this_key, file_parent_keys, text)
2337
        annotations = [(key[-1], line)
2338
                       for key, line in annotator.annotate_flat(this_key)]
2339
        return annotations
2340
6313.1.1 by Jelmer Vernooij
Move bzr-specific functionality to InventoryWorkingTree.
2341
    def _put_rio(self, filename, stanzas, header):
2342
        self._must_be_locked()
2343
        my_file = _mod_rio.rio_file(stanzas, header)
2344
        self._transport.put_file(filename, my_file,
2345
            mode=self.bzrdir._get_file_mode())
2346
2347
    @needs_tree_write_lock
2348
    def set_merge_modified(self, modified_hashes):
2349
        def iter_stanzas():
2350
            for file_id, hash in modified_hashes.iteritems():
2351
                yield _mod_rio.Stanza(file_id=file_id.decode('utf8'),
2352
                    hash=hash)
2353
        self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
2354
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2355
    @needs_read_lock
2356
    def merge_modified(self):
2357
        """Return a dictionary of files modified by a merge.
2358
2359
        The list is initialized by WorkingTree.set_merge_modified, which is
2360
        typically called after we make some automatic updates to the tree
2361
        because of a merge.
2362
2363
        This returns a map of file_id->sha1, containing only files which are
2364
        still in the working inventory and have that text hash.
2365
        """
2366
        try:
2367
            hashfile = self._transport.get('merge-hashes')
2368
        except errors.NoSuchFile:
2369
            return {}
2370
        try:
2371
            merge_hashes = {}
2372
            try:
2373
                if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
2374
                    raise errors.MergeModifiedFormatError()
2375
            except StopIteration:
2376
                raise errors.MergeModifiedFormatError()
2377
            for s in _mod_rio.RioReader(hashfile):
2378
                # RioReader reads in Unicode, so convert file_ids back to utf8
2379
                file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
6405.2.2 by Jelmer Vernooij
Use _path2inv_file_id.
2380
                if not self.has_id(file_id):
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2381
                    continue
2382
                text_hash = s.get("hash")
2383
                if text_hash == self.get_file_sha1(file_id):
2384
                    merge_hashes[file_id] = text_hash
2385
            return merge_hashes
2386
        finally:
2387
            hashfile.close()
2388
2389
    @needs_write_lock
2390
    def subsume(self, other_tree):
2391
        def add_children(inventory, entry):
2392
            for child_entry in entry.children.values():
2393
                inventory._byid[child_entry.file_id] = child_entry
2394
                if child_entry.kind == 'directory':
2395
                    add_children(inventory, child_entry)
2396
        if other_tree.get_root_id() == self.get_root_id():
2397
            raise errors.BadSubsumeSource(self, other_tree,
2398
                                          'Trees have the same root')
2399
        try:
2400
            other_tree_path = self.relpath(other_tree.basedir)
2401
        except errors.PathNotChild:
2402
            raise errors.BadSubsumeSource(self, other_tree,
2403
                'Tree is not contained by the other')
2404
        new_root_parent = self.path2id(osutils.dirname(other_tree_path))
2405
        if new_root_parent is None:
2406
            raise errors.BadSubsumeSource(self, other_tree,
2407
                'Parent directory is not versioned.')
2408
        # We need to ensure that the result of a fetch will have a
2409
        # versionedfile for the other_tree root, and only fetching into
2410
        # RepositoryKnit2 guarantees that.
2411
        if not self.branch.repository.supports_rich_root():
2412
            raise errors.SubsumeTargetNeedsUpgrade(other_tree)
2413
        other_tree.lock_tree_write()
2414
        try:
2415
            new_parents = other_tree.get_parent_ids()
6405.2.10 by Jelmer Vernooij
Fix more tests.
2416
            other_root = other_tree.root_inventory.root
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2417
            other_root.parent_id = new_root_parent
2418
            other_root.name = osutils.basename(other_tree_path)
6405.2.10 by Jelmer Vernooij
Fix more tests.
2419
            self.root_inventory.add(other_root)
2420
            add_children(self.root_inventory, other_root)
2421
            self._write_inventory(self.root_inventory)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2422
            # normally we don't want to fetch whole repositories, but i think
2423
            # here we really do want to consolidate the whole thing.
2424
            for parent_id in other_tree.get_parent_ids():
2425
                self.branch.fetch(other_tree.branch, parent_id)
2426
                self.add_parent_tree_id(parent_id)
2427
        finally:
2428
            other_tree.unlock()
2429
        other_tree.bzrdir.retire_bzrdir()
2430
2431
    @needs_tree_write_lock
2432
    def extract(self, file_id, format=None):
2433
        """Extract a subtree from this tree.
2434
2435
        A new branch will be created, relative to the path for this tree.
2436
        """
2437
        self.flush()
2438
        def mkdirs(path):
2439
            segments = osutils.splitpath(path)
2440
            transport = self.branch.bzrdir.root_transport
2441
            for name in segments:
2442
                transport = transport.clone(name)
2443
                transport.ensure_base()
2444
            return transport
2445
2446
        sub_path = self.id2path(file_id)
2447
        branch_transport = mkdirs(sub_path)
2448
        if format is None:
2449
            format = self.bzrdir.cloning_metadir()
2450
        branch_transport.ensure_base()
2451
        branch_bzrdir = format.initialize_on_transport(branch_transport)
2452
        try:
2453
            repo = branch_bzrdir.find_repository()
2454
        except errors.NoRepositoryPresent:
2455
            repo = branch_bzrdir.create_repository()
2456
        if not repo.supports_rich_root():
2457
            raise errors.RootNotRich()
2458
        new_branch = branch_bzrdir.create_branch()
2459
        new_branch.pull(self.branch)
2460
        for parent_id in self.get_parent_ids():
2461
            new_branch.fetch(self.branch, parent_id)
2462
        tree_transport = self.bzrdir.root_transport.clone(sub_path)
2463
        if tree_transport.base != branch_transport.base:
2464
            tree_bzrdir = format.initialize_on_transport(tree_transport)
6437.7.3 by Jelmer Vernooij
Use ControlDir.set_branch_reference.
2465
            tree_bzrdir.set_branch_reference(new_branch)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2466
        else:
2467
            tree_bzrdir = branch_bzrdir
2468
        wt = tree_bzrdir.create_workingtree(_mod_revision.NULL_REVISION)
2469
        wt.set_parent_ids(self.get_parent_ids())
6405.2.10 by Jelmer Vernooij
Fix more tests.
2470
        # FIXME: Support nested trees
2471
        my_inv = self.root_inventory
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2472
        child_inv = inventory.Inventory(root_id=None)
2473
        new_root = my_inv[file_id]
2474
        my_inv.remove_recursive_id(file_id)
2475
        new_root.parent_id = None
2476
        child_inv.add(new_root)
2477
        self._write_inventory(my_inv)
2478
        wt._write_inventory(child_inv)
2479
        return wt
2480
2481
    def list_files(self, include_root=False, from_dir=None, recursive=True):
2482
        """List all files as (path, class, kind, id, entry).
2483
2484
        Lists, but does not descend into unversioned directories.
2485
        This does not include files that have been deleted in this
2486
        tree. Skips the control directory.
2487
2488
        :param include_root: if True, return an entry for the root
2489
        :param from_dir: start from this directory or None for the root
2490
        :param recursive: whether to recurse into subdirectories or not
2491
        """
2492
        # list_files is an iterator, so @needs_read_lock doesn't work properly
2493
        # with it. So callers should be careful to always read_lock the tree.
2494
        if not self.is_locked():
2495
            raise errors.ObjectNotLocked(self)
2496
2497
        if from_dir is None and include_root is True:
6405.2.6 by Jelmer Vernooij
Lots of test fixes.
2498
            yield ('', 'V', 'directory', self.get_root_id(), self.root_inventory.root)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2499
        # Convert these into local objects to save lookup times
2500
        pathjoin = osutils.pathjoin
2501
        file_kind = self._kind
2502
2503
        # transport.base ends in a slash, we want the piece
2504
        # between the last two slashes
2505
        transport_base_dir = self.bzrdir.transport.base.rsplit('/', 2)[1]
2506
2507
        fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
2508
2509
        # directory file_id, relative path, absolute path, reverse sorted children
2510
        if from_dir is not None:
6405.2.1 by Jelmer Vernooij
Allow passing in tuples as file ids in various places.
2511
            inv, from_dir_id = self._path2inv_file_id(from_dir)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2512
            if from_dir_id is None:
2513
                # Directory not versioned
2514
                return
2515
            from_dir_abspath = pathjoin(self.basedir, from_dir)
2516
        else:
6405.2.6 by Jelmer Vernooij
Lots of test fixes.
2517
            inv = self.root_inventory
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2518
            from_dir_id = inv.root.file_id
2519
            from_dir_abspath = self.basedir
6619.3.18 by Jelmer Vernooij
Run 2to3 idioms fixer.
2520
        children = sorted(os.listdir(from_dir_abspath))
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2521
        # jam 20060527 The kernel sized tree seems equivalent whether we
2522
        # use a deque and popleft to keep them sorted, or if we use a plain
2523
        # list and just reverse() them.
2524
        children = collections.deque(children)
2525
        stack = [(from_dir_id, u'', from_dir_abspath, children)]
2526
        while stack:
2527
            from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
2528
2529
            while children:
2530
                f = children.popleft()
2531
                ## TODO: If we find a subdirectory with its own .bzr
2532
                ## directory, then that is a separate tree and we
2533
                ## should exclude it.
2534
2535
                # the bzrdir for this tree
2536
                if transport_base_dir == f:
2537
                    continue
2538
2539
                # we know that from_dir_relpath and from_dir_abspath never end in a slash
2540
                # and 'f' doesn't begin with one, we can do a string op, rather
2541
                # than the checks of pathjoin(), all relative paths will have an extra slash
2542
                # at the beginning
2543
                fp = from_dir_relpath + '/' + f
2544
2545
                # absolute path
2546
                fap = from_dir_abspath + '/' + f
2547
2548
                dir_ie = inv[from_dir_id]
2549
                if dir_ie.kind == 'directory':
2550
                    f_ie = dir_ie.children.get(f)
2551
                else:
2552
                    f_ie = None
2553
                if f_ie:
2554
                    c = 'V'
2555
                elif self.is_ignored(fp[1:]):
2556
                    c = 'I'
2557
                else:
2558
                    # we may not have found this file, because of a unicode
2559
                    # issue, or because the directory was actually a symlink.
2560
                    f_norm, can_access = osutils.normalized_filename(f)
2561
                    if f == f_norm or not can_access:
2562
                        # No change, so treat this file normally
2563
                        c = '?'
2564
                    else:
2565
                        # this file can be accessed by a normalized path
2566
                        # check again if it is versioned
2567
                        # these lines are repeated here for performance
2568
                        f = f_norm
2569
                        fp = from_dir_relpath + '/' + f
2570
                        fap = from_dir_abspath + '/' + f
2571
                        f_ie = inv.get_child(from_dir_id, f)
2572
                        if f_ie:
2573
                            c = 'V'
2574
                        elif self.is_ignored(fp[1:]):
2575
                            c = 'I'
2576
                        else:
2577
                            c = '?'
2578
2579
                fk = file_kind(fap)
2580
2581
                # make a last minute entry
2582
                if f_ie:
2583
                    yield fp[1:], c, fk, f_ie.file_id, f_ie
2584
                else:
2585
                    try:
2586
                        yield fp[1:], c, fk, None, fk_entries[fk]()
2587
                    except KeyError:
2588
                        yield fp[1:], c, fk, None, TreeEntry()
2589
                    continue
2590
2591
                if fk != 'directory':
2592
                    continue
2593
2594
                # But do this child first if recursing down
2595
                if recursive:
6619.3.18 by Jelmer Vernooij
Run 2to3 idioms fixer.
2596
                    new_children = sorted(os.listdir(fap))
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2597
                    new_children = collections.deque(new_children)
2598
                    stack.append((f_ie.file_id, fp, fap, new_children))
2599
                    # Break out of inner loop,
2600
                    # so that we start outer loop with child
2601
                    break
2602
            else:
2603
                # if we finished all children, pop it off the stack
2604
                stack.pop()
2605
2606
    @needs_tree_write_lock
2607
    def move(self, from_paths, to_dir=None, after=False):
2608
        """Rename files.
2609
2610
        to_dir must exist in the inventory.
2611
2612
        If to_dir exists and is a directory, the files are moved into
2613
        it, keeping their old names.
2614
2615
        Note that to_dir is only the last component of the new name;
2616
        this doesn't change the directory.
2617
2618
        For each entry in from_paths the move mode will be determined
2619
        independently.
2620
2621
        The first mode moves the file in the filesystem and updates the
2622
        inventory. The second mode only updates the inventory without
2623
        touching the file on the filesystem.
2624
5911.1.4 by Benoît Pierre
Update docstrings for WorkingTree.move() and WorkingTree.rename_one().
2625
        move uses the second mode if 'after == True' and the target is
2626
        either not versioned or newly added, and present in the working tree.
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2627
2628
        move uses the second mode if 'after == False' and the source is
2629
        versioned but no longer in the working tree, and the target is not
2630
        versioned but present in the working tree.
2631
2632
        move uses the first mode if 'after == False' and the source is
2633
        versioned and present in the working tree, and the target is not
2634
        versioned and not present in the working tree.
2635
2636
        Everything else results in an error.
2637
2638
        This returns a list of (from_path, to_path) pairs for each
2639
        entry that is moved.
2640
        """
2641
        rename_entries = []
2642
        rename_tuples = []
2643
6405.2.2 by Jelmer Vernooij
Use _path2inv_file_id.
2644
        invs_to_write = set()
2645
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2646
        # check for deprecated use of signature
2647
        if to_dir is None:
2648
            raise TypeError('You must supply a target directory')
2649
        # check destination directory
2650
        if isinstance(from_paths, basestring):
2651
            raise ValueError()
2652
        to_abs = self.abspath(to_dir)
2653
        if not isdir(to_abs):
2654
            raise errors.BzrMoveFailedError('',to_dir,
2655
                errors.NotADirectory(to_abs))
2656
        if not self.has_filename(to_dir):
2657
            raise errors.BzrMoveFailedError('',to_dir,
2658
                errors.NotInWorkingDirectory(to_dir))
6405.2.2 by Jelmer Vernooij
Use _path2inv_file_id.
2659
        to_inv, to_dir_id = self._path2inv_file_id(to_dir)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2660
        if to_dir_id is None:
2661
            raise errors.BzrMoveFailedError('',to_dir,
2662
                errors.NotVersionedError(path=to_dir))
2663
6405.2.2 by Jelmer Vernooij
Use _path2inv_file_id.
2664
        to_dir_ie = to_inv[to_dir_id]
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2665
        if to_dir_ie.kind != 'directory':
2666
            raise errors.BzrMoveFailedError('',to_dir,
2667
                errors.NotADirectory(to_abs))
2668
2669
        # create rename entries and tuples
2670
        for from_rel in from_paths:
2671
            from_tail = splitpath(from_rel)[-1]
6405.2.2 by Jelmer Vernooij
Use _path2inv_file_id.
2672
            from_inv, from_id = self._path2inv_file_id(from_rel)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2673
            if from_id is None:
2674
                raise errors.BzrMoveFailedError(from_rel,to_dir,
2675
                    errors.NotVersionedError(path=from_rel))
2676
6405.2.2 by Jelmer Vernooij
Use _path2inv_file_id.
2677
            from_entry = from_inv[from_id]
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2678
            from_parent_id = from_entry.parent_id
2679
            to_rel = pathjoin(to_dir, from_tail)
2680
            rename_entry = InventoryWorkingTree._RenameEntry(
2681
                from_rel=from_rel,
2682
                from_id=from_id,
2683
                from_tail=from_tail,
2684
                from_parent_id=from_parent_id,
2685
                to_rel=to_rel, to_tail=from_tail,
2686
                to_parent_id=to_dir_id)
2687
            rename_entries.append(rename_entry)
2688
            rename_tuples.append((from_rel, to_rel))
2689
2690
        # determine which move mode to use. checks also for movability
2691
        rename_entries = self._determine_mv_mode(rename_entries, after)
2692
2693
        original_modified = self._inventory_is_modified
2694
        try:
2695
            if len(from_paths):
2696
                self._inventory_is_modified = True
2697
            self._move(rename_entries)
2698
        except:
2699
            # restore the inventory on error
2700
            self._inventory_is_modified = original_modified
2701
            raise
6405.2.2 by Jelmer Vernooij
Use _path2inv_file_id.
2702
        #FIXME: Should potentially also write the from_invs
2703
        self._write_inventory(to_inv)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2704
        return rename_tuples
2705
2706
    @needs_tree_write_lock
2707
    def rename_one(self, from_rel, to_rel, after=False):
2708
        """Rename one file.
2709
2710
        This can change the directory or the filename or both.
2711
2712
        rename_one has several 'modes' to work. First, it can rename a physical
2713
        file and change the file_id. That is the normal mode. Second, it can
2714
        only change the file_id without touching any physical file.
2715
2716
        rename_one uses the second mode if 'after == True' and 'to_rel' is not
2717
        versioned but present in the working tree.
2718
2719
        rename_one uses the second mode if 'after == False' and 'from_rel' is
2720
        versioned but no longer in the working tree, and 'to_rel' is not
2721
        versioned but present in the working tree.
2722
2723
        rename_one uses the first mode if 'after == False' and 'from_rel' is
2724
        versioned and present in the working tree, and 'to_rel' is not
2725
        versioned and not present in the working tree.
2726
2727
        Everything else results in an error.
2728
        """
2729
        rename_entries = []
2730
2731
        # create rename entries and tuples
2732
        from_tail = splitpath(from_rel)[-1]
6405.2.2 by Jelmer Vernooij
Use _path2inv_file_id.
2733
        from_inv, from_id = self._path2inv_file_id(from_rel)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2734
        if from_id is None:
2735
            # if file is missing in the inventory maybe it's in the basis_tree
2736
            basis_tree = self.branch.basis_tree()
2737
            from_id = basis_tree.path2id(from_rel)
2738
            if from_id is None:
2739
                raise errors.BzrRenameFailedError(from_rel,to_rel,
2740
                    errors.NotVersionedError(path=from_rel))
2741
            # put entry back in the inventory so we can rename it
6405.2.10 by Jelmer Vernooij
Fix more tests.
2742
            from_entry = basis_tree.root_inventory[from_id].copy()
6405.2.2 by Jelmer Vernooij
Use _path2inv_file_id.
2743
            from_inv.add(from_entry)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2744
        else:
6405.2.2 by Jelmer Vernooij
Use _path2inv_file_id.
2745
            from_inv, from_inv_id = self._unpack_file_id(from_id)
2746
            from_entry = from_inv[from_inv_id]
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2747
        from_parent_id = from_entry.parent_id
2748
        to_dir, to_tail = os.path.split(to_rel)
6405.2.2 by Jelmer Vernooij
Use _path2inv_file_id.
2749
        to_inv, to_dir_id = self._path2inv_file_id(to_dir)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2750
        rename_entry = InventoryWorkingTree._RenameEntry(from_rel=from_rel,
2751
                                     from_id=from_id,
2752
                                     from_tail=from_tail,
2753
                                     from_parent_id=from_parent_id,
2754
                                     to_rel=to_rel, to_tail=to_tail,
2755
                                     to_parent_id=to_dir_id)
2756
        rename_entries.append(rename_entry)
2757
2758
        # determine which move mode to use. checks also for movability
2759
        rename_entries = self._determine_mv_mode(rename_entries, after)
2760
2761
        # check if the target changed directory and if the target directory is
2762
        # versioned
2763
        if to_dir_id is None:
2764
            raise errors.BzrMoveFailedError(from_rel,to_rel,
2765
                errors.NotVersionedError(path=to_dir))
2766
2767
        # all checks done. now we can continue with our actual work
2768
        mutter('rename_one:\n'
2769
               '  from_id   {%s}\n'
2770
               '  from_rel: %r\n'
2771
               '  to_rel:   %r\n'
2772
               '  to_dir    %r\n'
2773
               '  to_dir_id {%s}\n',
2774
               from_id, from_rel, to_rel, to_dir, to_dir_id)
2775
2776
        self._move(rename_entries)
6405.2.2 by Jelmer Vernooij
Use _path2inv_file_id.
2777
        self._write_inventory(to_inv)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2778
2779
    class _RenameEntry(object):
2780
        def __init__(self, from_rel, from_id, from_tail, from_parent_id,
5911.1.2 by Benoît Pierre
Implement new 'mv --after' behaviour.
2781
                     to_rel, to_tail, to_parent_id, only_change_inv=False,
2782
                     change_id=False):
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2783
            self.from_rel = from_rel
2784
            self.from_id = from_id
2785
            self.from_tail = from_tail
2786
            self.from_parent_id = from_parent_id
2787
            self.to_rel = to_rel
2788
            self.to_tail = to_tail
2789
            self.to_parent_id = to_parent_id
5911.1.2 by Benoît Pierre
Implement new 'mv --after' behaviour.
2790
            self.change_id = change_id
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2791
            self.only_change_inv = only_change_inv
2792
2793
    def _determine_mv_mode(self, rename_entries, after=False):
2794
        """Determines for each from-to pair if both inventory and working tree
2795
        or only the inventory has to be changed.
2796
2797
        Also does basic plausability tests.
2798
        """
6405.2.5 by Jelmer Vernooij
Add root_inventory.
2799
        # FIXME: Handling of nested trees
2800
        inv = self.root_inventory
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2801
2802
        for rename_entry in rename_entries:
2803
            # store to local variables for easier reference
2804
            from_rel = rename_entry.from_rel
2805
            from_id = rename_entry.from_id
2806
            to_rel = rename_entry.to_rel
2807
            to_id = inv.path2id(to_rel)
2808
            only_change_inv = False
5911.1.2 by Benoît Pierre
Implement new 'mv --after' behaviour.
2809
            change_id = False
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2810
2811
            # check the inventory for source and destination
2812
            if from_id is None:
2813
                raise errors.BzrMoveFailedError(from_rel,to_rel,
2814
                    errors.NotVersionedError(path=from_rel))
2815
            if to_id is not None:
5911.1.2 by Benoît Pierre
Implement new 'mv --after' behaviour.
2816
                allowed = False
5911.1.3 by Benoît Pierre
Unlock on errors as per Vincent Ladeuil recommendation.
2817
                # allow it with --after but only if dest is newly added
5911.1.2 by Benoît Pierre
Implement new 'mv --after' behaviour.
2818
                if after:
2819
                    basis = self.basis_tree()
2820
                    basis.lock_read()
5911.1.3 by Benoît Pierre
Unlock on errors as per Vincent Ladeuil recommendation.
2821
                    try:
2822
                        if not basis.has_id(to_id):
2823
                            rename_entry.change_id = True
2824
                            allowed = True
2825
                    finally:
2826
                        basis.unlock()
5911.1.2 by Benoît Pierre
Implement new 'mv --after' behaviour.
2827
                if not allowed:
2828
                    raise errors.BzrMoveFailedError(from_rel,to_rel,
2829
                        errors.AlreadyVersionedError(path=to_rel))
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2830
2831
            # try to determine the mode for rename (only change inv or change
2832
            # inv and file system)
2833
            if after:
2834
                if not self.has_filename(to_rel):
2835
                    raise errors.BzrMoveFailedError(from_id,to_rel,
2836
                        errors.NoSuchFile(path=to_rel,
2837
                        extra="New file has not been created yet"))
2838
                only_change_inv = True
2839
            elif not self.has_filename(from_rel) and self.has_filename(to_rel):
2840
                only_change_inv = True
2841
            elif self.has_filename(from_rel) and not self.has_filename(to_rel):
2842
                only_change_inv = False
2843
            elif (not self.case_sensitive
2844
                  and from_rel.lower() == to_rel.lower()
2845
                  and self.has_filename(from_rel)):
2846
                only_change_inv = False
2847
            else:
2848
                # something is wrong, so lets determine what exactly
2849
                if not self.has_filename(from_rel) and \
2850
                   not self.has_filename(to_rel):
6346.1.2 by Martin Packman
Don't call str() on a path, don't call str() on a path
2851
                    raise errors.BzrRenameFailedError(from_rel, to_rel,
2852
                        errors.PathsDoNotExist(paths=(from_rel, to_rel)))
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2853
                else:
2854
                    raise errors.RenameFailedFilesExist(from_rel, to_rel)
2855
            rename_entry.only_change_inv = only_change_inv
2856
        return rename_entries
2857
2858
    def _move(self, rename_entries):
2859
        """Moves a list of files.
2860
2861
        Depending on the value of the flag 'only_change_inv', the
2862
        file will be moved on the file system or not.
2863
        """
2864
        moved = []
2865
2866
        for entry in rename_entries:
2867
            try:
2868
                self._move_entry(entry)
2869
            except:
2870
                self._rollback_move(moved)
2871
                raise
2872
            moved.append(entry)
2873
2874
    def _rollback_move(self, moved):
2875
        """Try to rollback a previous move in case of an filesystem error."""
2876
        for entry in moved:
2877
            try:
2878
                self._move_entry(WorkingTree._RenameEntry(
2879
                    entry.to_rel, entry.from_id,
2880
                    entry.to_tail, entry.to_parent_id, entry.from_rel,
2881
                    entry.from_tail, entry.from_parent_id,
2882
                    entry.only_change_inv))
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2883
            except errors.BzrMoveFailedError as e:
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2884
                raise errors.BzrMoveFailedError( '', '', "Rollback failed."
2885
                        " The working tree is in an inconsistent state."
2886
                        " Please consider doing a 'bzr revert'."
2887
                        " Error message is: %s" % e)
2888
2889
    def _move_entry(self, entry):
6405.2.5 by Jelmer Vernooij
Add root_inventory.
2890
        inv = self.root_inventory
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2891
        from_rel_abs = self.abspath(entry.from_rel)
2892
        to_rel_abs = self.abspath(entry.to_rel)
2893
        if from_rel_abs == to_rel_abs:
2894
            raise errors.BzrMoveFailedError(entry.from_rel, entry.to_rel,
2895
                "Source and target are identical.")
2896
2897
        if not entry.only_change_inv:
2898
            try:
2899
                osutils.rename(from_rel_abs, to_rel_abs)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2900
            except OSError as e:
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2901
                raise errors.BzrMoveFailedError(entry.from_rel,
2902
                    entry.to_rel, e[1])
5911.1.2 by Benoît Pierre
Implement new 'mv --after' behaviour.
2903
        if entry.change_id:
2904
            to_id = inv.path2id(entry.to_rel)
2905
            inv.remove_recursive_id(to_id)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2906
        inv.rename(entry.from_id, entry.to_parent_id, entry.to_tail)
2907
2908
    @needs_tree_write_lock
2909
    def unversion(self, file_ids):
2910
        """Remove the file ids in file_ids from the current versioned set.
2911
2912
        When a file_id is unversioned, all of its children are automatically
2913
        unversioned.
2914
2915
        :param file_ids: The file ids to stop versioning.
2916
        :raises: NoSuchId if any fileid is not currently versioned.
2917
        """
2918
        for file_id in file_ids:
5967.7.1 by Martin Pool
Deprecate __contains__ on Tree and Inventory
2919
            if not self._inventory.has_id(file_id):
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2920
                raise errors.NoSuchId(self, file_id)
2921
        for file_id in file_ids:
2922
            if self._inventory.has_id(file_id):
2923
                self._inventory.remove_recursive_id(file_id)
2924
        if len(file_ids):
2925
            # in the future this should just set a dirty bit to wait for the
2926
            # final unlock. However, until all methods of workingtree start
2927
            # with the current in -memory inventory rather than triggering
2928
            # a read, it is more complex - we need to teach read_inventory
2929
            # to know when to read, and when to not read first... and possibly
2930
            # to save first when the in memory one may be corrupted.
2931
            # so for now, we just only write it if it is indeed dirty.
2932
            # - RBC 20060907
2933
            self._write_inventory(self._inventory)
2934
2935
    def stored_kind(self, file_id):
2936
        """See Tree.stored_kind"""
6405.2.5 by Jelmer Vernooij
Add root_inventory.
2937
        inv, inv_file_id = self._unpack_file_id(file_id)
2938
        return inv[inv_file_id].kind
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2939
2940
    def extras(self):
2941
        """Yield all unversioned files in this WorkingTree.
2942
2943
        If there are any unversioned directories then only the directory is
2944
        returned, not all its children.  But if there are unversioned files
2945
        under a versioned subdirectory, they are returned.
2946
2947
        Currently returned depth-first, sorted by name within directories.
2948
        This is the same order used by 'osutils.walkdirs'.
2949
        """
2950
        ## TODO: Work from given directory downwards
6468.2.1 by Jelmer Vernooij
Remove barely used Inventory.directories().
2951
        for path, dir_entry in self.iter_entries_by_dir():
2952
            if dir_entry.kind != 'directory':
2953
                continue
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2954
            # mutter("search for unknowns in %r", path)
2955
            dirabs = self.abspath(path)
2956
            if not isdir(dirabs):
2957
                # e.g. directory deleted
2958
                continue
2959
2960
            fl = []
2961
            for subf in os.listdir(dirabs):
2962
                if self.bzrdir.is_control_filename(subf):
2963
                    continue
2964
                if subf not in dir_entry.children:
2965
                    try:
2966
                        (subf_norm,
2967
                         can_access) = osutils.normalized_filename(subf)
2968
                    except UnicodeDecodeError:
2969
                        path_os_enc = path.encode(osutils._fs_enc)
2970
                        relpath = path_os_enc + '/' + subf
2971
                        raise errors.BadFilenameEncoding(relpath,
2972
                                                         osutils._fs_enc)
2973
                    if subf_norm != subf and can_access:
2974
                        if subf_norm not in dir_entry.children:
2975
                            fl.append(subf_norm)
2976
                    else:
2977
                        fl.append(subf)
2978
2979
            fl.sort()
2980
            for subf in fl:
2981
                subp = pathjoin(path, subf)
2982
                yield subp
2983
2984
    def _walkdirs(self, prefix=""):
2985
        """Walk the directories of this tree.
2986
5891.1.2 by Andrew Bennetts
Fix a bunch of docstring formatting nits, making pydoctor a bit happier.
2987
        :param prefix: is used as the directrory to start with.
2988
        :returns: a generator which yields items in the form::
2989
2990
            ((curren_directory_path, fileid),
2991
             [(file1_path, file1_name, file1_kind, None, file1_id,
2992
               file1_kind), ... ])
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2993
        """
2994
        _directory = 'directory'
2995
        # get the root in the inventory
6405.2.5 by Jelmer Vernooij
Add root_inventory.
2996
        inv, top_id = self._path2inv_file_id(prefix)
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
2997
        if top_id is None:
2998
            pending = []
2999
        else:
3000
            pending = [(prefix, '', _directory, None, top_id, None)]
3001
        while pending:
3002
            dirblock = []
3003
            currentdir = pending.pop()
3004
            # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-id, 5-kind
3005
            top_id = currentdir[4]
3006
            if currentdir[0]:
3007
                relroot = currentdir[0] + '/'
3008
            else:
3009
                relroot = ""
3010
            # FIXME: stash the node in pending
3011
            entry = inv[top_id]
3012
            if entry.kind == 'directory':
3013
                for name, child in entry.sorted_children():
3014
                    dirblock.append((relroot + name, name, child.kind, None,
3015
                        child.file_id, child.kind
3016
                        ))
3017
            yield (currentdir[0], entry.file_id), dirblock
3018
            # push the user specified dirs from dirblock
3019
            for dir in reversed(dirblock):
3020
                if dir[2] == _directory:
3021
                    pending.append(dir)
3022
6213.1.58 by Jelmer Vernooij
Use update_feature_flags everywhere.
3023
    @needs_write_lock
3024
    def update_feature_flags(self, updated_flags):
3025
        """Update the feature flags for this branch.
3026
3027
        :param updated_flags: Dictionary mapping feature names to necessities
3028
            A necessity can be None to indicate the feature should be removed
3029
        """
3030
        self._format._update_feature_flags(updated_flags)
3031
        self.control_transport.put_bytes('format', self._format.as_string())
3032
5777.5.2 by Jelmer Vernooij
Split inventory-specific methods and WorkingTree interface method
3033
5669.3.9 by Jelmer Vernooij
Consistent naming.
3034
class WorkingTreeFormatRegistry(controldir.ControlComponentFormatRegistry):
5662.3.1 by Jelmer Vernooij
Add WorkingTreeFormatRegistry.
3035
    """Registry for working tree formats."""
3036
3037
    def __init__(self, other_registry=None):
3038
        super(WorkingTreeFormatRegistry, self).__init__(other_registry)
3039
        self._default_format = None
5816.2.1 by Jelmer Vernooij
Allow lazily setting default for working trees.
3040
        self._default_format_key = None
5662.3.1 by Jelmer Vernooij
Add WorkingTreeFormatRegistry.
3041
3042
    def get_default(self):
3043
        """Return the current default format."""
5816.2.1 by Jelmer Vernooij
Allow lazily setting default for working trees.
3044
        if (self._default_format_key is not None and
3045
            self._default_format is None):
3046
            self._default_format = self.get(self._default_format_key)
5662.3.1 by Jelmer Vernooij
Add WorkingTreeFormatRegistry.
3047
        return self._default_format
3048
3049
    def set_default(self, format):
5816.2.3 by Jelmer Vernooij
Add docstrings.
3050
        """Set the default format."""
5662.3.1 by Jelmer Vernooij
Add WorkingTreeFormatRegistry.
3051
        self._default_format = format
5816.2.1 by Jelmer Vernooij
Allow lazily setting default for working trees.
3052
        self._default_format_key = None
3053
3054
    def set_default_key(self, format_string):
5816.2.3 by Jelmer Vernooij
Add docstrings.
3055
        """Set the default format by its format string."""
5816.2.1 by Jelmer Vernooij
Allow lazily setting default for working trees.
3056
        self._default_format_key = format_string
3057
        self._default_format = None
5662.3.1 by Jelmer Vernooij
Add WorkingTreeFormatRegistry.
3058
3059
3060
format_registry = WorkingTreeFormatRegistry()
3061
3062
5669.3.10 by Jelmer Vernooij
Use ControlComponentFormat.
3063
class WorkingTreeFormat(controldir.ControlComponentFormat):
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
3064
    """An encapsulation of the initialization and open routines for a format.
3065
3066
    Formats provide three things:
3067
     * An initialization routine,
3068
     * a format string,
3069
     * an open routine.
3070
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3071
    Formats are placed in an dict by their format string for reference
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
3072
    during workingtree opening. Its not required that these be instances, they
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3073
    can be classes themselves with class methods - it simply depends on
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
3074
    whether state is needed for a given format or not.
3075
3076
    Once a format is deprecated, just deprecate the initialize and open
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3077
    methods on the format class. Do not deprecate the object, as the
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
3078
    object will be created every time regardless.
3079
    """
3080
2100.3.14 by Aaron Bentley
Test workingtree4 format, prevent use with old repos
3081
    requires_rich_root = False
3082
2323.6.4 by Martin Pool
BzrDir._check_supported now also takes care of recommending upgrades, which
3083
    upgrade_recommended = False
3084
5582.10.29 by Jelmer Vernooij
Add requires_normalized_unicode_filenames
3085
    requires_normalized_unicode_filenames = False
3086
5632.1.1 by John Arbash Meinel
Make case_sensitive_filename an attribute of the format.
3087
    case_sensitive_filename = "FoRMaT"
3088
5661.1.1 by Jelmer Vernooij
Add 'WorkingTreeFormat.missing_parent_conflicts' flag to use in tests.
3089
    missing_parent_conflicts = False
3090
    """If this format supports missing parent conflicts."""
3091
5993.3.1 by Jelmer Vernooij
Add WorkingTreeFormat.supports_versioned_directories attribute.
3092
    supports_versioned_directories = None
3093
6207.3.3 by jelmer at samba
Fix tests and the like.
3094
    def initialize(self, controldir, revision_id=None, from_branch=None,
5683.1.1 by Jelmer Vernooij
Add stub WorkingTreeFormat.initialize().
3095
                   accelerator_tree=None, hardlink=False):
6207.3.3 by jelmer at samba
Fix tests and the like.
3096
        """Initialize a new working tree in controldir.
5683.1.1 by Jelmer Vernooij
Add stub WorkingTreeFormat.initialize().
3097
6207.3.3 by jelmer at samba
Fix tests and the like.
3098
        :param controldir: ControlDir to initialize the working tree in.
5683.1.1 by Jelmer Vernooij
Add stub WorkingTreeFormat.initialize().
3099
        :param revision_id: allows creating a working tree at a different
3100
            revision than the branch is at.
3101
        :param from_branch: Branch to checkout
3102
        :param accelerator_tree: A tree which can be used for retrieving file
3103
            contents more quickly than the revision tree, i.e. a workingtree.
3104
            The revision tree will be used for cases where accelerator_tree's
3105
            content is different.
3106
        :param hardlink: If true, hard-link files from accelerator_tree,
3107
            where possible.
3108
        """
3109
        raise NotImplementedError(self.initialize)
3110
2100.3.35 by Aaron Bentley
equality operations on bzrdir
3111
    def __eq__(self, other):
3112
        return self.__class__ is other.__class__
3113
3114
    def __ne__(self, other):
3115
        return not (self == other)
3116
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
3117
    def get_format_description(self):
3118
        """Return the short description for this format."""
3119
        raise NotImplementedError(self.get_format_description)
3120
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
3121
    def is_supported(self):
3122
        """Is this format supported?
3123
3124
        Supported formats can be initialized and opened.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3125
        Unsupported formats may not support initialization or committing or
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
3126
        some other features depending on the reason for not being supported.
3127
        """
3128
        return True
3129
3907.2.1 by Ian Clatworthy
WorkingTreeFormat5 supporting content filtering and views
3130
    def supports_content_filtering(self):
3131
        """True if this format supports content filtering."""
3132
        return False
3133
3586.1.4 by Ian Clatworthy
first cut at tree-level view tests
3134
    def supports_views(self):
3135
        """True if this format supports stored views."""
3136
        return False
3137
6162.3.2 by Jelmer Vernooij
Add WorkingTreeFormat.get_controldir_for_branch().
3138
    def get_controldir_for_branch(self):
3139
        """Get the control directory format for creating branches.
3140
3141
        This is to support testing of working tree formats that can not exist
3142
        in the same control directory as a branch.
3143
        """
3144
        return self._matchingbzrdir
3145
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
3146
6213.1.30 by Jelmer Vernooij
Add BzrFormat.
3147
class WorkingTreeFormatMetaDir(bzrdir.BzrFormat, WorkingTreeFormat):
6349.2.1 by Jelmer Vernooij
Add BzrDirMetaComponentFormat.
3148
    """Base class for working trees that live in bzr meta directories."""
6213.1.9 by Jelmer Vernooij
Add metadir working tree format with feature support.
3149
3150
    def __init__(self):
6213.1.24 by Jelmer Vernooij
More refactoring.
3151
        WorkingTreeFormat.__init__(self)
6213.1.30 by Jelmer Vernooij
Add BzrFormat.
3152
        bzrdir.BzrFormat.__init__(self)
6213.1.24 by Jelmer Vernooij
More refactoring.
3153
3154
    @classmethod
3155
    def find_format_string(klass, controldir):
3156
        """Return format name for the working tree object in controldir."""
3157
        try:
3158
            transport = controldir.get_workingtree_transport(None)
3159
            return transport.get_bytes("format")
3160
        except errors.NoSuchFile:
3161
            raise errors.NoWorkingTree(base=transport.base)
3162
3163
    @classmethod
3164
    def find_format(klass, controldir):
3165
        """Return the format for the working tree object in controldir."""
3166
        format_string = klass.find_format_string(controldir)
3167
        return klass._find_format(format_registry, 'working tree',
3168
                format_string)
6213.1.20 by Jelmer Vernooij
Fix __eq__.
3169
6213.1.34 by Jelmer Vernooij
Fix remaining test.
3170
    def check_support_status(self, allow_unsupported, recommend_upgrade=True,
3171
            basedir=None):
3172
        WorkingTreeFormat.check_support_status(self,
3173
            allow_unsupported=allow_unsupported, recommend_upgrade=recommend_upgrade,
3174
            basedir=basedir)
3175
        bzrdir.BzrFormat.check_support_status(self, allow_unsupported=allow_unsupported,
3176
            recommend_upgrade=recommend_upgrade, basedir=basedir)
3177
6162.3.2 by Jelmer Vernooij
Add WorkingTreeFormat.get_controldir_for_branch().
3178
    def get_controldir_for_branch(self):
3179
        """Get the control directory format for creating branches.
3180
3181
        This is to support testing of working tree formats that can not exist
3182
        in the same control directory as a branch.
3183
        """
3184
        return self._matchingbzrdir
3185
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
3186
6213.1.30 by Jelmer Vernooij
Add BzrFormat.
3187
class WorkingTreeFormatMetaDir(bzrdir.BzrFormat, WorkingTreeFormat):
6349.2.1 by Jelmer Vernooij
Add BzrDirMetaComponentFormat.
3188
    """Base class for working trees that live in bzr meta directories."""
6213.1.9 by Jelmer Vernooij
Add metadir working tree format with feature support.
3189
3190
    def __init__(self):
6213.1.24 by Jelmer Vernooij
More refactoring.
3191
        WorkingTreeFormat.__init__(self)
6213.1.30 by Jelmer Vernooij
Add BzrFormat.
3192
        bzrdir.BzrFormat.__init__(self)
6213.1.24 by Jelmer Vernooij
More refactoring.
3193
3194
    @classmethod
3195
    def find_format_string(klass, controldir):
3196
        """Return format name for the working tree object in controldir."""
3197
        try:
3198
            transport = controldir.get_workingtree_transport(None)
3199
            return transport.get_bytes("format")
3200
        except errors.NoSuchFile:
3201
            raise errors.NoWorkingTree(base=transport.base)
3202
3203
    @classmethod
3204
    def find_format(klass, controldir):
3205
        """Return the format for the working tree object in controldir."""
3206
        format_string = klass.find_format_string(controldir)
3207
        return klass._find_format(format_registry, 'working tree',
3208
                format_string)
6213.1.20 by Jelmer Vernooij
Fix __eq__.
3209
6213.1.34 by Jelmer Vernooij
Fix remaining test.
3210
    def check_support_status(self, allow_unsupported, recommend_upgrade=True,
3211
            basedir=None):
3212
        WorkingTreeFormat.check_support_status(self,
3213
            allow_unsupported=allow_unsupported, recommend_upgrade=recommend_upgrade,
3214
            basedir=basedir)
3215
        bzrdir.BzrFormat.check_support_status(self, allow_unsupported=allow_unsupported,
3216
            recommend_upgrade=recommend_upgrade, basedir=basedir)
3217
6213.1.9 by Jelmer Vernooij
Add metadir working tree format with feature support.
3218
5662.3.1 by Jelmer Vernooij
Add WorkingTreeFormatRegistry.
3219
format_registry.register_lazy("Bazaar Working Tree Format 4 (bzr 0.15)\n",
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3220
    "breezy.workingtree_4", "WorkingTreeFormat4")
5662.3.1 by Jelmer Vernooij
Add WorkingTreeFormatRegistry.
3221
format_registry.register_lazy("Bazaar Working Tree Format 5 (bzr 1.11)\n",
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3222
    "breezy.workingtree_4", "WorkingTreeFormat5")
5662.3.1 by Jelmer Vernooij
Add WorkingTreeFormatRegistry.
3223
format_registry.register_lazy("Bazaar Working Tree Format 6 (bzr 1.14)\n",
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3224
    "breezy.workingtree_4", "WorkingTreeFormat6")
5816.5.1 by Jelmer Vernooij
Move WorkingTree3 to bzrlib.workingtree_3.
3225
format_registry.register_lazy("Bazaar-NG Working Tree format 3",
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
3226
    "breezy.workingtree_3", "WorkingTreeFormat3")
5816.2.1 by Jelmer Vernooij
Allow lazily setting default for working trees.
3227
format_registry.set_default_key("Bazaar Working Tree Format 6 (bzr 1.14)\n")