/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
1
# Copyright (C) 2005, 2006 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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
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.
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 
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
1534.7.196 by Aaron Bentley
Switched to Rio format for merge-modified list
32
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
33
CONFLICT_HEADER_1 = "BZR conflict list format 1"
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
34
35
# TODO: Give the workingtree sole responsibility for the working inventory;
36
# remove the variable and references to it from the branch.  This may require
37
# updating the commit code so as to update the inventory within the working
38
# copy, and making sure there's only one WorkingTree for any directory on disk.
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
39
# At the moment they may alias the inventory and have old copies of it in
40
# memory.  (Now done? -- mbp 20060309)
956 by Martin Pool
doc
41
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
42
from binascii import hexlify
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
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
45
from copy import deepcopy
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
46
from cStringIO import StringIO
47
import errno
48
import fnmatch
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
49
import itertools
50
import operator
453 by Martin Pool
- Split WorkingTree into its own file
51
import os
1185.85.34 by John Arbash Meinel
Updating 'bzr file-id' exposed that we weren't allowing unicode file ids. Enabling them reveals a lot more bugs.
52
import re
1398 by Robert Collins
integrate in Gustavos x-bit patch
53
import stat
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
54
from time import time
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
55
import warnings
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
56
1836.1.21 by John Arbash Meinel
Restore the ability to ignore items by modifying DEFAULT_IGNORE
57
import bzrlib
1852.13.15 by Robert Collins
Ensure Format4 working trees start with a dirstate.
58
from bzrlib import bzrdir, dirstate, errors, ignores, osutils, urlutils
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
59
from bzrlib.atomicfile import AtomicFile
1852.3.1 by Robert Collins
Trivial cleanups to workingtree.py
60
import bzrlib.branch
1534.10.22 by Aaron Bentley
Got ConflictList implemented
61
from bzrlib.conflicts import Conflict, ConflictList, CONFLICT_SUFFIXES
1534.4.28 by Robert Collins
first cut at merge from integration.
62
from bzrlib.decorators import needs_read_lock, needs_write_lock
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
63
from bzrlib.errors import (BzrCheckError,
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
64
                           BzrError,
1534.10.7 by Aaron Bentley
Added tests for bad conflict lists
65
                           ConflictFormatError,
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
66
                           WeaveRevisionNotPresent,
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
67
                           NotBranchError,
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
68
                           NoSuchFile,
1558.3.3 by Aaron Bentley
Fix error handling for merge_modified
69
                           NotVersionedError,
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
70
                           MergeModifiedFormatError,
71
                           UnsupportedOperation,
72
                           )
1534.7.165 by Aaron Bentley
Switched to build_tree instead of revert
73
from bzrlib.inventory import InventoryEntry, Inventory
1553.5.63 by Martin Pool
Lock type is now mandatory for LockableFiles constructor
74
from bzrlib.lockable_files import LockableFiles, TransportLock
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
75
from bzrlib.lockdir import LockDir
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.
76
from bzrlib.merge import merge_inner, transform_tree
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
77
from bzrlib.osutils import (
78
                            abspath,
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
79
                            compact_date,
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
80
                            file_kind,
81
                            isdir,
1185.31.39 by John Arbash Meinel
Replacing os.getcwdu() with osutils.getcwd(),
82
                            getcwd,
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 \
83
                            pathjoin,
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
84
                            pumpfile,
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
85
                            safe_unicode,
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
86
                            splitpath,
1713.1.7 by Robert Collins
Review comments for gen_file_id changes.
87
                            rand_chars,
1185.31.38 by John Arbash Meinel
Changing os.path.normpath to osutils.normpath
88
                            normpath,
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
89
                            realpath,
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
90
                            relpath,
1534.7.25 by Aaron Bentley
Added set_executability
91
                            rename,
92
                            supports_executable,
93
                            )
1551.2.36 by Aaron Bentley
Make pull update the progress bar more nicely
94
from bzrlib.progress import DummyProgress, ProgressPhase
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
95
from bzrlib.revision import NULL_REVISION
1534.10.3 by Aaron Bentley
Simplify set_merge_modified with rio_file
96
from bzrlib.rio import RioReader, rio_file, Stanza
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
97
from bzrlib.symbol_versioning import (deprecated_passed,
98
        deprecated_method,
99
        deprecated_function,
100
        DEPRECATED_PARAMETER,
101
        zero_eight,
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
102
        zero_eleven,
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
103
        )
1852.3.1 by Robert Collins
Trivial cleanups to workingtree.py
104
from bzrlib.trace import mutter, note
1534.7.165 by Aaron Bentley
Switched to build_tree instead of revert
105
from bzrlib.transform import build_tree
1534.4.28 by Robert Collins
first cut at merge from integration.
106
from bzrlib.transport import get_transport
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
107
from bzrlib.transport.local import LocalTransport
1852.3.1 by Robert Collins
Trivial cleanups to workingtree.py
108
from bzrlib.textui import show_status
109
import bzrlib.tree
1534.9.10 by Aaron Bentley
Fixed use of ui_factory (which can't be imported directly)
110
import bzrlib.ui
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
111
import bzrlib.xml5
453 by Martin Pool
- Split WorkingTree into its own file
112
1685.1.30 by John Arbash Meinel
PEP8 for workingtree.py
113
1864.4.1 by John Arbash Meinel
Fix bug #43801 by squashing file ids a little bit more.
114
# the regex removes any weird characters; we don't escape them 
115
# but rather just pull them out
116
_gen_file_id_re = re.compile(r'[^\w.]')
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
117
_gen_id_suffix = None
118
_gen_id_serial = 0
119
120
121
def _next_id_suffix():
122
    """Create a new file id suffix that is reasonably unique.
123
    
124
    On the first call we combine the current time with 64 bits of randomness
125
    to give a highly probably globally unique number. Then each call in the same
126
    process adds 1 to a serial number we append to that unique value.
127
    """
1713.1.7 by Robert Collins
Review comments for gen_file_id changes.
128
    # XXX TODO: change bzrlib.add.smart_add to call workingtree.add() rather 
129
    # than having to move the id randomness out of the inner loop like this.
130
    # XXX TODO: for the global randomness this uses we should add the thread-id
131
    # before the serial #.
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
132
    global _gen_id_suffix, _gen_id_serial
133
    if _gen_id_suffix is None:
1713.1.7 by Robert Collins
Review comments for gen_file_id changes.
134
        _gen_id_suffix = "-%s-%s-" % (compact_date(time()), rand_chars(16))
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
135
    _gen_id_serial += 1
136
    return _gen_id_suffix + str(_gen_id_serial)
1185.85.34 by John Arbash Meinel
Updating 'bzr file-id' exposed that we weren't allowing unicode file ids. Enabling them reveals a lot more bugs.
137
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
138
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
139
def gen_file_id(name):
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
140
    """Return new file id for the basename 'name'.
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
141
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
142
    The uniqueness is supplied from _next_id_suffix.
1185.85.34 by John Arbash Meinel
Updating 'bzr file-id' exposed that we weren't allowing unicode file ids. Enabling them reveals a lot more bugs.
143
    """
1864.4.1 by John Arbash Meinel
Fix bug #43801 by squashing file ids a little bit more.
144
    # The real randomness is in the _next_id_suffix, the
145
    # rest of the identifier is just to be nice.
146
    # So we:
147
    # 1) Remove non-ascii word characters to keep the ids portable
148
    # 2) squash to lowercase, so the file id doesn't have to
149
    #    be escaped (case insensitive filesystems would bork for ids
150
    #    that only differred in case without escaping).
151
    # 3) truncate the filename to 20 chars. Long filenames also bork on some
152
    #    filesystems
153
    # 4) Removing starting '.' characters to prevent the file ids from
154
    #    being considered hidden.
155
    ascii_word_only = _gen_file_id_re.sub('', name.lower())
156
    short_no_dots = ascii_word_only.lstrip('.')[:20]
157
    return short_no_dots + _next_id_suffix()
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
158
159
160
def gen_root_id():
161
    """Return a new tree-root file id."""
162
    return gen_file_id('TREE_ROOT')
163
164
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
165
class TreeEntry(object):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
166
    """An entry that implements the minimum interface used by commands.
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
167
168
    This needs further inspection, it may be better to have 
169
    InventoryEntries without ids - though that seems wrong. For now,
170
    this is a parallel hierarchy to InventoryEntry, and needs to become
171
    one of several things: decorates to that hierarchy, children of, or
172
    parents of it.
1399.1.3 by Robert Collins
move change detection for text and metadata from delta to entry.detect_changes
173
    Another note is that these objects are currently only used when there is
174
    no InventoryEntry available - i.e. for unversioned objects.
175
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
176
    """
177
 
178
    def __eq__(self, other):
179
        # yes, this us ugly, TODO: best practice __eq__ style.
180
        return (isinstance(other, TreeEntry)
181
                and other.__class__ == self.__class__)
182
 
183
    def kind_character(self):
184
        return "???"
185
186
187
class TreeDirectory(TreeEntry):
188
    """See TreeEntry. This is a directory in a working tree."""
189
190
    def __eq__(self, other):
191
        return (isinstance(other, TreeDirectory)
192
                and other.__class__ == self.__class__)
193
194
    def kind_character(self):
195
        return "/"
196
197
198
class TreeFile(TreeEntry):
199
    """See TreeEntry. This is a regular file in a working tree."""
200
201
    def __eq__(self, other):
202
        return (isinstance(other, TreeFile)
203
                and other.__class__ == self.__class__)
204
205
    def kind_character(self):
206
        return ''
207
208
209
class TreeLink(TreeEntry):
210
    """See TreeEntry. This is a symlink in a working tree."""
211
212
    def __eq__(self, other):
213
        return (isinstance(other, TreeLink)
214
                and other.__class__ == self.__class__)
215
216
    def kind_character(self):
217
        return ''
218
219
453 by Martin Pool
- Split WorkingTree into its own file
220
class WorkingTree(bzrlib.tree.Tree):
221
    """Working copy tree.
222
223
    The inventory is held in the `Branch` working-inventory, and the
224
    files are in a directory on disk.
225
226
    It is possible for a `WorkingTree` to have a filename which is
227
    not listed in the Inventory and vice versa.
228
    """
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
229
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
230
    def __init__(self, basedir='.',
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
231
                 branch=DEPRECATED_PARAMETER,
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
232
                 _inventory=None,
233
                 _control_files=None,
234
                 _internal=False,
235
                 _format=None,
236
                 _bzrdir=None):
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
237
        """Construct a WorkingTree for basedir.
238
239
        If the branch is not supplied, it is opened automatically.
240
        If the branch is supplied, it must be the branch for this basedir.
241
        (branch.base is not cross checked, because for remote branches that
242
        would be meaningless).
243
        """
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.
244
        self._format = _format
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
245
        self.bzrdir = _bzrdir
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
246
        if not _internal:
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
247
            # not created via open etc.
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
248
            warnings.warn("WorkingTree() is deprecated as of bzr version 0.8. "
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
249
                 "Please use bzrdir.open_workingtree or WorkingTree.open().",
250
                 DeprecationWarning,
251
                 stacklevel=2)
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.
252
            wt = WorkingTree.open(basedir)
1681.1.1 by Robert Collins
Make WorkingTree.branch a read only property. (Robert Collins)
253
            self._branch = wt.branch
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
254
            self.basedir = wt.basedir
255
            self._control_files = wt._control_files
256
            self._hashcache = wt._hashcache
257
            self._set_inventory(wt._inventory)
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.
258
            self._format = wt._format
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
259
            self.bzrdir = wt.bzrdir
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
260
        from bzrlib.hashcache import HashCache
261
        from bzrlib.trace import note, mutter
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
262
        assert isinstance(basedir, basestring), \
263
            "base directory %r is not a string" % basedir
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
264
        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.
265
        mutter("opening working tree %r", basedir)
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
266
        if deprecated_passed(branch):
267
            if not _internal:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
268
                warnings.warn("WorkingTree(..., branch=XXX) is deprecated as of bzr 0.8."
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
269
                     " Please use bzrdir.open_workingtree() or"
270
                     " WorkingTree.open().",
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
271
                     DeprecationWarning,
272
                     stacklevel=2
273
                     )
1681.1.1 by Robert Collins
Make WorkingTree.branch a read only property. (Robert Collins)
274
            self._branch = branch
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
275
        else:
1681.1.1 by Robert Collins
Make WorkingTree.branch a read only property. (Robert Collins)
276
            self._branch = self.bzrdir.open_branch()
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
277
        self.basedir = realpath(basedir)
1534.4.28 by Robert Collins
first cut at merge from integration.
278
        # if branch is at our basedir and is a format 6 or less
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
279
        if isinstance(self._format, WorkingTreeFormat2):
280
            # share control object
1534.4.28 by Robert Collins
first cut at merge from integration.
281
            self._control_files = self.branch.control_files
282
        else:
1852.3.1 by Robert Collins
Trivial cleanups to workingtree.py
283
            # assume all other formats have their own control files.
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
284
            assert isinstance(_control_files, LockableFiles), \
285
                    "_control_files must be a LockableFiles, not %r" \
286
                    % _control_files
287
            self._control_files = _control_files
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
288
        # update the whole cache up front and write to disk if anything changed;
289
        # in the future we might want to do this more selectively
1467 by Robert Collins
WorkingTree.__del__ has been removed.
290
        # two possible ways offer themselves : in self._unlock, write the cache
291
        # if needed, or, when the cache sees a change, append it to the hash
292
        # cache file, and have the parser take the most recent entry for a
293
        # given path only.
1685.1.9 by John Arbash Meinel
Updated LocalTransport so that it's base is now a URL rather than a local path. This helps consistency with all other functions. To do so, I added local_abspath() which returns the local path, and local_path_to/from_url
294
        cache_filename = self.bzrdir.get_workingtree_transport(None).local_abspath('stat-cache')
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
295
        hc = self._hashcache = HashCache(basedir, cache_filename, self._control_files._file_mode)
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
296
        hc.read()
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.
297
        # is this scan needed ? it makes things kinda slow.
1732.1.20 by John Arbash Meinel
hash cache pre-scan cost us ~500ms on a kernel sized tree
298
        #hc.scan()
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
299
300
        if hc.needs_write:
301
            mutter("write hc")
302
            hc.write()
453 by Martin Pool
- Split WorkingTree into its own file
303
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
304
        if _inventory is None:
305
            self._set_inventory(self.read_working_inventory())
306
        else:
307
            self._set_inventory(_inventory)
1185.60.6 by Aaron Bentley
Fixed hashcache
308
1681.1.1 by Robert Collins
Make WorkingTree.branch a read only property. (Robert Collins)
309
    branch = property(
310
        fget=lambda self: self._branch,
311
        doc="""The branch this WorkingTree is connected to.
312
313
            This cannot be set - it is reflective of the actual disk structure
314
            the working tree has been constructed from.
315
            """)
316
1687.1.9 by Robert Collins
Teach WorkingTree about break-lock.
317
    def break_lock(self):
318
        """Break a lock if one is present from another instance.
319
320
        Uses the ui factory to ask for confirmation if the lock may be from
321
        an active process.
322
323
        This will probe the repository for its lock as well.
324
        """
325
        self._control_files.break_lock()
326
        self.branch.break_lock()
327
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
328
    def _set_inventory(self, inv):
1910.2.6 by Aaron Bentley
Update for merge review, handle deprecations
329
        assert inv.root is not None
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
330
        self._inventory = inv
331
        self.path2id = self._inventory.path2id
332
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
333
    def is_control_filename(self, filename):
1534.5.16 by Robert Collins
Review feedback.
334
        """True if filename is the name of a control file in this tree.
335
        
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
336
        :param filename: A filename within the tree. This is a relative path
337
        from the root of this tree.
338
1534.5.16 by Robert Collins
Review feedback.
339
        This is true IF and ONLY IF the filename is part of the meta data
340
        that bzr controls in this tree. I.E. a random .bzr directory placed
341
        on disk will not be a control file for this tree.
342
        """
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
343
        return self.bzrdir.is_control_filename(filename)
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
344
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
345
    @staticmethod
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
346
    def open(path=None, _unsupported=False):
347
        """Open an existing working tree at path.
348
349
        """
350
        if path is None:
351
            path = os.path.getcwdu()
352
        control = bzrdir.BzrDir.open(path, _unsupported)
353
        return control.open_workingtree(_unsupported)
354
        
355
    @staticmethod
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
356
    def open_containing(path=None):
357
        """Open an existing working tree which has its root about path.
358
        
359
        This probes for a working tree at path and searches upwards from there.
360
361
        Basically we keep looking up until we find the control directory or
362
        run into /.  If there isn't one, raises NotBranchError.
363
        TODO: give this a new exception.
364
        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
365
366
        :return: The WorkingTree that contains 'path', and the rest of path
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
367
        """
368
        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
369
            path = osutils.getcwd()
1685.1.28 by John Arbash Meinel
Changing open_containing to always return a unicode path.
370
        control, relpath = bzrdir.BzrDir.open_containing(path)
1685.1.27 by John Arbash Meinel
BzrDir works in URLs, but WorkingTree works in unicode paths
371
1685.1.28 by John Arbash Meinel
Changing open_containing to always return a unicode path.
372
        return control.open_workingtree(), relpath
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
373
374
    @staticmethod
375
    def open_downlevel(path=None):
376
        """Open an unsupported working tree.
377
378
        Only intended for advanced situations like upgrading part of a bzrdir.
379
        """
380
        return WorkingTree.open(path, _unsupported=True)
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
381
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
382
    def __iter__(self):
383
        """Iterate through file_ids for this tree.
384
385
        file_ids are in a WorkingTree if they are in the working inventory
386
        and the working file exists.
387
        """
388
        inv = self._inventory
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
389
        for path, ie in inv.iter_entries():
1836.1.22 by John Arbash Meinel
[merge] bzr.dev 1861
390
            if osutils.lexists(self.abspath(path)):
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
391
                yield ie.file_id
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
392
453 by Martin Pool
- Split WorkingTree into its own file
393
    def __repr__(self):
394
        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
395
                               getattr(self, 'basedir', None))
453 by Martin Pool
- Split WorkingTree into its own file
396
397
    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 \
398
        return pathjoin(self.basedir, filename)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
399
    
400
    def basis_tree(self):
1927.2.3 by Robert Collins
review comment application - paired with Martin.
401
        """Return RevisionTree for the current last revision.
402
        
403
        If the left most parent is a ghost then the returned tree will be an
404
        empty tree - one obtained by calling repository.revision_tree(None).
405
        """
1908.11.2 by Robert Collins
Implement WorkingTree interface conformance tests for
406
        revision_id = self.last_revision()
407
        if revision_id is None:
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
408
            # no parents, return an empty revision tree.
409
            # in the future this should return the tree for
410
            # 'empty:' - the implicit root empty tree.
411
            return self.branch.repository.revision_tree(None)
1908.11.2 by Robert Collins
Implement WorkingTree interface conformance tests for
412
        try:
413
            return self.revision_tree(revision_id)
414
        except errors.NoSuchRevision:
415
            pass
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
416
        # No cached copy available, retrieve from the repository.
417
        # FIXME? RBC 20060403 should we cache the inventory locally
418
        # 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.
419
        try:
420
            return self.branch.repository.revision_tree(revision_id)
421
        except errors.RevisionNotPresent:
422
            # the basis tree *may* be a ghost or a low level error may have
423
            # occured. If the revision is present, its a problem, if its not
424
            # its a ghost.
425
            if self.branch.repository.has_revision(revision_id):
426
                raise
1927.2.3 by Robert Collins
review comment application - paired with Martin.
427
            # the basis tree is a ghost so return an empty tree.
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
            return self.branch.repository.revision_tree(None)
453 by Martin Pool
- Split WorkingTree into its own file
429
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
430
    @staticmethod
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
431
    @deprecated_method(zero_eight)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
432
    def create(branch, directory):
433
        """Create a workingtree for branch at directory.
434
435
        If existing_directory already exists it must have a .bzr directory.
436
        If it does not exist, it will be created.
437
438
        This returns a new WorkingTree object for the new checkout.
439
440
        TODO FIXME RBC 20060124 when we have checkout formats in place this
441
        should accept an optional revisionid to checkout [and reject this if
442
        checking out into the same dir as a pre-checkout-aware branch format.]
1551.1.2 by Martin Pool
Deprecation warnings for popular APIs that will change in BzrDir
443
444
        XXX: When BzrDir is present, these should be created through that 
445
        interface instead.
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
446
        """
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
447
        warnings.warn('delete WorkingTree.create', stacklevel=3)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
448
        transport = get_transport(directory)
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.
449
        if branch.bzrdir.root_transport.base == transport.base:
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
450
            # same dir 
451
            return branch.bzrdir.create_workingtree()
452
        # different directory, 
453
        # create a branch reference
454
        # and now a working tree.
455
        raise NotImplementedError
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
456
 
457
    @staticmethod
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
458
    @deprecated_method(zero_eight)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
459
    def create_standalone(directory):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
460
        """Create a checkout and a branch and a repo at directory.
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
461
462
        Directory must exist and be empty.
1551.1.2 by Martin Pool
Deprecation warnings for popular APIs that will change in BzrDir
463
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
464
        please use BzrDir.create_standalone_workingtree
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
465
        """
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
466
        return bzrdir.BzrDir.create_standalone_workingtree(directory)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
467
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
468
    def relpath(self, path):
469
        """Return the local path portion from a given path.
470
        
471
        The path may be absolute or relative. If its a relative path it is 
472
        interpreted relative to the python current working directory.
473
        """
474
        return relpath(self.basedir, path)
1457.1.3 by Robert Collins
make Branch.relpath delegate to the working tree.
475
453 by Martin Pool
- Split WorkingTree into its own file
476
    def has_filename(self, filename):
1836.1.22 by John Arbash Meinel
[merge] bzr.dev 1861
477
        return osutils.lexists(self.abspath(filename))
453 by Martin Pool
- Split WorkingTree into its own file
478
479
    def get_file(self, file_id):
480
        return self.get_file_byname(self.id2path(file_id))
481
1852.6.9 by Robert Collins
Add more test trees to the tree-implementations tests.
482
    def get_file_text(self, file_id):
483
        return self.get_file(file_id).read()
484
453 by Martin Pool
- Split WorkingTree into its own file
485
    def get_file_byname(self, filename):
486
        return file(self.abspath(filename), 'rb')
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.
490
        
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
        """
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
494
        last_rev = self._last_revision()
1773.2.1 by Robert Collins
Teach all trees about unknowns, conflicts and get_parent_ids.
495
        if last_rev is None:
496
            parents = []
497
        else:
498
            parents = [last_rev]
1908.6.10 by Robert Collins
forward to get_parent_ids in pending_merges.
499
        try:
500
            merges_file = self._control_files.get_utf8('pending-merges')
501
        except NoSuchFile:
502
            pass
503
        else:
504
            for l in merges_file.readlines():
505
                parents.append(l.rstrip('\n'))
506
        return parents
1773.2.1 by Robert Collins
Teach all trees about unknowns, conflicts and get_parent_ids.
507
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
508
    def get_root_id(self):
509
        """Return the id of this trees root"""
510
        inv = self.read_working_inventory()
511
        return inv.root.file_id
512
        
453 by Martin Pool
- Split WorkingTree into its own file
513
    def _get_store_filename(self, file_id):
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
514
        ## XXX: badly named; this is not in the store at all
453 by Martin Pool
- Split WorkingTree into its own file
515
        return self.abspath(self.id2path(file_id))
516
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
517
    @needs_read_lock
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.
518
    def clone(self, to_bzrdir, revision_id=None, basis=None):
519
        """Duplicate this working tree into to_bzr, including all state.
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
520
        
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.
521
        Specifically modified files are kept as modified, but
522
        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()
523
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.
524
        If you want to make a new line of development, see bzrdir.sprout()
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
525
526
        revision
527
            If not None, the cloned tree will have its last revision set to 
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.
528
            revision, and and difference between the source trees last revision
529
            and this one merged in.
530
531
        basis
532
            If not None, a closer copy of a tree which may have some files in
533
            common, and which file content should be preferentially copied from.
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
534
        """
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.
535
        # assumes the target bzr dir format is compatible.
536
        result = self._format.initialize(to_bzrdir)
537
        self.copy_content_into(result, revision_id)
538
        return result
539
540
    @needs_read_lock
541
    def copy_content_into(self, tree, revision_id=None):
542
        """Copy the current content and user files of this tree into tree."""
543
        if revision_id is None:
544
            transform_tree(tree, self)
545
        else:
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
546
            # TODO now merge from tree.last_revision to revision (to preserve
547
            # user local changes)
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.
548
            transform_tree(tree, self)
1908.6.3 by Robert Collins
Tidy up the last_revision_id and add_pending_merge conversion to use cleaner apis.
549
            tree.set_parent_ids([revision_id])
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
550
1457.1.17 by Robert Collins
Branch.commit() has moved to WorkingTree.commit(). (Robert Collins)
551
    @needs_write_lock
1593.1.1 by Robert Collins
Move responsibility for setting branch nickname in commits to the WorkingTree convenience function.
552
    def commit(self, message=None, revprops=None, *args, **kwargs):
553
        # avoid circular imports
1457.1.17 by Robert Collins
Branch.commit() has moved to WorkingTree.commit(). (Robert Collins)
554
        from bzrlib.commit import Commit
1593.1.1 by Robert Collins
Move responsibility for setting branch nickname in commits to the WorkingTree convenience function.
555
        if revprops is None:
556
            revprops = {}
557
        if not 'branch-nick' in revprops:
558
            revprops['branch-nick'] = self.branch.nick
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
559
        # args for wt.commit start at message from the Commit.commit method,
560
        # but with branch a kwarg now, passing in args as is results in the
561
        #message being used for the branch
1593.1.1 by Robert Collins
Move responsibility for setting branch nickname in commits to the WorkingTree convenience function.
562
        args = (DEPRECATED_PARAMETER, message, ) + args
1773.1.1 by Robert Collins
Teach WorkingTree.commit to return the committed revision id.
563
        committed_id = Commit().commit( working_tree=self, revprops=revprops,
564
            *args, **kwargs)
565
        return committed_id
1248 by Martin Pool
- new weave based cleanup [broken]
566
567
    def id2abspath(self, file_id):
568
        return self.abspath(self.id2path(file_id))
569
1185.12.39 by abentley
Propogated has_or_had_id to Tree
570
    def has_id(self, file_id):
453 by Martin Pool
- Split WorkingTree into its own file
571
        # files that have been deleted are excluded
1185.12.39 by abentley
Propogated has_or_had_id to Tree
572
        inv = self._inventory
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
573
        if not inv.has_id(file_id):
453 by Martin Pool
- Split WorkingTree into its own file
574
            return False
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
575
        path = inv.id2path(file_id)
1836.1.22 by John Arbash Meinel
[merge] bzr.dev 1861
576
        return osutils.lexists(self.abspath(path))
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
577
1185.12.39 by abentley
Propogated has_or_had_id to Tree
578
    def has_or_had_id(self, file_id):
579
        if file_id == self.inventory.root.file_id:
580
            return True
581
        return self.inventory.has_id(file_id)
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
582
583
    __contains__ = has_id
584
453 by Martin Pool
- Split WorkingTree into its own file
585
    def get_file_size(self, file_id):
1248 by Martin Pool
- new weave based cleanup [broken]
586
        return os.path.getsize(self.id2abspath(file_id))
453 by Martin Pool
- Split WorkingTree into its own file
587
1185.60.6 by Aaron Bentley
Fixed hashcache
588
    @needs_read_lock
1732.1.19 by John Arbash Meinel
If you have the path, use it rather than looking it up again
589
    def get_file_sha1(self, file_id, path=None):
590
        if not path:
591
            path = self._inventory.id2path(file_id)
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
592
        return self._hashcache.get_sha1(path)
453 by Martin Pool
- Split WorkingTree into its own file
593
1740.2.5 by Aaron Bentley
Merge from bzr.dev
594
    def get_file_mtime(self, file_id, path=None):
595
        if not path:
596
            path = self._inventory.id2path(file_id)
597
        return os.lstat(self.abspath(path)).st_mtime
598
1732.1.19 by John Arbash Meinel
If you have the path, use it rather than looking it up again
599
    if not supports_executable():
600
        def is_executable(self, file_id, path=None):
1398 by Robert Collins
integrate in Gustavos x-bit patch
601
            return self._inventory[file_id].executable
1732.1.19 by John Arbash Meinel
If you have the path, use it rather than looking it up again
602
    else:
603
        def is_executable(self, file_id, path=None):
604
            if not path:
605
                path = self._inventory.id2path(file_id)
1398 by Robert Collins
integrate in Gustavos x-bit patch
606
            mode = os.lstat(self.abspath(path)).st_mode
1733.1.4 by Robert Collins
Cosmetic niceties for debugging, extra comments etc.
607
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1398 by Robert Collins
integrate in Gustavos x-bit patch
608
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
609
    @needs_write_lock
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
610
    def add(self, files, ids=None):
611
        """Make files versioned.
612
613
        Note that the command line normally calls smart_add instead,
614
        which can automatically recurse.
615
616
        This adds the files to the inventory, so that they will be
617
        recorded by the next commit.
618
619
        files
620
            List of paths to add, relative to the base of the tree.
621
622
        ids
623
            If set, use these instead of automatically generated ids.
624
            Must be the same length as the list of files, but may
625
            contain None for ids that are to be autogenerated.
626
627
        TODO: Perhaps have an option to add the ids even if the files do
628
              not (yet) exist.
629
630
        TODO: Perhaps callback with the ids and paths as they're added.
631
        """
632
        # TODO: Re-adding a file that is removed in the working copy
633
        # should probably put it back with the previous ID.
634
        if isinstance(files, basestring):
635
            assert(ids is None or isinstance(ids, basestring))
636
            files = [files]
637
            if ids is not None:
638
                ids = [ids]
639
640
        if ids is None:
641
            ids = [None] * len(files)
642
        else:
643
            assert(len(ids) == len(files))
644
645
        inv = self.read_working_inventory()
646
        for f,file_id in zip(files, ids):
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
647
            if self.is_control_filename(f):
1773.4.2 by Martin Pool
Cleanup of imports; undeprecate all_revision_ids()
648
                raise errors.ForbiddenControlFileError(filename=f)
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
649
650
            fp = splitpath(f)
651
652
            if len(fp) == 0:
653
                raise BzrError("cannot add top-level %r" % f)
654
1185.31.38 by John Arbash Meinel
Changing os.path.normpath to osutils.normpath
655
            fullpath = normpath(self.abspath(f))
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
656
            try:
657
                kind = file_kind(fullpath)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
658
            except OSError, e:
659
                if e.errno == errno.ENOENT:
660
                    raise NoSuchFile(fullpath)
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
661
            if not InventoryEntry.versionable_kind(kind):
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
662
                raise errors.BadFileKindError(filename=f, kind=kind)
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
663
            if file_id is None:
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
664
                inv.add_path(f, kind=kind)
665
            else:
666
                inv.add_path(f, kind=kind, file_id=file_id)
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
667
668
        self._write_inventory(inv)
669
670
    @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.
671
    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.
672
        """Add revision_id as a parent.
673
674
        This is equivalent to retrieving the current list of parent ids
675
        and setting the list to its value plus revision_id.
676
677
        :param revision_id: The revision id to add to the parent list. It may
1908.5.12 by Robert Collins
Apply review feedback - paired with Martin.
678
        be a ghost revision as long as its not the first parent to be added,
679
        or the allow_leftmost_as_ghost parameter is set True.
680
        :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.
681
        """
1908.5.13 by Robert Collins
Adding a parent when the first is a ghost already should not require forcing it.
682
        parents = self.get_parent_ids() + [revision_id]
683
        self.set_parent_ids(parents,
684
            allow_leftmost_as_ghost=len(parents) > 1 or allow_leftmost_as_ghost)
1908.5.4 by Robert Collins
Add add_parent_tree_id WorkingTree helper api.
685
686
    @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.
687
    def add_parent_tree(self, parent_tuple, allow_leftmost_as_ghost=False):
1908.5.6 by Robert Collins
Add add_parent_tree to WorkingTree.
688
        """Add revision_id, tree tuple as a parent.
689
690
        This is equivalent to retrieving the current list of parent trees
691
        and setting the list to its value plus parent_tuple. See also
692
        add_parent_tree_id - if you only have a parent id available it will be
693
        simpler to use that api. If you have the parent already available, using
694
        this api is preferred.
695
1908.5.12 by Robert Collins
Apply review feedback - paired with Martin.
696
        :param parent_tuple: The (revision id, tree) to add to the parent list.
697
            If the revision_id is a ghost, pass None for the tree.
698
        :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.
699
        """
1979.2.1 by Robert Collins
(robertc) adds a convenience method "merge_from_branch" to WorkingTree.
700
        parent_ids = self.get_parent_ids() + [parent_tuple[0]]
701
        if len(parent_ids) > 1:
702
            # the leftmost may have already been a ghost, preserve that if it
703
            # was.
704
            allow_leftmost_as_ghost = True
705
        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.
706
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
1908.5.6 by Robert Collins
Add add_parent_tree to WorkingTree.
707
708
    @needs_write_lock
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
709
    def add_pending_merge(self, *revision_ids):
710
        # TODO: Perhaps should check at this point that the
711
        # 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.
712
        parents = self.get_parent_ids()
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
713
        updated = False
714
        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.
715
            if rev_id in parents:
716
                continue
717
            parents.append(rev_id)
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
718
            updated = True
719
        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.
720
            self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
721
1908.7.7 by Robert Collins
Deprecated WorkingTree.pending_merges.
722
    @deprecated_method(zero_eleven)
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
723
    @needs_read_lock
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
724
    def pending_merges(self):
725
        """Return a list of pending merges.
726
727
        These are revisions that have been merged into the working
728
        directory but not yet committed.
1908.7.9 by Robert Collins
WorkingTree.last_revision and WorkingTree.pending_merges are deprecated.
729
730
        As of 0.11 this is deprecated. Please see WorkingTree.get_parent_ids()
731
        instead - which is available on all tree objects.
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
732
        """
1908.6.10 by Robert Collins
forward to get_parent_ids in pending_merges.
733
        return self.get_parent_ids()[1:]
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
734
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
735
    @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.
736
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
1908.5.5 by Robert Collins
Add WorkingTree.set_parent_ids.
737
        """Set the parent ids to revision_ids.
738
        
739
        See also set_parent_trees. This api will try to retrieve the tree data
740
        for each element of revision_ids from the trees repository. If you have
741
        tree data already available, it is more efficient to use
742
        set_parent_trees rather than set_parent_ids. set_parent_ids is however
743
        an easier API to use.
744
745
        :param revision_ids: The revision_ids to set as the parent ids of this
746
            working tree. Any of these may be ghosts.
747
        """
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
748
        if len(revision_ids) > 0:
749
            leftmost_id = revision_ids[0]
750
            if (not allow_leftmost_as_ghost and not
751
                self.branch.repository.has_revision(leftmost_id)):
752
                raise errors.GhostRevisionUnusableHere(leftmost_id)
753
            self.set_last_revision(leftmost_id)
754
        else:
755
            self.set_last_revision(None)
756
        merges = revision_ids[1:]
757
        self._control_files.put_utf8('pending-merges', '\n'.join(merges))
1908.5.5 by Robert Collins
Add WorkingTree.set_parent_ids.
758
759
    @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.
760
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
1908.5.2 by Robert Collins
Create and test set_parent_trees.
761
        """Set the parents of the working tree.
762
763
        :param parents_list: A list of (revision_id, tree) tuples. 
764
            If tree is None, then that element is treated as an unreachable
765
            parent tree - i.e. a ghost.
766
        """
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
767
        # parent trees are not used in current format trees, delegate to
768
        # set_parent_ids
769
        self.set_parent_ids([rev for (rev, tree) in parents_list],
770
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
1908.5.2 by Robert Collins
Create and test set_parent_trees.
771
772
    @needs_write_lock
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
773
    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.
774
        parents = self.get_parent_ids()
775
        leftmost = parents[:1]
776
        new_parents = leftmost + rev_list
777
        self.set_parent_ids(new_parents)
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
778
1534.7.192 by Aaron Bentley
Record hashes produced by merges
779
    @needs_write_lock
780
    def set_merge_modified(self, modified_hashes):
1534.10.3 by Aaron Bentley
Simplify set_merge_modified with rio_file
781
        def iter_stanzas():
782
            for file_id, hash in modified_hashes.iteritems():
783
                yield Stanza(file_id=file_id, hash=hash)
784
        self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
785
786
    @needs_write_lock
787
    def _put_rio(self, filename, stanzas, header):
788
        my_file = rio_file(stanzas, header)
789
        self._control_files.put(filename, my_file)
1534.7.192 by Aaron Bentley
Record hashes produced by merges
790
1979.2.1 by Robert Collins
(robertc) adds a convenience method "merge_from_branch" to WorkingTree.
791
    @needs_write_lock
792
    def merge_from_branch(self, branch, to_revision=None):
793
        """Merge from a branch into this working tree.
794
795
        :param branch: The branch to merge from.
796
        :param to_revision: If non-None, the merge will merge to to_revision, but 
797
            not beyond it. to_revision does not need to be in the history of
798
            the branch when it is supplied. If None, to_revision defaults to
799
            branch.last_revision().
800
        """
801
        from bzrlib.merge import Merger, Merge3Merger
802
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
803
        try:
804
            merger = Merger(self.branch, this_tree=self, pb=pb)
805
            merger.pp = ProgressPhase("Merge phase", 5, pb)
806
            merger.pp.next_phase()
807
            # check that there are no
808
            # local alterations
809
            merger.check_basis(check_clean=True, require_commits=False)
810
            if to_revision is None:
811
                to_revision = branch.last_revision()
812
            merger.other_rev_id = to_revision
813
            if merger.other_rev_id is None:
814
                raise error.NoCommits(branch)
815
            self.branch.fetch(branch, last_revision=merger.other_rev_id)
816
            merger.other_basis = merger.other_rev_id
817
            merger.other_tree = self.branch.repository.revision_tree(
818
                merger.other_rev_id)
819
            merger.pp.next_phase()
820
            merger.find_base()
821
            if merger.base_rev_id == merger.other_rev_id:
822
                raise errors.PointlessMerge
823
            merger.backup_files = False
824
            merger.merge_type = Merge3Merger
825
            merger.set_interesting_files(None)
826
            merger.show_base = False
827
            merger.reprocess = False
828
            conflicts = merger.do_merge()
829
            merger.set_pending()
830
        finally:
831
            pb.finished()
832
        return conflicts
833
1534.7.192 by Aaron Bentley
Record hashes produced by merges
834
    @needs_read_lock
835
    def merge_modified(self):
836
        try:
837
            hashfile = self._control_files.get('merge-hashes')
838
        except NoSuchFile:
839
            return {}
1534.7.196 by Aaron Bentley
Switched to Rio format for merge-modified list
840
        merge_hashes = {}
841
        try:
842
            if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
843
                raise MergeModifiedFormatError()
844
        except StopIteration:
845
            raise MergeModifiedFormatError()
846
        for s in RioReader(hashfile):
1534.7.198 by Aaron Bentley
Removed spurious encode/decode
847
            file_id = s.get("file_id")
1558.12.10 by Aaron Bentley
Be robust when merge_hash file_id not in inventory
848
            if file_id not in self.inventory:
849
                continue
1534.7.196 by Aaron Bentley
Switched to Rio format for merge-modified list
850
            hash = s.get("hash")
851
            if hash == self.get_file_sha1(file_id):
852
                merge_hashes[file_id] = hash
853
        return merge_hashes
1534.7.192 by Aaron Bentley
Record hashes produced by merges
854
1092.2.6 by Robert Collins
symlink support updated to work
855
    def get_symlink_target(self, file_id):
1185.15.10 by Scott James Remnant
Fix WorkingTree.get_symlink_target() to read the absolute path of the
856
        return os.readlink(self.id2abspath(file_id))
453 by Martin Pool
- Split WorkingTree into its own file
857
858
    def file_class(self, filename):
859
        if self.path2id(filename):
860
            return 'V'
861
        elif self.is_ignored(filename):
862
            return 'I'
863
        else:
864
            return '?'
865
1907.1.1 by Aaron Bentley
Unshelved all changes except those related to removing RootEntry
866
    def list_files(self):
1732.1.6 by John Arbash Meinel
Fix documentation bug in workingtree.list_files
867
        """Recursively list all files as (path, class, kind, id, entry).
453 by Martin Pool
- Split WorkingTree into its own file
868
869
        Lists, but does not descend into unversioned directories.
870
871
        This does not include files that have been deleted in this
872
        tree.
873
874
        Skips the control directory.
875
        """
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
876
        inv = self._inventory
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
877
        # Convert these into local objects to save lookup times
1836.1.22 by John Arbash Meinel
[merge] bzr.dev 1861
878
        pathjoin = osutils.pathjoin
879
        file_kind = osutils.file_kind
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
880
881
        # transport.base ends in a slash, we want the piece
882
        # between the last two slashes
883
        transport_base_dir = self.bzrdir.transport.base.rsplit('/', 2)[1]
884
1732.1.11 by John Arbash Meinel
Trying multiple things to get WorkingTree.list_files time down
885
        fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
886
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
887
        # directory file_id, relative path, absolute path, reverse sorted children
888
        children = os.listdir(self.basedir)
889
        children.sort()
1732.1.14 by John Arbash Meinel
Some speedups by not calling pathjoin()
890
        # jam 20060527 The kernel sized tree seems equivalent whether we 
891
        # use a deque and popleft to keep them sorted, or if we use a plain
892
        # list and just reverse() them.
1732.1.13 by John Arbash Meinel
A large improvement from not popping the parent off until we have done all children.
893
        children = collections.deque(children)
1732.1.21 by John Arbash Meinel
We don't need to strip off 2 characters, just do one, minor memory improvement
894
        stack = [(inv.root.file_id, u'', self.basedir, children)]
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
895
        while stack:
1732.1.13 by John Arbash Meinel
A large improvement from not popping the parent off until we have done all children.
896
            from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
897
898
            while children:
1732.1.13 by John Arbash Meinel
A large improvement from not popping the parent off until we have done all children.
899
                f = children.popleft()
453 by Martin Pool
- Split WorkingTree into its own file
900
                ## TODO: If we find a subdirectory with its own .bzr
901
                ## directory, then that is a separate tree and we
902
                ## should exclude it.
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
903
904
                # the bzrdir for this tree
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
905
                if transport_base_dir == f:
453 by Martin Pool
- Split WorkingTree into its own file
906
                    continue
907
1732.1.14 by John Arbash Meinel
Some speedups by not calling pathjoin()
908
                # we know that from_dir_relpath and from_dir_abspath never end in a slash
909
                # and 'f' doesn't begin with one, we can do a string op, rather
1732.1.21 by John Arbash Meinel
We don't need to strip off 2 characters, just do one, minor memory improvement
910
                # than the checks of pathjoin(), all relative paths will have an extra slash
911
                # at the beginning
1732.1.14 by John Arbash Meinel
Some speedups by not calling pathjoin()
912
                fp = from_dir_relpath + '/' + f
453 by Martin Pool
- Split WorkingTree into its own file
913
914
                # absolute path
1732.1.14 by John Arbash Meinel
Some speedups by not calling pathjoin()
915
                fap = from_dir_abspath + '/' + f
453 by Martin Pool
- Split WorkingTree into its own file
916
                
917
                f_ie = inv.get_child(from_dir_id, f)
918
                if f_ie:
919
                    c = 'V'
1551.6.36 by Aaron Bentley
Revert --debris/--detritus changes
920
                elif self.is_ignored(fp[1:]):
921
                    c = 'I'
453 by Martin Pool
- Split WorkingTree into its own file
922
                else:
1830.3.3 by John Arbash Meinel
inside workingtree check for normalized filename access
923
                    # we may not have found this file, because of a unicode issue
924
                    f_norm, can_access = osutils.normalized_filename(f)
925
                    if f == f_norm or not can_access:
926
                        # No change, so treat this file normally
927
                        c = '?'
928
                    else:
929
                        # this file can be accessed by a normalized path
930
                        # check again if it is versioned
931
                        # these lines are repeated here for performance
932
                        f = f_norm
933
                        fp = from_dir_relpath + '/' + f
934
                        fap = from_dir_abspath + '/' + f
935
                        f_ie = inv.get_child(from_dir_id, f)
936
                        if f_ie:
937
                            c = 'V'
938
                        elif self.is_ignored(fp[1:]):
939
                            c = 'I'
940
                        else:
941
                            c = '?'
453 by Martin Pool
- Split WorkingTree into its own file
942
943
                fk = file_kind(fap)
944
945
                if f_ie:
946
                    if f_ie.kind != fk:
947
                        raise BzrCheckError("file %r entered as kind %r id %r, "
948
                                            "now of kind %r"
949
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
950
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
951
                # make a last minute entry
952
                if f_ie:
1732.1.21 by John Arbash Meinel
We don't need to strip off 2 characters, just do one, minor memory improvement
953
                    yield fp[1:], c, fk, f_ie.file_id, f_ie
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
954
                else:
1732.1.11 by John Arbash Meinel
Trying multiple things to get WorkingTree.list_files time down
955
                    try:
1732.1.21 by John Arbash Meinel
We don't need to strip off 2 characters, just do one, minor memory improvement
956
                        yield fp[1:], c, fk, None, fk_entries[fk]()
1732.1.11 by John Arbash Meinel
Trying multiple things to get WorkingTree.list_files time down
957
                    except KeyError:
1732.1.21 by John Arbash Meinel
We don't need to strip off 2 characters, just do one, minor memory improvement
958
                        yield fp[1:], c, fk, None, TreeEntry()
1732.1.13 by John Arbash Meinel
A large improvement from not popping the parent off until we have done all children.
959
                    continue
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
960
                
453 by Martin Pool
- Split WorkingTree into its own file
961
                if fk != 'directory':
962
                    continue
963
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
964
                # But do this child first
1732.1.13 by John Arbash Meinel
A large improvement from not popping the parent off until we have done all children.
965
                new_children = os.listdir(fap)
966
                new_children.sort()
967
                new_children = collections.deque(new_children)
968
                stack.append((f_ie.file_id, fp, fap, new_children))
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
969
                # Break out of inner loop, so that we start outer loop with child
970
                break
1732.1.22 by John Arbash Meinel
Bug in list_files if the last entry in a directory is another directory
971
            else:
972
                # if we finished all children, pop it off the stack
1732.1.25 by John Arbash Meinel
Fix list_files test, we don't need to check if children are empty if we fall off the loop.
973
                stack.pop()
1732.1.13 by John Arbash Meinel
A large improvement from not popping the parent off until we have done all children.
974
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
975
976
    @needs_write_lock
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
977
    def move(self, from_paths, to_name):
978
        """Rename files.
979
980
        to_name must exist in the inventory.
981
982
        If to_name exists and is a directory, the files are moved into
983
        it, keeping their old names.  
984
985
        Note that to_name is only the last component of the new name;
986
        this doesn't change the directory.
987
988
        This returns a list of (from_path, to_path) pairs for each
989
        entry that is moved.
990
        """
991
        result = []
992
        ## TODO: Option to move IDs only
993
        assert not isinstance(from_paths, basestring)
994
        inv = self.inventory
995
        to_abs = self.abspath(to_name)
996
        if not isdir(to_abs):
997
            raise BzrError("destination %r is not a directory" % to_abs)
998
        if not self.has_filename(to_name):
999
            raise BzrError("destination %r not in working directory" % to_abs)
1000
        to_dir_id = inv.path2id(to_name)
1001
        if to_dir_id == None and to_name != '':
1002
            raise BzrError("destination %r is not a versioned directory" % to_name)
1003
        to_dir_ie = inv[to_dir_id]
1731.1.2 by Aaron Bentley
Removed all remaining uses of root_directory
1004
        if to_dir_ie.kind != 'directory':
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1005
            raise BzrError("destination %r is not a directory" % to_abs)
1006
1007
        to_idpath = inv.get_idpath(to_dir_id)
1008
1009
        for f in from_paths:
1010
            if not self.has_filename(f):
1011
                raise BzrError("%r does not exist in working tree" % f)
1012
            f_id = inv.path2id(f)
1013
            if f_id == None:
1014
                raise BzrError("%r is not versioned" % f)
1015
            name_tail = splitpath(f)[-1]
1732.1.1 by John Arbash Meinel
deprecating appendpath, it does exactly what pathjoin does
1016
            dest_path = pathjoin(to_name, name_tail)
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1017
            if self.has_filename(dest_path):
1018
                raise BzrError("destination %r already exists" % dest_path)
1019
            if f_id in to_idpath:
1020
                raise BzrError("can't move %r to a subdirectory of itself" % f)
1021
1022
        # OK, so there's a race here, it's possible that someone will
1023
        # create a file in this interval and then the rename might be
1024
        # left half-done.  But we should have caught most problems.
1025
        orig_inv = deepcopy(self.inventory)
1026
        try:
1027
            for f in from_paths:
1028
                name_tail = splitpath(f)[-1]
1732.1.1 by John Arbash Meinel
deprecating appendpath, it does exactly what pathjoin does
1029
                dest_path = pathjoin(to_name, name_tail)
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1030
                result.append((f, dest_path))
1031
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1032
                try:
1033
                    rename(self.abspath(f), self.abspath(dest_path))
1034
                except OSError, e:
1035
                    raise BzrError("failed to rename %r to %r: %s" %
1036
                                   (f, dest_path, e[1]),
1037
                            ["rename rolled back"])
1038
        except:
1039
            # restore the inventory on error
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
1040
            self._set_inventory(orig_inv)
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
1041
            raise
1042
        self._write_inventory(inv)
1043
        return result
1044
1045
    @needs_write_lock
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
1046
    def rename_one(self, from_rel, to_rel):
1047
        """Rename one file.
1048
1049
        This can change the directory or the filename or both.
1050
        """
1051
        inv = self.inventory
1052
        if not self.has_filename(from_rel):
1053
            raise BzrError("can't rename: old working file %r does not exist" % from_rel)
1054
        if self.has_filename(to_rel):
1055
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
1056
1057
        file_id = inv.path2id(from_rel)
1058
        if file_id == None:
1059
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1060
1061
        entry = inv[file_id]
1062
        from_parent = entry.parent_id
1063
        from_name = entry.name
1064
        
1065
        if inv.path2id(to_rel):
1066
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
1067
1068
        to_dir, to_tail = os.path.split(to_rel)
1069
        to_dir_id = inv.path2id(to_dir)
1070
        if to_dir_id == None and to_dir != '':
1071
            raise BzrError("can't determine destination directory id for %r" % to_dir)
1072
1073
        mutter("rename_one:")
1074
        mutter("  file_id    {%s}" % file_id)
1075
        mutter("  from_rel   %r" % from_rel)
1076
        mutter("  to_rel     %r" % to_rel)
1077
        mutter("  to_dir     %r" % to_dir)
1078
        mutter("  to_dir_id  {%s}" % to_dir_id)
1079
1080
        inv.rename(file_id, to_dir_id, to_tail)
1081
1082
        from_abs = self.abspath(from_rel)
1083
        to_abs = self.abspath(to_rel)
1084
        try:
1085
            rename(from_abs, to_abs)
1086
        except OSError, e:
1087
            inv.rename(file_id, from_parent, from_name)
1088
            raise BzrError("failed to rename %r to %r: %s"
1089
                    % (from_abs, to_abs, e[1]),
1090
                    ["rename rolled back"])
1091
        self._write_inventory(inv)
1092
1093
    @needs_read_lock
453 by Martin Pool
- Split WorkingTree into its own file
1094
    def unknowns(self):
1508.1.6 by Robert Collins
Move Branch.unknowns() to WorkingTree.
1095
        """Return all unknown files.
1096
1097
        These are files in the working directory that are not versioned or
1098
        control files or ignored.
1099
        """
453 by Martin Pool
- Split WorkingTree into its own file
1100
        for subp in self.extras():
1101
            if not self.is_ignored(subp):
1102
                yield subp
1988.2.1 by Robert Collins
WorkingTree has a new api ``unversion`` which allow the unversioning of
1103
    
1104
    @needs_write_lock
1105
    def unversion(self, file_ids):
1106
        """Remove the file ids in file_ids from the current versioned set.
1107
1108
        When a file_id is unversioned, all of its children are automatically
1109
        unversioned.
1110
1111
        :param file_ids: The file ids to stop versioning.
1112
        :raises: NoSuchId if any fileid is not currently versioned.
1113
        """
1114
        for file_id in file_ids:
1115
            if self._inventory.has_id(file_id):
1988.2.6 by Robert Collins
Review feedback.
1116
                self._inventory.remove_recursive_id(file_id)
1988.2.1 by Robert Collins
WorkingTree has a new api ``unversion`` which allow the unversioning of
1117
            else:
1118
                raise errors.NoSuchId(self, file_id)
1119
        if len(file_ids):
1120
            # in the future this should just set a dirty bit to wait for the 
1121
            # final unlock. However, until all methods of workingtree start
1122
            # with the current in -memory inventory rather than triggering 
1123
            # a read, it is more complex - we need to teach read_inventory
1124
            # to know when to read, and when to not read first... and possibly
1125
            # to save first when the in memory one may be corrupted.
1126
            # so for now, we just only write it if it is indeed dirty.
1127
            # - RBC 20060907
1128
            self._write_inventory(self._inventory)
1129
    
1534.10.16 by Aaron Bentley
Small tweaks
1130
    @deprecated_method(zero_eight)
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
1131
    def iter_conflicts(self):
1534.10.16 by Aaron Bentley
Small tweaks
1132
        """List all files in the tree that have text or content conflicts.
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1133
        DEPRECATED.  Use conflicts instead."""
1534.10.10 by Aaron Bentley
Resolve uses the new stuff.
1134
        return self._iter_conflicts()
1135
1534.10.9 by Aaron Bentley
Switched display functions to conflict_lines
1136
    def _iter_conflicts(self):
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
1137
        conflicted = set()
1732.1.11 by John Arbash Meinel
Trying multiple things to get WorkingTree.list_files time down
1138
        for info in self.list_files():
1139
            path = info[0]
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
1140
            stem = get_conflicted_stem(path)
1141
            if stem is None:
1142
                continue
1143
            if stem not in conflicted:
1144
                conflicted.add(stem)
1145
                yield stem
453 by Martin Pool
- Split WorkingTree into its own file
1146
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
1147
    @needs_write_lock
1185.76.1 by Erik Bågfors
Support for --revision in pull
1148
    def pull(self, source, overwrite=False, stop_revision=None):
1551.2.36 by Aaron Bentley
Make pull update the progress bar more nicely
1149
        top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
1150
        source.lock_read()
1151
        try:
1551.2.36 by Aaron Bentley
Make pull update the progress bar more nicely
1152
            pp = ProgressPhase("Pull phase", 2, top_pb)
1153
            pp.next_phase()
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
1154
            old_revision_history = self.branch.revision_history()
1563.1.4 by Robert Collins
Fix 'bzr pull' on metadir trees.
1155
            basis_tree = self.basis_tree()
1534.4.54 by Robert Collins
Merge from integration.
1156
            count = self.branch.pull(source, overwrite, stop_revision)
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
1157
            new_revision_history = self.branch.revision_history()
1158
            if new_revision_history != old_revision_history:
1551.2.36 by Aaron Bentley
Make pull update the progress bar more nicely
1159
                pp.next_phase()
1465 by Robert Collins
Bugfix the new pull --clobber to not generate spurious conflicts.
1160
                if len(old_revision_history):
1161
                    other_revision = old_revision_history[-1]
1162
                else:
1163
                    other_revision = None
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1164
                repository = self.branch.repository
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
1165
                pb = bzrlib.ui.ui_factory.nested_progress_bar()
1166
                try:
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
1167
                    new_basis_tree = self.branch.basis_tree()
1907.1.1 by Aaron Bentley
Unshelved all changes except those related to removing RootEntry
1168
                    merge_inner(self.branch,
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
1169
                                new_basis_tree,
1170
                                basis_tree,
1171
                                this_tree=self,
1907.1.1 by Aaron Bentley
Unshelved all changes except those related to removing RootEntry
1172
                                pb=pb)
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
1173
                finally:
1174
                    pb.finished()
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
1175
                # 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.
1176
                # reuse the revisiontree we merged against to set the new
1177
                # tree data.
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
1178
                parent_trees = [(self.branch.last_revision(), new_basis_tree)]
1908.6.3 by Robert Collins
Tidy up the last_revision_id and add_pending_merge conversion to use cleaner apis.
1179
                # we have to pull the merge trees out again, because 
1180
                # merge_inner has set the ids. - this corner is not yet 
1181
                # layered well enough to prevent double handling.
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
1182
                merges = self.get_parent_ids()[1:]
1183
                parent_trees.extend([
1184
                    (parent, repository.revision_tree(parent)) for
1185
                     parent in merges])
1186
                self.set_parent_trees(parent_trees)
1185.33.44 by Martin Pool
[patch] show number of revisions pushed/pulled/merged (Robey Pointer)
1187
            return count
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
1188
        finally:
1189
            source.unlock()
1551.2.36 by Aaron Bentley
Make pull update the progress bar more nicely
1190
            top_pb.finished()
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
1191
453 by Martin Pool
- Split WorkingTree into its own file
1192
    def extras(self):
1193
        """Yield all unknown files in this WorkingTree.
1194
1195
        If there are any unknown directories then only the directory is
1196
        returned, not all its children.  But if there are unknown files
1197
        under a versioned subdirectory, they are returned.
1198
1199
        Currently returned depth-first, sorted by name within directories.
1200
        """
1201
        ## TODO: Work from given directory downwards
1202
        for path, dir_entry in self.inventory.directories():
1711.2.101 by John Arbash Meinel
Clean up some unnecessary mutter() calls
1203
            # mutter("search for unknowns in %r", path)
453 by Martin Pool
- Split WorkingTree into its own file
1204
            dirabs = self.abspath(path)
1205
            if not isdir(dirabs):
1206
                # e.g. directory deleted
1207
                continue
1208
1209
            fl = []
1210
            for subf in os.listdir(dirabs):
1830.3.3 by John Arbash Meinel
inside workingtree check for normalized filename access
1211
                if subf == '.bzr':
1212
                    continue
1213
                if subf not in dir_entry.children:
1214
                    subf_norm, can_access = osutils.normalized_filename(subf)
1215
                    if subf_norm != subf and can_access:
1216
                        if subf_norm not in dir_entry.children:
1217
                            fl.append(subf_norm)
1218
                    else:
1219
                        fl.append(subf)
453 by Martin Pool
- Split WorkingTree into its own file
1220
            
1221
            fl.sort()
1222
            for subf in fl:
1732.1.1 by John Arbash Meinel
deprecating appendpath, it does exactly what pathjoin does
1223
                subp = pathjoin(path, subf)
453 by Martin Pool
- Split WorkingTree into its own file
1224
                yield subp
1225
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
1226
    def _translate_ignore_rule(self, rule):
1227
        """Translate a single ignore rule to a regex.
1228
1713.2.7 by Robert Collins
Better description of ignore rule types from Martin.
1229
        There are two types of ignore rules.  Those that do not contain a / are
1230
        matched against the tail of the filename (that is, they do not care
1231
        what directory the file is in.)  Rules which do contain a slash must
1232
        match the entire path.  As a special case, './' at the start of the
1233
        string counts as a slash in the string but is removed before matching
1234
        (e.g. ./foo.c, ./src/foo.c)
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
1235
1236
        :return: The translated regex.
1237
        """
1238
        if rule[:2] in ('./', '.\\'):
1239
            # rootdir rule
1240
            result = fnmatch.translate(rule[2:])
1241
        elif '/' in rule or '\\' in rule:
1242
            # path prefix 
1243
            result = fnmatch.translate(rule)
1244
        else:
1245
            # default rule style.
1246
            result = "(?:.*/)?(?!.*/)" + fnmatch.translate(rule)
1247
        assert result[-1] == '$', "fnmatch.translate did not add the expected $"
1248
        return "(" + result + ")"
1249
1250
    def _combine_ignore_rules(self, rules):
1251
        """Combine a list of ignore rules into a single regex object.
1252
1253
        Each individual rule is combined with | to form a big regex, which then
1254
        has $ added to it to form something like ()|()|()$. The group index for
1255
        each subregex's outermost group is placed in a dictionary mapping back 
1256
        to the rule. This allows quick identification of the matching rule that
1257
        triggered a match.
1713.2.5 by Robert Collins
Support more than 100 ignore rules.
1258
        :return: a list of the compiled regex and the matching-group index 
1259
        dictionaries. We return a list because python complains if you try to 
1260
        combine more than 100 regexes.
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
1261
        """
1713.2.5 by Robert Collins
Support more than 100 ignore rules.
1262
        result = []
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
1263
        groups = {}
1264
        next_group = 0
1265
        translated_rules = []
1266
        for rule in rules:
1267
            translated_rule = self._translate_ignore_rule(rule)
1268
            compiled_rule = re.compile(translated_rule)
1269
            groups[next_group] = rule
1270
            next_group += compiled_rule.groups
1271
            translated_rules.append(translated_rule)
1713.2.5 by Robert Collins
Support more than 100 ignore rules.
1272
            if next_group == 99:
1273
                result.append((re.compile("|".join(translated_rules)), groups))
1274
                groups = {}
1275
                next_group = 0
1276
                translated_rules = []
1277
        if len(translated_rules):
1278
            result.append((re.compile("|".join(translated_rules)), groups))
1279
        return result
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
1280
453 by Martin Pool
- Split WorkingTree into its own file
1281
    def ignored_files(self):
1282
        """Yield list of PATH, IGNORE_PATTERN"""
1283
        for subp in self.extras():
1284
            pat = self.is_ignored(subp)
1285
            if pat != None:
1286
                yield subp, pat
1287
1288
    def get_ignore_list(self):
1289
        """Return list of ignore patterns.
1290
1291
        Cached in the Tree object after the first call.
1292
        """
1836.1.30 by John Arbash Meinel
Change ignore functions to use sets instead of lists.
1293
        ignoreset = getattr(self, '_ignoreset', None)
1294
        if ignoreset is not None:
1295
            return ignoreset
1296
1297
        ignore_globs = set(bzrlib.DEFAULT_IGNORE)
1298
        ignore_globs.update(ignores.get_runtime_ignores())
1299
1300
        ignore_globs.update(ignores.get_user_ignores())
1836.1.4 by John Arbash Meinel
Cleanup is_ignored to handle comment lines, and a global ignore pattern
1301
453 by Martin Pool
- Split WorkingTree into its own file
1302
        if self.has_filename(bzrlib.IGNORE_FILENAME):
1303
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
1836.1.4 by John Arbash Meinel
Cleanup is_ignored to handle comment lines, and a global ignore pattern
1304
            try:
1836.1.30 by John Arbash Meinel
Change ignore functions to use sets instead of lists.
1305
                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
1306
            finally:
1307
                f.close()
1308
1836.1.30 by John Arbash Meinel
Change ignore functions to use sets instead of lists.
1309
        self._ignoreset = ignore_globs
1836.1.4 by John Arbash Meinel
Cleanup is_ignored to handle comment lines, and a global ignore pattern
1310
        self._ignore_regex = self._combine_ignore_rules(ignore_globs)
1311
        return ignore_globs
453 by Martin Pool
- Split WorkingTree into its own file
1312
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
1313
    def _get_ignore_rules_as_regex(self):
1314
        """Return a regex of the ignore rules and a mapping dict.
1315
1316
        :return: (ignore rules compiled regex, dictionary mapping rule group 
1317
        indices to original rule.)
1318
        """
1836.1.30 by John Arbash Meinel
Change ignore functions to use sets instead of lists.
1319
        if getattr(self, '_ignoreset', None) is None:
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
1320
            self.get_ignore_list()
1321
        return self._ignore_regex
1322
453 by Martin Pool
- Split WorkingTree into its own file
1323
    def is_ignored(self, filename):
1324
        r"""Check whether the filename matches an ignore pattern.
1325
1326
        Patterns containing '/' or '\' need to match the whole path;
1327
        others match against only the last component.
1328
1329
        If the file is ignored, returns the pattern which caused it to
1330
        be ignored, otherwise None.  So this can simply be used as a
1331
        boolean if desired."""
1332
1333
        # TODO: Use '**' to match directories, and other extended
1334
        # globbing stuff from cvs/rsync.
1335
1336
        # XXX: fnmatch is actually not quite what we want: it's only
1337
        # approximately the same as real Unix fnmatch, and doesn't
1338
        # treat dotfiles correctly and allows * to match /.
1339
        # Eventually it should be replaced with something more
1340
        # accurate.
1713.2.5 by Robert Collins
Support more than 100 ignore rules.
1341
    
1342
        rules = self._get_ignore_rules_as_regex()
1343
        for regex, mapping in rules:
1344
            match = regex.match(filename)
1345
            if match is not None:
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.
1346
                # one or more of the groups in mapping will have a non-None
1347
                # group match.
1713.2.5 by Robert Collins
Support more than 100 ignore rules.
1348
                groups = match.groups()
1349
                rules = [mapping[group] for group in 
1350
                    mapping if groups[group] is not None]
1351
                return rules[0]
1707.2.5 by Robert Collins
slightly improve add
1352
        return None
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
1353
1185.12.28 by Aaron Bentley
Removed use of readonly path for executability test
1354
    def kind(self, file_id):
1355
        return file_kind(self.id2abspath(file_id))
1356
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1357
    def last_revision(self):
1358
        """Return the last revision id of this working tree.
1359
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
1360
        In early branch formats this was the same as the branch last_revision,
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1361
        but that cannot be relied upon - for working tree operations,
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
1362
        always use tree.last_revision(). This returns the left most parent id,
1363
        or None if there are no parents.
1364
1908.7.9 by Robert Collins
WorkingTree.last_revision and WorkingTree.pending_merges are deprecated.
1365
        This was deprecated as of 0.11. Please use get_parent_ids instead.
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1366
        """
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
1367
        return self._last_revision()
1368
1369
    @needs_read_lock
1370
    def _last_revision(self):
1371
        """helper for get_parent_ids."""
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1372
        return self.branch.last_revision()
1373
1694.2.6 by Martin Pool
[merge] bzr.dev
1374
    def is_locked(self):
1375
        return self._control_files.is_locked()
1376
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1377
    def lock_read(self):
1378
        """See Branch.lock_read, and WorkingTree.unlock."""
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.
1379
        self.branch.lock_read()
1380
        try:
1381
            return self._control_files.lock_read()
1382
        except:
1383
            self.branch.unlock()
1384
            raise
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1385
1386
    def lock_write(self):
1387
        """See Branch.lock_write, and WorkingTree.unlock."""
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.
1388
        self.branch.lock_write()
1389
        try:
1390
            return self._control_files.lock_write()
1391
        except:
1392
            self.branch.unlock()
1393
            raise
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1394
1694.2.6 by Martin Pool
[merge] bzr.dev
1395
    def get_physical_lock_status(self):
1396
        return self._control_files.get_physical_lock_status()
1397
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1398
    def _basis_inventory_name(self):
1399
        return 'basis-inventory'
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1400
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1401
    @needs_write_lock
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1402
    def set_last_revision(self, new_revision):
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1403
        """Change the last revision in the working tree."""
1404
        if self._change_last_revision(new_revision):
1405
            self._cache_basis_inventory(new_revision)
1406
1407
    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.
1408
        """Template method part of set_last_revision to perform the change.
1409
        
1410
        This is used to allow WorkingTree3 instances to not affect branch
1411
        when their last revision is set.
1412
        """
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1413
        if new_revision is None:
1414
            self.branch.set_revision_history([])
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1415
            return False
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1416
        try:
1908.1.1 by Robert Collins
Relax WorkingTree.set_last-revision to allow any revision to be set.
1417
            self.branch.generate_revision_history(new_revision)
1418
        except errors.NoSuchRevision:
1419
            # not present in the repo - dont try to set it deeper than the tip
1420
            self.branch.set_revision_history([new_revision])
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1421
        return True
1422
1423
    def _cache_basis_inventory(self, new_revision):
1424
        """Cache new_revision as the basis inventory."""
1740.2.3 by Aaron Bentley
Only reserialize the working tree basis inventory when needed.
1425
        # TODO: this should allow the ready-to-use inventory to be passed in,
1426
        # as commit already has that ready-to-use [while the format is the
1427
        # same, that is].
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1428
        try:
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1429
            # this double handles the inventory - unpack and repack - 
1430
            # but is easier to understand. We can/should put a conditional
1431
            # in here based on whether the inventory is in the latest format
1432
            # - perhaps we should repack all inventories on a repository
1433
            # upgrade ?
1740.2.3 by Aaron Bentley
Only reserialize the working tree basis inventory when needed.
1434
            # the fast path is to copy the raw xml from the repository. If the
1435
            # xml contains 'revision_id="', then we assume the right 
1436
            # revision_id is set. We must check for this full string, because a
1437
            # root node id can legitimately look like 'revision_id' but cannot
1438
            # contain a '"'.
1439
            xml = self.branch.repository.get_inventory_xml(new_revision)
1440
            if not 'revision_id="' in xml.split('\n', 1)[0]:
1441
                inv = self.branch.repository.deserialise_inventory(
1442
                    new_revision, xml)
1443
                inv.revision_id = new_revision
1444
                xml = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
1757.1.3 by Robert Collins
Dont treat the basis inventory xml as ascii - its utf8 and should be preserved as such.
1445
            assert isinstance(xml, str), 'serialised xml must be bytestring.'
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1446
            path = self._basis_inventory_name()
1757.1.3 by Robert Collins
Dont treat the basis inventory xml as ascii - its utf8 and should be preserved as such.
1447
            sio = StringIO(xml)
1448
            self._control_files.put(path, sio)
1908.1.1 by Robert Collins
Relax WorkingTree.set_last-revision to allow any revision to be set.
1449
        except (errors.NoSuchRevision, errors.RevisionNotPresent):
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1450
            pass
1451
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1452
    def read_basis_inventory(self):
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1453
        """Read the cached basis inventory."""
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1454
        path = self._basis_inventory_name()
1757.1.3 by Robert Collins
Dont treat the basis inventory xml as ascii - its utf8 and should be preserved as such.
1455
        return self._control_files.get(path).read()
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1456
        
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1457
    @needs_read_lock
1458
    def read_working_inventory(self):
1459
        """Read the working inventory."""
1460
        # ElementTree does its own conversion from UTF-8, so open in
1461
        # binary.
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1462
        result = bzrlib.xml5.serializer_v5.read_inventory(
1534.4.28 by Robert Collins
first cut at merge from integration.
1463
            self._control_files.get('inventory'))
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1464
        self._set_inventory(result)
1465
        return result
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1466
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1467
    @needs_write_lock
1685.1.77 by Wouter van Heyst
WorkingTree.remove takes an optional output file
1468
    def remove(self, files, verbose=False, to_file=None):
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1469
        """Remove nominated files from the working inventory..
1470
1471
        This does not remove their text.  This does not run on XXX on what? RBC
1472
1473
        TODO: Refuse to remove modified files unless --force is given?
1474
1475
        TODO: Do something useful with directories.
1476
1477
        TODO: Should this remove the text or not?  Tough call; not
1478
        removing may be useful and the user can just use use rm, and
1479
        is the opposite of add.  Removing it is consistent with most
1480
        other tools.  Maybe an option.
1481
        """
1482
        ## TODO: Normalize names
1483
        ## TODO: Remove nested loops; better scalability
1484
        if isinstance(files, basestring):
1485
            files = [files]
1486
1487
        inv = self.inventory
1488
1489
        # do this before any modifications
1490
        for f in files:
1491
            fid = inv.path2id(f)
1492
            if not fid:
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
1493
                # TODO: Perhaps make this just a warning, and continue?
1494
                # This tends to happen when 
1495
                raise NotVersionedError(path=f)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1496
            if verbose:
1497
                # having remove it, it must be either ignored or unknown
1498
                if self.is_ignored(f):
1499
                    new_status = 'I'
1500
                else:
1501
                    new_status = '?'
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1502
                show_status(new_status, inv[fid].kind, f, to_file=to_file)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1503
            del inv[fid]
1504
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1505
        self._write_inventory(inv)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1506
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1507
    @needs_write_lock
1534.9.4 by Aaron Bentley
Added progress bars to revert.
1508
    def revert(self, filenames, old_tree=None, backups=True, 
1509
               pb=DummyProgress()):
1534.7.47 by Aaron Bentley
Started work on 'revert'
1510
        from transform import revert
1534.10.14 by Aaron Bentley
Made revert clear conflicts
1511
        from conflicts import resolve
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1512
        if old_tree is None:
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1513
            old_tree = self.basis_tree()
1558.7.13 by Aaron Bentley
WorkingTree.revert returns conflicts
1514
        conflicts = revert(self, old_tree, filenames, backups, pb)
1457.1.8 by Robert Collins
Replace the WorkingTree.revert method algorithm with a call to merge_inner.
1515
        if not len(filenames):
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
1516
            self.set_parent_ids(self.get_parent_ids()[:1])
1534.10.14 by Aaron Bentley
Made revert clear conflicts
1517
            resolve(self)
1518
        else:
1534.10.15 by Aaron Bentley
Revert does resolve
1519
            resolve(self, filenames, ignore_misses=True)
1558.7.13 by Aaron Bentley
WorkingTree.revert returns conflicts
1520
        return conflicts
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1521
1908.11.2 by Robert Collins
Implement WorkingTree interface conformance tests for
1522
    def revision_tree(self, revision_id):
1523
        """See Tree.revision_tree.
1524
1525
        WorkingTree can supply revision_trees for the basis revision only
1526
        because there is only one cached inventory in the bzr directory.
1527
        """
1528
        if revision_id == self.last_revision():
1529
            try:
1530
                xml = self.read_basis_inventory()
1531
            except NoSuchFile:
1532
                pass
1533
            else:
1534
                inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
1535
                # Fixup old inventory serialization that has a missing root
1536
                # revision_id attribute.
1537
                inv.root.revision = revision_id
1538
                # dont use the repository revision_tree api because we want
1539
                # to supply the inventory.
1540
                if inv.revision_id == revision_id:
1541
                    return bzrlib.tree.RevisionTree(self.branch.repository,
1542
                        inv, revision_id)
1543
        # raise if there was no inventory, or if we read the wrong inventory.
1544
        raise errors.NoSuchRevisionInTree(self, revision_id)
1545
1658.1.3 by Martin Pool
Doc
1546
    # XXX: This method should be deprecated in favour of taking in a proper
1547
    # new Inventory object.
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1548
    @needs_write_lock
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1549
    def set_inventory(self, new_inventory_list):
1550
        from bzrlib.inventory import (Inventory,
1551
                                      InventoryDirectory,
1552
                                      InventoryEntry,
1553
                                      InventoryFile,
1554
                                      InventoryLink)
1555
        inv = Inventory(self.get_root_id())
1658.1.2 by Martin Pool
Revert changes to WorkingTree.set_inventory to unbreak bzrtools
1556
        for path, file_id, parent, kind in new_inventory_list:
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1557
            name = os.path.basename(path)
1558
            if name == "":
1559
                continue
1560
            # fixme, there should be a factory function inv,add_?? 
1561
            if kind == 'directory':
1562
                inv.add(InventoryDirectory(file_id, name, parent))
1563
            elif kind == 'file':
1658.1.2 by Martin Pool
Revert changes to WorkingTree.set_inventory to unbreak bzrtools
1564
                inv.add(InventoryFile(file_id, name, parent))
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1565
            elif kind == 'symlink':
1566
                inv.add(InventoryLink(file_id, name, parent))
1567
            else:
1568
                raise BzrError("unknown kind %r" % kind)
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1569
        self._write_inventory(inv)
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1570
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1571
    @needs_write_lock
1572
    def set_root_id(self, file_id):
1573
        """Set the root id for this tree."""
1574
        inv = self.read_working_inventory()
1575
        orig_root_id = inv.root.file_id
1576
        del inv._byid[inv.root.file_id]
1577
        inv.root.file_id = file_id
1578
        inv._byid[inv.root.file_id] = inv.root
1579
        for fid in inv:
1580
            entry = inv[fid]
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1581
            if entry.parent_id == orig_root_id:
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1582
                entry.parent_id = inv.root.file_id
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1583
        self._write_inventory(inv)
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1584
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1585
    def unlock(self):
1586
        """See Branch.unlock.
1587
        
1588
        WorkingTree locking just uses the Branch locking facilities.
1589
        This is current because all working trees have an embedded branch
1590
        within them. IF in the future, we were to make branch data shareable
1591
        between multiple working trees, i.e. via shared storage, then we 
1592
        would probably want to lock both the local tree, and the branch.
1593
        """
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.
1594
        raise NotImplementedError(self.unlock)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1595
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1596
    @needs_write_lock
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1597
    def update(self):
1587.1.11 by Robert Collins
Local commits appear to be working properly.
1598
        """Update a working tree along its branch.
1599
1907.1.1 by Aaron Bentley
Unshelved all changes except those related to removing RootEntry
1600
        This will update the branch if its bound too, which means we have multiple trees involved:
1601
        The new basis tree of the master.
1602
        The old basis tree of the branch.
1603
        The old basis tree of the working tree.
1604
        The current working tree state.
1605
        pathologically all three may be different, and non ancestors of each other.
1606
        Conceptually we want to:
1607
        Preserve the wt.basis->wt.state changes
1608
        Transform the wt.basis to the new master basis.
1609
        Apply a merge of the old branch basis to get any 'local' changes from it into the tree.
1610
        Restore the wt.basis->wt.state changes.
1587.1.11 by Robert Collins
Local commits appear to be working properly.
1611
1612
        There isn't a single operation at the moment to do that, so we:
1907.1.1 by Aaron Bentley
Unshelved all changes except those related to removing RootEntry
1613
        Merge current state -> basis tree of the master w.r.t. the old tree basis.
1614
        Do a 'normal' merge of the old branch basis if it is relevant.
1587.1.11 by Robert Collins
Local commits appear to be working properly.
1615
        """
1587.1.10 by Robert Collins
update updates working tree and branch together.
1616
        old_tip = self.branch.update()
1927.2.3 by Robert Collins
review comment application - paired with Martin.
1617
        # here if old_tip is not None, it is the old tip of the branch before
1618
        # it was updated from the master branch. This should become a pending
1619
        # merge in the working tree to preserve the user existing work.  we
1620
        # cant set that until we update the working trees last revision to be
1621
        # one from the new branch, because it will just get absorbed by the
1622
        # parent de-duplication logic.
1623
        # 
1624
        # We MUST save it even if an error occurs, because otherwise the users
1625
        # local work is unreferenced and will appear to have been lost.
1626
        # 
1627
        result = 0
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
1628
        try:
1629
            last_rev = self.get_parent_ids()[0]
1630
        except IndexError:
1631
            last_rev = None
1632
        if last_rev != self.branch.last_revision():
1927.2.3 by Robert Collins
review comment application - paired with Martin.
1633
            # merge tree state up to new branch tip.
1634
            basis = self.basis_tree()
1635
            to_tree = self.branch.basis_tree()
1636
            result += merge_inner(self.branch,
1637
                                  to_tree,
1638
                                  basis,
1639
                                  this_tree=self)
1908.6.6 by Robert Collins
Merge updated set_parents api.
1640
            # TODO - dedup parents list with things merged by pull ?
1641
            # reuse the tree we've updated to to set the basis:
1642
            parent_trees = [(self.branch.last_revision(), to_tree)]
1643
            merges = self.get_parent_ids()[1:]
1644
            # Ideally we ask the tree for the trees here, that way the working
1645
            # tree can decide whether to give us teh entire tree or give us a
1646
            # lazy initialised tree. dirstate for instance will have the trees
1647
            # in ram already, whereas a last-revision + basis-inventory tree
1648
            # will not, but also does not need them when setting parents.
1649
            for parent in merges:
1650
                parent_trees.append(
1651
                    (parent, self.branch.repository.revision_tree(parent)))
1652
            if old_tip is not None:
1653
                parent_trees.append(
1654
                    (old_tip, self.branch.repository.revision_tree(old_tip)))
1655
            self.set_parent_trees(parent_trees)
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
1656
            last_rev = parent_trees[0][0]
1927.2.3 by Robert Collins
review comment application - paired with Martin.
1657
        else:
1658
            # the working tree had the same last-revision as the master
1659
            # branch did. We may still have pivot local work from the local
1660
            # branch into old_tip:
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.
1661
            if old_tip is not None:
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
1662
                self.add_parent_tree_id(old_tip)
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
1663
        if old_tip and old_tip != last_rev:
1927.2.3 by Robert Collins
review comment application - paired with Martin.
1664
            # our last revision was not the prior branch last revision
1665
            # and we have converted that last revision to a pending merge.
1666
            # base is somewhere between the branch tip now
1667
            # and the now pending merge
1668
            from bzrlib.revision import common_ancestor
1669
            try:
1670
                base_rev_id = common_ancestor(self.branch.last_revision(),
1671
                                              old_tip,
1672
                                              self.branch.repository)
1673
            except errors.NoCommonAncestor:
1674
                base_rev_id = None
1675
            base_tree = self.branch.repository.revision_tree(base_rev_id)
1676
            other_tree = self.branch.repository.revision_tree(old_tip)
1677
            result += merge_inner(self.branch,
1678
                                  other_tree,
1679
                                  base_tree,
1680
                                  this_tree=self)
1681
        return result
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1682
1683
    @needs_write_lock
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1684
    def _write_inventory(self, inv):
1685
        """Write inventory as the current inventory."""
1686
        sio = StringIO()
1687
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
1688
        sio.seek(0)
1534.4.28 by Robert Collins
first cut at merge from integration.
1689
        self._control_files.put('inventory', sio)
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
1690
        self._set_inventory(inv)
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1691
        mutter('wrote working inventory')
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1692
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1693
    def set_conflicts(self, arg):
1694
        raise UnsupportedOperation(self.set_conflicts, self)
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
1695
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
1696
    def add_conflicts(self, arg):
1697
        raise UnsupportedOperation(self.add_conflicts, self)
1698
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
1699
    @needs_read_lock
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1700
    def conflicts(self):
1701
        conflicts = ConflictList()
1534.10.9 by Aaron Bentley
Switched display functions to conflict_lines
1702
        for conflicted in self._iter_conflicts():
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
1703
            text = True
1704
            try:
1705
                if file_kind(self.abspath(conflicted)) != "file":
1706
                    text = False
1757.2.4 by Robert Collins
Teach file_kind about NoSuchFile, reducing duplicate code, and add user files before entering the main loop in smart_add.
1707
            except errors.NoSuchFile:
1708
                text = False
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
1709
            if text is True:
1710
                for suffix in ('.THIS', '.OTHER'):
1711
                    try:
1712
                        kind = file_kind(self.abspath(conflicted+suffix))
1757.2.4 by Robert Collins
Teach file_kind about NoSuchFile, reducing duplicate code, and add user files before entering the main loop in smart_add.
1713
                        if kind != "file":
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
1714
                            text = False
1757.2.4 by Robert Collins
Teach file_kind about NoSuchFile, reducing duplicate code, and add user files before entering the main loop in smart_add.
1715
                    except errors.NoSuchFile:
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
1716
                        text = False
1757.2.4 by Robert Collins
Teach file_kind about NoSuchFile, reducing duplicate code, and add user files before entering the main loop in smart_add.
1717
                    if text == False:
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
1718
                        break
1719
            ctype = {True: 'text conflict', False: 'contents conflict'}[text]
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1720
            conflicts.append(Conflict.factory(ctype, path=conflicted,
1721
                             file_id=self.path2id(conflicted)))
1722
        return conflicts
1723
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
1724
    def walkdirs(self, prefix=""):
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1725
        disk_top = self.abspath(prefix)
1726
        if disk_top.endswith('/'):
1727
            disk_top = disk_top[:-1]
1728
        top_strip_len = len(disk_top) + 1
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1729
        inventory_iterator = self._walkdirs(prefix)
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1730
        disk_iterator = osutils.walkdirs(disk_top, prefix)
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1731
        try:
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1732
            current_disk = disk_iterator.next()
1733
            disk_finished = False
1734
        except OSError, e:
1735
            if e.errno != errno.ENOENT:
1736
                raise
1737
            current_disk = None
1738
            disk_finished = True
1739
        try:
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1740
            current_inv = inventory_iterator.next()
1741
            inv_finished = False
1742
        except StopIteration:
1743
            current_inv = None
1744
            inv_finished = True
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1745
        while not inv_finished or not disk_finished:
1746
            if not disk_finished:
1747
                # strip out .bzr dirs
1748
                if current_disk[0][1][top_strip_len:] == '':
1749
                    # osutils.walkdirs can be made nicer - 
1750
                    # yield the path-from-prefix rather than the pathjoined
1751
                    # value.
1752
                    bzrdir_loc = bisect_left(current_disk[1], ('.bzr', '.bzr'))
1753
                    if current_disk[1][bzrdir_loc][0] == '.bzr':
1754
                        # we dont yield the contents of, or, .bzr itself.
1755
                        del current_disk[1][bzrdir_loc]
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1756
            if inv_finished:
1757
                # 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.
1758
                direction = 1
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1759
            elif disk_finished:
1760
                # 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.
1761
                direction = -1
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1762
            else:
1763
                direction = cmp(current_inv[0][0], current_disk[0][0])
1852.15.12 by Robert Collins
WorkingTree.walkdirs handling of changing file kinds, and multi-directory with missing and unknown ordering bugfix.
1764
            if direction > 0:
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1765
                # disk is before inventory - unknown
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1766
                dirblock = [(relpath, basename, kind, stat, None, None) for
1767
                    relpath, basename, kind, stat, top_path in current_disk[1]]
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1768
                yield (current_disk[0][0], None), dirblock
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1769
                try:
1770
                    current_disk = disk_iterator.next()
1771
                except StopIteration:
1772
                    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.
1773
            elif direction < 0:
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1774
                # inventory is before disk - missing.
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1775
                dirblock = [(relpath, basename, 'unknown', None, fileid, kind)
1776
                    for relpath, basename, dkind, stat, fileid, kind in 
1777
                    current_inv[1]]
1778
                yield (current_inv[0][0], current_inv[0][1]), dirblock
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1779
                try:
1780
                    current_inv = inventory_iterator.next()
1781
                except StopIteration:
1782
                    inv_finished = True
1783
            else:
1784
                # versioned present directory
1785
                # merge the inventory and disk data together
1786
                dirblock = []
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1787
                for relpath, subiterator in itertools.groupby(sorted(
1852.15.12 by Robert Collins
WorkingTree.walkdirs handling of changing file kinds, and multi-directory with missing and unknown ordering bugfix.
1788
                    current_inv[1] + current_disk[1], key=operator.itemgetter(0)), operator.itemgetter(1)):
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1789
                    path_elements = list(subiterator)
1790
                    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.
1791
                        inv_row, disk_row = path_elements
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1792
                        # 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.
1793
                        dirblock.append((inv_row[0],
1794
                            inv_row[1], disk_row[2],
1795
                            disk_row[3], inv_row[4],
1796
                            inv_row[5]))
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1797
                    elif len(path_elements[0]) == 5:
1798
                        # unknown disk file
1852.15.11 by Robert Collins
Tree.walkdirs handles missing contents in workingtrees.
1799
                        dirblock.append((path_elements[0][0],
1800
                            path_elements[0][1], path_elements[0][2],
1801
                            path_elements[0][3], None, None))
1802
                    elif len(path_elements[0]) == 6:
1803
                        # versioned, absent file.
1804
                        dirblock.append((path_elements[0][0],
1805
                            path_elements[0][1], 'unknown', None,
1806
                            path_elements[0][4], path_elements[0][5]))
1807
                    else:
1808
                        raise NotImplementedError('unreachable code')
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1809
                yield current_inv[0], dirblock
1810
                try:
1811
                    current_inv = inventory_iterator.next()
1812
                except StopIteration:
1813
                    inv_finished = True
1814
                try:
1815
                    current_disk = disk_iterator.next()
1816
                except StopIteration:
1817
                    disk_finished = True
1818
1819
    def _walkdirs(self, prefix=""):
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
1820
        _directory = 'directory'
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1821
        # get the root in the inventory
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
1822
        inv = self.inventory
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1823
        top_id = inv.path2id(prefix)
1824
        if top_id is None:
1825
            pending = []
1826
        else:
1827
            pending = [(prefix, '', _directory, None, top_id, None)]
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
1828
        while pending:
1829
            dirblock = []
1830
            currentdir = pending.pop()
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1831
            # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-id, 5-kind
1832
            top_id = currentdir[4]
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
1833
            if currentdir[0]:
1834
                relroot = currentdir[0] + '/'
1835
            else:
1836
                relroot = ""
1837
            # FIXME: stash the node in pending
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1838
            entry = inv[top_id]
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
1839
            for name, child in entry.sorted_children():
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1840
                dirblock.append((relroot + name, name, child.kind, None,
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
1841
                    child.file_id, child.kind
1842
                    ))
1852.15.10 by Robert Collins
Tweak the Tree.walkdirs interface more to be more useful.
1843
            yield (currentdir[0], entry.file_id), dirblock
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
1844
            # push the user specified dirs from dirblock
1845
            for dir in reversed(dirblock):
1846
                if dir[2] == _directory:
1847
                    pending.append(dir)
1848
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1849
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.
1850
class WorkingTree2(WorkingTree):
1851
    """This is the Format 2 working tree.
1852
1853
    This was the first weave based working tree. 
1854
     - uses os locks for locking.
1855
     - uses the branch last-revision.
1856
    """
1857
1858
    def unlock(self):
1859
        # we share control files:
1860
        if self._hashcache.needs_write and self._control_files._lock_count==3:
1861
            self._hashcache.write()
1862
        # reverse order of locking.
1863
        try:
1864
            return self._control_files.unlock()
1865
        finally:
1866
            self.branch.unlock()
1867
1868
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1869
class WorkingTree3(WorkingTree):
1870
    """This is the Format 3 working tree.
1871
1872
    This differs from the base WorkingTree by:
1873
     - having its own file lock
1874
     - having its own last-revision property.
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
1875
1876
    This is new in bzr 0.8
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1877
    """
1878
1879
    @needs_read_lock
1908.7.6 by Robert Collins
Deprecate WorkingTree.last_revision.
1880
    def _last_revision(self):
1881
        """See WorkingTree._last_revision."""
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1882
        try:
1883
            return self._control_files.get_utf8('last-revision').read()
1884
        except NoSuchFile:
1885
            return None
1886
1887
    def _change_last_revision(self, revision_id):
1888
        """See WorkingTree._change_last_revision."""
1889
        if revision_id is None or revision_id == NULL_REVISION:
1890
            try:
1891
                self._control_files._transport.delete('last-revision')
1892
            except errors.NoSuchFile:
1893
                pass
1894
            return False
1895
        else:
1896
            self._control_files.put_utf8('last-revision', revision_id)
1897
            return True
1898
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
1899
    @needs_write_lock
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1900
    def set_conflicts(self, conflicts):
1901
        self._put_rio('conflicts', conflicts.to_stanzas(), 
1534.10.21 by Aaron Bentley
Moved and renamed conflict functions
1902
                      CONFLICT_HEADER_1)
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
1903
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
1904
    @needs_write_lock
1905
    def add_conflicts(self, new_conflicts):
1906
        conflict_set = set(self.conflicts())
1907
        conflict_set.update(set(list(new_conflicts)))
1908
        self.set_conflicts(ConflictList(sorted(conflict_set,
1909
                                               key=Conflict.sort_key)))
1910
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
1911
    @needs_read_lock
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1912
    def conflicts(self):
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
1913
        try:
1914
            confile = self._control_files.get('conflicts')
1915
        except NoSuchFile:
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1916
            return ConflictList()
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
1917
        try:
1918
            if confile.next() != CONFLICT_HEADER_1 + '\n':
1919
                raise ConflictFormatError()
1920
        except StopIteration:
1921
            raise ConflictFormatError()
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1922
        return ConflictList.from_stanzas(RioReader(confile))
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
1923
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.
1924
    def unlock(self):
1925
        if self._hashcache.needs_write and self._control_files._lock_count==1:
1926
            self._hashcache.write()
1927
        # reverse order of locking.
1928
        try:
1929
            return self._control_files.unlock()
1930
        finally:
1931
            self.branch.unlock()
1932
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
1933
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
1934
class WorkingTree4(WorkingTree3):
1935
    """This is the Format 4 working tree.
1936
1937
    This differs from WorkingTree3 by:
1938
     - having a consolidated internal dirstate.
1939
1940
    This is new in bzr TODO FIXME SETMEBEFORE MERGE.
1941
    """
1942
1943
    def __init__(self, basedir,
1944
                 branch,
1945
                 _inventory=None,
1946
                 _control_files=None,
1947
                 _format=None,
1948
                 _bzrdir=None):
1949
        """Construct a WorkingTree for basedir.
1950
1951
        If the branch is not supplied, it is opened automatically.
1952
        If the branch is supplied, it must be the branch for this basedir.
1953
        (branch.base is not cross checked, because for remote branches that
1954
        would be meaningless).
1955
        """
1956
        self._format = _format
1957
        self.bzrdir = _bzrdir
1958
        from bzrlib.hashcache import HashCache
1959
        from bzrlib.trace import note, mutter
1960
        assert isinstance(basedir, basestring), \
1961
            "base directory %r is not a string" % basedir
1962
        basedir = safe_unicode(basedir)
1963
        mutter("opening working tree %r", basedir)
1964
        self._branch = branch
1965
        assert isinstance(self.branch, bzrlib.branch.Branch), \
1966
            "branch %r is not a Branch" % self.branch
1967
        self.basedir = realpath(basedir)
1968
        # if branch is at our basedir and is a format 6 or less
1969
        # assume all other formats have their own control files.
1970
        assert isinstance(_control_files, LockableFiles), \
1971
            "_control_files must be a LockableFiles, not %r" % _control_files
1972
        self._control_files = _control_files
1973
        # update the whole cache up front and write to disk if anything changed;
1974
        # in the future we might want to do this more selectively
1975
        # two possible ways offer themselves : in self._unlock, write the cache
1976
        # if needed, or, when the cache sees a change, append it to the hash
1977
        # cache file, and have the parser take the most recent entry for a
1978
        # given path only.
1979
        cache_filename = self.bzrdir.get_workingtree_transport(None).local_abspath('stat-cache')
1980
        hc = self._hashcache = HashCache(basedir, cache_filename, self._control_files._file_mode)
1981
        hc.read()
1982
        # is this scan needed ? it makes things kinda slow.
1983
        #hc.scan()
1984
1985
        if hc.needs_write:
1986
            mutter("write hc")
1987
            hc.write()
1988
1989
        if _inventory is None:
1990
            self._set_inventory(self.read_working_inventory())
1991
        else:
1992
            self._set_inventory(_inventory)
1993
        self._dirty = None
1994
        self._parent_revisions = None
1995
1996
    def _new_tree(self):
1997
        """Initialize the state in this tree to be a new tree."""
1998
        self._parent_revisions = [NULL_REVISION]
1999
        self._inventory = Inventory()
2000
        self._dirty = True
2001
1852.13.19 by Robert Collins
Get DirState objects roundtripping an add of a ghost tree.
2002
    @needs_read_lock
2003
    def revision_tree(self, revision_id):
2004
        """See Tree.revision_tree.
2005
2006
        WorkingTree4 supplies revision_trees for any basis tree.
2007
        """
2008
        local_path = self.bzrdir.get_workingtree_transport(None).local_abspath('dirstate')
2009
        self._dirstate = dirstate.DirState.on_file(local_path)
2010
        parent_ids = self._dirstate.get_parent_ids()
2011
        if revision_id not in parent_ids:
2012
            raise errors.NoSuchRevisionInTree(self, revision_id)
2013
2014
    @needs_write_lock
2015
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
2016
        """Set the parent ids to revision_ids.
2017
        
2018
        See also set_parent_trees. This api will try to retrieve the tree data
2019
        for each element of revision_ids from the trees repository. If you have
2020
        tree data already available, it is more efficient to use
2021
        set_parent_trees rather than set_parent_ids. set_parent_ids is however
2022
        an easier API to use.
2023
2024
        :param revision_ids: The revision_ids to set as the parent ids of this
2025
            working tree. Any of these may be ghosts.
2026
        """
2027
        trees = []
2028
        for revision_id in revision_ids:
2029
            try:
2030
                revtree = self.branch.repository.revision_tree(revision_id)
2031
            except errors.NoSuchRevision:
2032
                revtree = None
2033
            trees.append((revision_id, revtree))
2034
        self.set_parent_trees(trees,
2035
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
2036
2037
    @needs_write_lock
2038
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
2039
        """Set the parents of the working tree.
2040
2041
        :param parents_list: A list of (revision_id, tree) tuples. 
2042
            If tree is None, then that element is treated as an unreachable
2043
            parent tree - i.e. a ghost.
2044
        """
2045
        if len(parents_list) > 0:
2046
            if not allow_leftmost_as_ghost and parents_list[0][1] is None:
2047
                raise errors.GhostRevisionUnusableHere(leftmost_id)
2048
            leftmost_id = parents_list[0][0]
2049
            #self.set_last_revision(leftmost_id)
2050
        else:
2051
            self.set_last_revision(None)
2052
        merges = [revid for revid, tree in parents_list[1:]]
2053
        self._control_files.put_utf8('pending-merges', '\n'.join(merges))
2054
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
2055
    def unlock(self):
2056
        """Unlock in format 4 trees needs to write the entire dirstate."""
2057
        if self._control_files._lock_count == 1:
2058
            if self._hashcache.needs_write:
2059
                self._hashcache.write()
2060
            # eventually we should do signature checking during read locks for
2061
            # dirstate updates.
2062
            if self._control_files._lock_mode == 'w':
2063
                if self._dirty:
2064
                    self._write_dirstate()
2065
        # reverse order of locking.
2066
        try:
2067
            return self._control_files.unlock()
2068
        finally:
2069
            self.branch.unlock()
2070
2071
    def _write_dirstate(self):
2072
        """Write the full dirstate to disk."""
2073
        # in progress - not ready yet.
2074
        return
2075
        state_header = 'Bzr dirstate format 1'
2076
        checksum_line = ''
2077
        lines = [state_header, checksum_line]
2078
        lines.append("%s" % " ".join(self._parent_revisions))
2079
        kind_map = {
2080
            'root_directory':'r',
2081
            'file':'f',
2082
            'directory':'d',
2083
            'link':'l',
2084
            }
2085
        # root is not yielded by iter_entries_by_dir
2086
        entry = self._inventory.root
2087
        lines.append(kind_map[entry.kind])
2088
        lines.append('') # dir stats dont matter.
2089
        lines.append('') # and they have no sha1/link target
2090
        lines.append(entry.file_id)
2091
        lines.append('/')
2092
        lines.append('null:')
2093
        lines.append('')
2094
        lines.append('')
2095
        lines.append('')
2096
        lines.append('')
2097
        lines.append('')
2098
        lines.append('')
2099
        for path, entry in self._inventory.iter_entries_by_dir():
2100
            lines.append(kind_map[entry.kind])
2101
            lines.append(path)
2102
            # lines.append(entry.stat_blob)
2103
            # lines.append(entry.dirstate_value)
2104
2105
        self._control_files.put_utf8('dirstate', '\n'.join(lines))
2106
        
2107
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
2108
def get_conflicted_stem(path):
2109
    for suffix in CONFLICT_SUFFIXES:
2110
        if path.endswith(suffix):
2111
            return path[:-len(suffix)]
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
2112
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
2113
@deprecated_function(zero_eight)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
2114
def is_control_file(filename):
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
2115
    """See WorkingTree.is_control_filename(filename)."""
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
2116
    ## FIXME: better check
2117
    filename = normpath(filename)
2118
    while filename != '':
2119
        head, tail = os.path.split(filename)
2120
        ## mutter('check %r for control file' % ((head, tail),))
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
2121
        if tail == '.bzr':
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
2122
            return True
2123
        if filename == head:
2124
            break
2125
        filename = head
2126
    return False
2127
2128
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2129
class WorkingTreeFormat(object):
2130
    """An encapsulation of the initialization and open routines for a format.
2131
2132
    Formats provide three things:
2133
     * An initialization routine,
2134
     * a format string,
2135
     * an open routine.
2136
2137
    Formats are placed in an dict by their format string for reference 
2138
    during workingtree opening. Its not required that these be instances, they
2139
    can be classes themselves with class methods - it simply depends on 
2140
    whether state is needed for a given format or not.
2141
2142
    Once a format is deprecated, just deprecate the initialize and open
2143
    methods on the format class. Do not deprecate the object, as the 
2144
    object will be created every time regardless.
2145
    """
2146
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2147
    _default_format = None
2148
    """The default format used for new trees."""
2149
2150
    _formats = {}
2151
    """The known formats."""
2152
2153
    @classmethod
2154
    def find_format(klass, a_bzrdir):
2155
        """Return the format for the working tree object in a_bzrdir."""
2156
        try:
2157
            transport = a_bzrdir.get_workingtree_transport(None)
2158
            format_string = transport.get("format").read()
2159
            return klass._formats[format_string]
2160
        except NoSuchFile:
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
2161
            raise errors.NoWorkingTree(base=transport.base)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2162
        except KeyError:
1740.5.6 by Martin Pool
Clean up many exception classes.
2163
            raise errors.UnknownFormatError(format=format_string)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2164
2165
    @classmethod
2166
    def get_default_format(klass):
2167
        """Return the current default format."""
2168
        return klass._default_format
2169
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2170
    def get_format_string(self):
2171
        """Return the ASCII format string that identifies this format."""
2172
        raise NotImplementedError(self.get_format_string)
2173
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
2174
    def get_format_description(self):
2175
        """Return the short description for this format."""
2176
        raise NotImplementedError(self.get_format_description)
2177
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2178
    def is_supported(self):
2179
        """Is this format supported?
2180
2181
        Supported formats can be initialized and opened.
2182
        Unsupported formats may not support initialization or committing or 
2183
        some other features depending on the reason for not being supported.
2184
        """
2185
        return True
2186
2187
    @classmethod
2188
    def register_format(klass, format):
2189
        klass._formats[format.get_format_string()] = format
2190
2191
    @classmethod
2192
    def set_default_format(klass, format):
2193
        klass._default_format = format
2194
2195
    @classmethod
2196
    def unregister_format(klass, format):
2197
        assert klass._formats[format.get_format_string()] is format
2198
        del klass._formats[format.get_format_string()]
2199
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2200
2201
2202
class WorkingTreeFormat2(WorkingTreeFormat):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
2203
    """The second working tree format. 
2204
2205
    This format modified the hash cache from the format 1 hash cache.
2206
    """
2207
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
2208
    def get_format_description(self):
2209
        """See WorkingTreeFormat.get_format_description()."""
2210
        return "Working tree format 2"
2211
1692.7.9 by Martin Pool
Don't create broken standalone branches over sftp (Malone #43064)
2212
    def stub_initialize_remote(self, control_files):
2213
        """As a special workaround create critical control files for a remote working tree
2214
        
2215
        This ensures that it can later be updated and dealt with locally,
2216
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with 
2217
        no working tree.  (See bug #43064).
2218
        """
2219
        sio = StringIO()
2220
        inv = Inventory()
2221
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
2222
        sio.seek(0)
2223
        control_files.put('inventory', sio)
2224
2225
        control_files.put_utf8('pending-merges', '')
2226
        
2227
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
2228
    def initialize(self, a_bzrdir, revision_id=None):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
2229
        """See WorkingTreeFormat.initialize()."""
2230
        if not isinstance(a_bzrdir.transport, LocalTransport):
2231
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
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.
2232
        branch = a_bzrdir.open_branch()
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
2233
        if revision_id is not None:
2234
            branch.lock_write()
2235
            try:
2236
                revision_history = branch.revision_history()
2237
                try:
2238
                    position = revision_history.index(revision_id)
2239
                except ValueError:
2240
                    raise errors.NoSuchRevision(branch, revision_id)
2241
                branch.set_revision_history(revision_history[:position + 1])
2242
            finally:
2243
                branch.unlock()
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.
2244
        revision = branch.last_revision()
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
2245
        inv = Inventory()
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.
2246
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
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.
2247
                         branch,
2248
                         inv,
2249
                         _internal=True,
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
2250
                         _format=self,
2251
                         _bzrdir=a_bzrdir)
1907.1.1 by Aaron Bentley
Unshelved all changes except those related to removing RootEntry
2252
        wt._write_inventory(inv)
2253
        wt.set_root_id(inv.root.file_id)
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
2254
        basis_tree = branch.repository.revision_tree(revision)
2255
        wt.set_parent_trees([(revision, basis_tree)])
2256
        build_tree(basis_tree, wt)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2257
        return wt
2258
2259
    def __init__(self):
2260
        super(WorkingTreeFormat2, self).__init__()
2261
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
2262
2263
    def open(self, a_bzrdir, _found=False):
2264
        """Return the WorkingTree object for a_bzrdir
2265
2266
        _found is a private parameter, do not use it. It is used to indicate
2267
               if format probing has already been done.
2268
        """
2269
        if not _found:
2270
            # we are being called directly and must probe.
2271
            raise NotImplementedError
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2272
        if not isinstance(a_bzrdir.transport, LocalTransport):
2273
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
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.
2274
        return WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
2275
                           _internal=True,
2276
                           _format=self,
2277
                           _bzrdir=a_bzrdir)
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2278
2279
2280
class WorkingTreeFormat3(WorkingTreeFormat):
2281
    """The second working tree format updated to record a format marker.
2282
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
2283
    This format:
2284
        - exists within a metadir controlling .bzr
2285
        - includes an explicit version marker for the workingtree control
2286
          files, separate from the BzrDir format
2287
        - modifies the hash cache format
2288
        - is new in bzr 0.8
1852.3.1 by Robert Collins
Trivial cleanups to workingtree.py
2289
        - uses a LockDir to guard access for writes.
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2290
    """
2291
2292
    def get_format_string(self):
2293
        """See WorkingTreeFormat.get_format_string()."""
1553.5.81 by Martin Pool
Revert change to WorkingTreeFormat3 format string; too many things want it the old way
2294
        return "Bazaar-NG Working Tree format 3"
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2295
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
2296
    def get_format_description(self):
2297
        """See WorkingTreeFormat.get_format_description()."""
2298
        return "Working tree format 3"
2299
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
2300
    _lock_file_name = 'lock'
2301
    _lock_class = LockDir
2302
2303
    def _open_control_files(self, a_bzrdir):
2304
        transport = a_bzrdir.get_workingtree_transport(None)
2305
        return LockableFiles(transport, self._lock_file_name, 
2306
                             self._lock_class)
2307
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
2308
    def initialize(self, a_bzrdir, revision_id=None):
2309
        """See WorkingTreeFormat.initialize().
2310
        
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
2311
        revision_id allows creating a working tree at a different
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
2312
        revision than the branch is at.
2313
        """
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2314
        if not isinstance(a_bzrdir.transport, LocalTransport):
2315
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2316
        transport = a_bzrdir.get_workingtree_transport(self)
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
2317
        control_files = self._open_control_files(a_bzrdir)
2318
        control_files.create_lock()
1607.1.14 by Robert Collins
Reduce lock thrashing somewhat - drops bound branch tests lock count from 6554 to 4456 locks.
2319
        control_files.lock_write()
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2320
        control_files.put_utf8('format', self.get_format_string())
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.
2321
        branch = a_bzrdir.open_branch()
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
2322
        if revision_id is None:
2323
            revision_id = branch.last_revision()
1907.1.1 by Aaron Bentley
Unshelved all changes except those related to removing RootEntry
2324
        inv = Inventory() 
1685.1.9 by John Arbash Meinel
Updated LocalTransport so that it's base is now a URL rather than a local path. This helps consistency with all other functions. To do so, I added local_abspath() which returns the local path, and local_path_to/from_url
2325
        wt = WorkingTree3(a_bzrdir.root_transport.local_abspath('.'),
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.
2326
                         branch,
2327
                         inv,
2328
                         _internal=True,
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
2329
                         _format=self,
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
2330
                         _bzrdir=a_bzrdir,
2331
                         _control_files=control_files)
1607.1.14 by Robert Collins
Reduce lock thrashing somewhat - drops bound branch tests lock count from 6554 to 4456 locks.
2332
        wt.lock_write()
2333
        try:
1907.1.1 by Aaron Bentley
Unshelved all changes except those related to removing RootEntry
2334
            wt._write_inventory(inv)
2335
            wt.set_root_id(inv.root.file_id)
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
2336
            basis_tree = branch.repository.revision_tree(revision_id)
1551.8.20 by Aaron Bentley
Fix BzrDir.create_workingtree for NULL_REVISION
2337
            if revision_id == bzrlib.revision.NULL_REVISION:
2338
                wt.set_parent_trees([])
2339
            else:
2340
                wt.set_parent_trees([(revision_id, basis_tree)])
1908.6.1 by Robert Collins
Change all callers of set_last_revision to use set_parent_trees.
2341
            build_tree(basis_tree, wt)
1607.1.14 by Robert Collins
Reduce lock thrashing somewhat - drops bound branch tests lock count from 6554 to 4456 locks.
2342
        finally:
2343
            wt.unlock()
2344
            control_files.unlock()
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2345
        return wt
2346
2347
    def __init__(self):
2348
        super(WorkingTreeFormat3, self).__init__()
2349
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
2350
2351
    def open(self, a_bzrdir, _found=False):
2352
        """Return the WorkingTree object for a_bzrdir
2353
2354
        _found is a private parameter, do not use it. It is used to indicate
2355
               if format probing has already been done.
2356
        """
2357
        if not _found:
2358
            # we are being called directly and must probe.
2359
            raise NotImplementedError
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2360
        if not isinstance(a_bzrdir.transport, LocalTransport):
2361
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1852.3.1 by Robert Collins
Trivial cleanups to workingtree.py
2362
        return self._open(a_bzrdir, self._open_control_files(a_bzrdir))
2363
2364
    def _open(self, a_bzrdir, control_files):
2365
        """Open the tree itself.
2366
        
2367
        :param a_bzrdir: the dir for the tree.
2368
        :param control_files: the control files for the tree.
2369
        """
1685.1.9 by John Arbash Meinel
Updated LocalTransport so that it's base is now a URL rather than a local path. This helps consistency with all other functions. To do so, I added local_abspath() which returns the local path, and local_path_to/from_url
2370
        return WorkingTree3(a_bzrdir.root_transport.local_abspath('.'),
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
2371
                           _internal=True,
2372
                           _format=self,
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
2373
                           _bzrdir=a_bzrdir,
2374
                           _control_files=control_files)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2375
1534.5.1 by Robert Collins
Give info some reasonable output and tests.
2376
    def __str__(self):
2377
        return self.get_format_string()
2378
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2379
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
2380
class WorkingTreeFormat4(WorkingTreeFormat3):
2381
    """The first consolidated dirstate working tree format.
2382
2383
    This format:
2384
        - exists within a metadir controlling .bzr
2385
        - includes an explicit version marker for the workingtree control
2386
          files, separate from the BzrDir format
2387
        - modifies the hash cache format
2388
        - is new in bzr TODO FIXME SETBEFOREMERGE
2389
        - uses a LockDir to guard access to it.
2390
    """
2391
2392
    def get_format_string(self):
2393
        """See WorkingTreeFormat.get_format_string()."""
1852.13.21 by Robert Collins
(Robert Collins, John Meinel) Update WorkingTree Format 4 format string to be nicer to read.
2394
        return "Bazaar Working Tree format 4\n"
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
2395
2396
    def get_format_description(self):
2397
        """See WorkingTreeFormat.get_format_description()."""
2398
        return "Working tree format 4"
2399
2400
    def initialize(self, a_bzrdir, revision_id=None):
2401
        """See WorkingTreeFormat.initialize().
2402
        
2403
        revision_id allows creating a working tree at a different
2404
        revision than the branch is at.
2405
        """
2406
        if not isinstance(a_bzrdir.transport, LocalTransport):
2407
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
2408
        transport = a_bzrdir.get_workingtree_transport(self)
2409
        control_files = self._open_control_files(a_bzrdir)
2410
        control_files.create_lock()
2411
        control_files.lock_write()
2412
        control_files.put_utf8('format', self.get_format_string())
2413
        branch = a_bzrdir.open_branch()
2414
        if revision_id is None:
2415
            revision_id = branch.last_revision()
1852.13.15 by Robert Collins
Ensure Format4 working trees start with a dirstate.
2416
        inv = Inventory()
2417
        local_path = transport.local_abspath('dirstate')
2418
        dirstate.DirState.initialize(local_path)
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
2419
        wt = WorkingTree4(a_bzrdir.root_transport.local_abspath('.'),
2420
                         branch,
2421
                         inv,
2422
                         _format=self,
2423
                         _bzrdir=a_bzrdir,
2424
                         _control_files=control_files)
2425
        wt._new_tree()
2426
        wt.lock_write()
2427
        try:
2428
            wt._write_inventory(inv)
2429
            wt.set_root_id(inv.root.file_id)
2430
            wt.set_last_revision(revision_id)
2431
            wt.set_pending_merges([])
2432
            build_tree(wt.basis_tree(), wt)
2433
        finally:
2434
            control_files.unlock()
2435
            wt.unlock()
2436
        return wt
2437
2438
2439
    def _open(self, a_bzrdir, control_files):
2440
        """Open the tree itself.
2441
        
2442
        :param a_bzrdir: the dir for the tree.
2443
        :param control_files: the control files for the tree.
2444
        """
2445
        return WorkingTree4(a_bzrdir.root_transport.local_abspath('.'),
2446
                           branch=a_bzrdir.open_branch(),
2447
                           _format=self,
2448
                           _bzrdir=a_bzrdir,
2449
                           _control_files=control_files)
2450
2451
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2452
__default_format = WorkingTreeFormat3()
2453
WorkingTreeFormat.register_format(__default_format)
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
2454
WorkingTreeFormat.register_format(WorkingTreeFormat4())
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2455
WorkingTreeFormat.set_default_format(__default_format)
1852.13.2 by Robert Collins
Introduce a WorkingTree Format 4, which is the new dirstate format.
2456
# formats which have no format string are not discoverable
2457
# and not independently creatable, so are not registered.
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2458
_legacy_formats = [WorkingTreeFormat2(),
2459
                   ]
2460
2461
2462
class WorkingTreeTestProviderAdapter(object):
2463
    """A tool to generate a suite testing multiple workingtree formats at once.
2464
2465
    This is done by copying the test once for each transport and injecting
2466
    the transport_server, transport_readonly_server, and workingtree_format
2467
    classes into each copy. Each copy is also given a new id() to make it
2468
    easy to identify.
2469
    """
2470
2471
    def __init__(self, transport_server, transport_readonly_server, formats):
2472
        self._transport_server = transport_server
2473
        self._transport_readonly_server = transport_readonly_server
2474
        self._formats = formats
2475
    
1852.6.1 by Robert Collins
Start tree implementation tests.
2476
    def _clone_test(self, test, bzrdir_format, workingtree_format, variation):
2477
        """Clone test for adaption."""
2478
        new_test = deepcopy(test)
2479
        new_test.transport_server = self._transport_server
2480
        new_test.transport_readonly_server = self._transport_readonly_server
2481
        new_test.bzrdir_format = bzrdir_format
2482
        new_test.workingtree_format = workingtree_format
2483
        def make_new_test_id():
2484
            new_id = "%s(%s)" % (test.id(), variation)
2485
            return lambda: new_id
2486
        new_test.id = make_new_test_id()
2487
        return new_test
2488
    
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2489
    def adapt(self, test):
2490
        from bzrlib.tests import TestSuite
2491
        result = TestSuite()
2492
        for workingtree_format, bzrdir_format in self._formats:
1852.6.1 by Robert Collins
Start tree implementation tests.
2493
            new_test = self._clone_test(
2494
                test,
2495
                bzrdir_format,
2496
                workingtree_format, workingtree_format.__class__.__name__)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
2497
            result.addTest(new_test)
2498
        return result