/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
1836.1.22 by John Arbash Meinel
[merge] bzr.dev 1861
58
from bzrlib import bzrdir, 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,
102
        )
1852.3.1 by Robert Collins
Trivial cleanups to workingtree.py
103
from bzrlib.trace import mutter, note
1534.7.165 by Aaron Bentley
Switched to build_tree instead of revert
104
from bzrlib.transform import build_tree
1534.4.28 by Robert Collins
first cut at merge from integration.
105
from bzrlib.transport import get_transport
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
106
from bzrlib.transport.local import LocalTransport
1852.3.1 by Robert Collins
Trivial cleanups to workingtree.py
107
from bzrlib.textui import show_status
108
import bzrlib.tree
1534.9.10 by Aaron Bentley
Fixed use of ui_factory (which can't be imported directly)
109
import bzrlib.ui
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
110
import bzrlib.xml5
453 by Martin Pool
- Split WorkingTree into its own file
111
1685.1.30 by John Arbash Meinel
PEP8 for workingtree.py
112
1864.4.1 by John Arbash Meinel
Fix bug #43801 by squashing file ids a little bit more.
113
# the regex removes any weird characters; we don't escape them 
114
# but rather just pull them out
115
_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'.
116
_gen_id_suffix = None
117
_gen_id_serial = 0
118
119
120
def _next_id_suffix():
121
    """Create a new file id suffix that is reasonably unique.
122
    
123
    On the first call we combine the current time with 64 bits of randomness
124
    to give a highly probably globally unique number. Then each call in the same
125
    process adds 1 to a serial number we append to that unique value.
126
    """
1713.1.7 by Robert Collins
Review comments for gen_file_id changes.
127
    # XXX TODO: change bzrlib.add.smart_add to call workingtree.add() rather 
128
    # than having to move the id randomness out of the inner loop like this.
129
    # XXX TODO: for the global randomness this uses we should add the thread-id
130
    # before the serial #.
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
131
    global _gen_id_suffix, _gen_id_serial
132
    if _gen_id_suffix is None:
1713.1.7 by Robert Collins
Review comments for gen_file_id changes.
133
        _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'.
134
    _gen_id_serial += 1
135
    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.
136
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
137
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
138
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'.
139
    """Return new file id for the basename 'name'.
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
140
1713.1.6 by Robert Collins
Move file id random data selection out of the inner loop for 'bzr add'.
141
    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.
142
    """
1864.4.1 by John Arbash Meinel
Fix bug #43801 by squashing file ids a little bit more.
143
    # The real randomness is in the _next_id_suffix, the
144
    # rest of the identifier is just to be nice.
145
    # So we:
146
    # 1) Remove non-ascii word characters to keep the ids portable
147
    # 2) squash to lowercase, so the file id doesn't have to
148
    #    be escaped (case insensitive filesystems would bork for ids
149
    #    that only differred in case without escaping).
150
    # 3) truncate the filename to 20 chars. Long filenames also bork on some
151
    #    filesystems
152
    # 4) Removing starting '.' characters to prevent the file ids from
153
    #    being considered hidden.
154
    ascii_word_only = _gen_file_id_re.sub('', name.lower())
155
    short_no_dots = ascii_word_only.lstrip('.')[:20]
156
    return short_no_dots + _next_id_suffix()
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
157
158
159
def gen_root_id():
160
    """Return a new tree-root file id."""
161
    return gen_file_id('TREE_ROOT')
162
163
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
164
class TreeEntry(object):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
165
    """An entry that implements the minimum interface used by commands.
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
166
167
    This needs further inspection, it may be better to have 
168
    InventoryEntries without ids - though that seems wrong. For now,
169
    this is a parallel hierarchy to InventoryEntry, and needs to become
170
    one of several things: decorates to that hierarchy, children of, or
171
    parents of it.
1399.1.3 by Robert Collins
move change detection for text and metadata from delta to entry.detect_changes
172
    Another note is that these objects are currently only used when there is
173
    no InventoryEntry available - i.e. for unversioned objects.
174
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
175
    """
176
 
177
    def __eq__(self, other):
178
        # yes, this us ugly, TODO: best practice __eq__ style.
179
        return (isinstance(other, TreeEntry)
180
                and other.__class__ == self.__class__)
181
 
182
    def kind_character(self):
183
        return "???"
184
185
186
class TreeDirectory(TreeEntry):
187
    """See TreeEntry. This is a directory in a working tree."""
188
189
    def __eq__(self, other):
190
        return (isinstance(other, TreeDirectory)
191
                and other.__class__ == self.__class__)
192
193
    def kind_character(self):
194
        return "/"
195
196
197
class TreeFile(TreeEntry):
198
    """See TreeEntry. This is a regular file in a working tree."""
199
200
    def __eq__(self, other):
201
        return (isinstance(other, TreeFile)
202
                and other.__class__ == self.__class__)
203
204
    def kind_character(self):
205
        return ''
206
207
208
class TreeLink(TreeEntry):
209
    """See TreeEntry. This is a symlink in a working tree."""
210
211
    def __eq__(self, other):
212
        return (isinstance(other, TreeLink)
213
                and other.__class__ == self.__class__)
214
215
    def kind_character(self):
216
        return ''
217
218
453 by Martin Pool
- Split WorkingTree into its own file
219
class WorkingTree(bzrlib.tree.Tree):
220
    """Working copy tree.
221
222
    The inventory is held in the `Branch` working-inventory, and the
223
    files are in a directory on disk.
224
225
    It is possible for a `WorkingTree` to have a filename which is
226
    not listed in the Inventory and vice versa.
227
    """
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
228
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
229
    def __init__(self, basedir='.',
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
230
                 branch=DEPRECATED_PARAMETER,
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
231
                 _inventory=None,
232
                 _control_files=None,
233
                 _internal=False,
234
                 _format=None,
235
                 _bzrdir=None):
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
236
        """Construct a WorkingTree for basedir.
237
238
        If the branch is not supplied, it is opened automatically.
239
        If the branch is supplied, it must be the branch for this basedir.
240
        (branch.base is not cross checked, because for remote branches that
241
        would be meaningless).
242
        """
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.
243
        self._format = _format
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
244
        self.bzrdir = _bzrdir
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
245
        if not _internal:
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
246
            # not created via open etc.
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
247
            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.
248
                 "Please use bzrdir.open_workingtree or WorkingTree.open().",
249
                 DeprecationWarning,
250
                 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.
251
            wt = WorkingTree.open(basedir)
1681.1.1 by Robert Collins
Make WorkingTree.branch a read only property. (Robert Collins)
252
            self._branch = wt.branch
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
253
            self.basedir = wt.basedir
254
            self._control_files = wt._control_files
255
            self._hashcache = wt._hashcache
256
            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.
257
            self._format = wt._format
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
258
            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.
259
        from bzrlib.hashcache import HashCache
260
        from bzrlib.trace import note, mutter
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
261
        assert isinstance(basedir, basestring), \
262
            "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.
263
        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.
264
        mutter("opening working tree %r", basedir)
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
265
        if deprecated_passed(branch):
266
            if not _internal:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
267
                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
268
                     " Please use bzrdir.open_workingtree() or"
269
                     " WorkingTree.open().",
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
270
                     DeprecationWarning,
271
                     stacklevel=2
272
                     )
1681.1.1 by Robert Collins
Make WorkingTree.branch a read only property. (Robert Collins)
273
            self._branch = branch
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
274
        else:
1681.1.1 by Robert Collins
Make WorkingTree.branch a read only property. (Robert Collins)
275
            self._branch = self.bzrdir.open_branch()
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
276
        self.basedir = realpath(basedir)
1534.4.28 by Robert Collins
first cut at merge from integration.
277
        # 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.
278
        if isinstance(self._format, WorkingTreeFormat2):
279
            # share control object
1534.4.28 by Robert Collins
first cut at merge from integration.
280
            self._control_files = self.branch.control_files
281
        else:
1852.3.1 by Robert Collins
Trivial cleanups to workingtree.py
282
            # assume all other formats have their own control files.
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
283
            assert isinstance(_control_files, LockableFiles), \
284
                    "_control_files must be a LockableFiles, not %r" \
285
                    % _control_files
286
            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.
287
        # update the whole cache up front and write to disk if anything changed;
288
        # in the future we might want to do this more selectively
1467 by Robert Collins
WorkingTree.__del__ has been removed.
289
        # two possible ways offer themselves : in self._unlock, write the cache
290
        # if needed, or, when the cache sees a change, append it to the hash
291
        # cache file, and have the parser take the most recent entry for a
292
        # 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
293
        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.
294
        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.
295
        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.
296
        # 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
297
        #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.
298
299
        if hc.needs_write:
300
            mutter("write hc")
301
            hc.write()
453 by Martin Pool
- Split WorkingTree into its own file
302
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
303
        if _inventory is None:
304
            self._set_inventory(self.read_working_inventory())
305
        else:
306
            self._set_inventory(_inventory)
1185.60.6 by Aaron Bentley
Fixed hashcache
307
1681.1.1 by Robert Collins
Make WorkingTree.branch a read only property. (Robert Collins)
308
    branch = property(
309
        fget=lambda self: self._branch,
310
        doc="""The branch this WorkingTree is connected to.
311
312
            This cannot be set - it is reflective of the actual disk structure
313
            the working tree has been constructed from.
314
            """)
315
1687.1.9 by Robert Collins
Teach WorkingTree about break-lock.
316
    def break_lock(self):
317
        """Break a lock if one is present from another instance.
318
319
        Uses the ui factory to ask for confirmation if the lock may be from
320
        an active process.
321
322
        This will probe the repository for its lock as well.
323
        """
324
        self._control_files.break_lock()
325
        self.branch.break_lock()
326
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
327
    def _set_inventory(self, inv):
328
        self._inventory = inv
329
        self.path2id = self._inventory.path2id
330
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
331
    def is_control_filename(self, filename):
1534.5.16 by Robert Collins
Review feedback.
332
        """True if filename is the name of a control file in this tree.
333
        
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
334
        :param filename: A filename within the tree. This is a relative path
335
        from the root of this tree.
336
1534.5.16 by Robert Collins
Review feedback.
337
        This is true IF and ONLY IF the filename is part of the meta data
338
        that bzr controls in this tree. I.E. a random .bzr directory placed
339
        on disk will not be a control file for this tree.
340
        """
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
341
        return self.bzrdir.is_control_filename(filename)
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
342
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
343
    @staticmethod
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
344
    def open(path=None, _unsupported=False):
345
        """Open an existing working tree at path.
346
347
        """
348
        if path is None:
349
            path = os.path.getcwdu()
350
        control = bzrdir.BzrDir.open(path, _unsupported)
351
        return control.open_workingtree(_unsupported)
352
        
353
    @staticmethod
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
354
    def open_containing(path=None):
355
        """Open an existing working tree which has its root about path.
356
        
357
        This probes for a working tree at path and searches upwards from there.
358
359
        Basically we keep looking up until we find the control directory or
360
        run into /.  If there isn't one, raises NotBranchError.
361
        TODO: give this a new exception.
362
        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
363
364
        :return: The WorkingTree that contains 'path', and the rest of path
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
365
        """
366
        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
367
            path = osutils.getcwd()
1685.1.28 by John Arbash Meinel
Changing open_containing to always return a unicode path.
368
        control, relpath = bzrdir.BzrDir.open_containing(path)
1685.1.27 by John Arbash Meinel
BzrDir works in URLs, but WorkingTree works in unicode paths
369
1685.1.28 by John Arbash Meinel
Changing open_containing to always return a unicode path.
370
        return control.open_workingtree(), relpath
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
371
372
    @staticmethod
373
    def open_downlevel(path=None):
374
        """Open an unsupported working tree.
375
376
        Only intended for advanced situations like upgrading part of a bzrdir.
377
        """
378
        return WorkingTree.open(path, _unsupported=True)
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
379
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
380
    def __iter__(self):
381
        """Iterate through file_ids for this tree.
382
383
        file_ids are in a WorkingTree if they are in the working inventory
384
        and the working file exists.
385
        """
386
        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.
387
        for path, ie in inv.iter_entries():
1836.1.22 by John Arbash Meinel
[merge] bzr.dev 1861
388
            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.
389
                yield ie.file_id
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
390
453 by Martin Pool
- Split WorkingTree into its own file
391
    def __repr__(self):
392
        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
393
                               getattr(self, 'basedir', None))
453 by Martin Pool
- Split WorkingTree into its own file
394
395
    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 \
396
        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()
397
    
398
    def basis_tree(self):
399
        """Return RevisionTree for the current last revision."""
400
        revision_id = self.last_revision()
401
        if revision_id is not None:
402
            try:
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
403
                xml = self.read_basis_inventory()
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
404
                inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
405
            except NoSuchFile:
406
                inv = None
407
            if inv is not None and inv.revision_id == revision_id:
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
408
                return bzrlib.tree.RevisionTree(self.branch.repository, inv,
409
                                                revision_id)
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
410
        # FIXME? RBC 20060403 should we cache the inventory here ?
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
411
        return self.branch.repository.revision_tree(revision_id)
453 by Martin Pool
- Split WorkingTree into its own file
412
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
413
    @staticmethod
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
414
    @deprecated_method(zero_eight)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
415
    def create(branch, directory):
416
        """Create a workingtree for branch at directory.
417
418
        If existing_directory already exists it must have a .bzr directory.
419
        If it does not exist, it will be created.
420
421
        This returns a new WorkingTree object for the new checkout.
422
423
        TODO FIXME RBC 20060124 when we have checkout formats in place this
424
        should accept an optional revisionid to checkout [and reject this if
425
        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
426
427
        XXX: When BzrDir is present, these should be created through that 
428
        interface instead.
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
429
        """
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
430
        warnings.warn('delete WorkingTree.create', stacklevel=3)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
431
        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.
432
        if branch.bzrdir.root_transport.base == transport.base:
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
433
            # same dir 
434
            return branch.bzrdir.create_workingtree()
435
        # different directory, 
436
        # create a branch reference
437
        # and now a working tree.
438
        raise NotImplementedError
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
439
 
440
    @staticmethod
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
441
    @deprecated_method(zero_eight)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
442
    def create_standalone(directory):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
443
        """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.
444
445
        Directory must exist and be empty.
1551.1.2 by Martin Pool
Deprecation warnings for popular APIs that will change in BzrDir
446
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
447
        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.
448
        """
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
449
        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.
450
1713.1.9 by Robert Collins
Paired performance tuning of bzr add. (Robert Collins, Martin Pool).
451
    def relpath(self, path):
452
        """Return the local path portion from a given path.
453
        
454
        The path may be absolute or relative. If its a relative path it is 
455
        interpreted relative to the python current working directory.
456
        """
457
        return relpath(self.basedir, path)
1457.1.3 by Robert Collins
make Branch.relpath delegate to the working tree.
458
453 by Martin Pool
- Split WorkingTree into its own file
459
    def has_filename(self, filename):
1836.1.22 by John Arbash Meinel
[merge] bzr.dev 1861
460
        return osutils.lexists(self.abspath(filename))
453 by Martin Pool
- Split WorkingTree into its own file
461
462
    def get_file(self, file_id):
463
        return self.get_file_byname(self.id2path(file_id))
464
1852.6.9 by Robert Collins
Add more test trees to the tree-implementations tests.
465
    def get_file_text(self, file_id):
466
        return self.get_file(file_id).read()
467
453 by Martin Pool
- Split WorkingTree into its own file
468
    def get_file_byname(self, filename):
469
        return file(self.abspath(filename), 'rb')
470
1773.2.1 by Robert Collins
Teach all trees about unknowns, conflicts and get_parent_ids.
471
    def get_parent_ids(self):
472
        """See Tree.get_parent_ids.
473
        
474
        This implementation reads the pending merges list and last_revision
475
        value and uses that to decide what the parents list should be.
476
        """
477
        last_rev = self.last_revision()
478
        if last_rev is None:
479
            parents = []
480
        else:
481
            parents = [last_rev]
482
        other_parents = self.pending_merges()
483
        return parents + other_parents
484
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
485
    def get_root_id(self):
486
        """Return the id of this trees root"""
487
        inv = self.read_working_inventory()
488
        return inv.root.file_id
489
        
453 by Martin Pool
- Split WorkingTree into its own file
490
    def _get_store_filename(self, file_id):
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
491
        ## XXX: badly named; this is not in the store at all
453 by Martin Pool
- Split WorkingTree into its own file
492
        return self.abspath(self.id2path(file_id))
493
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
494
    @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.
495
    def clone(self, to_bzrdir, revision_id=None, basis=None):
496
        """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()
497
        
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.
498
        Specifically modified files are kept as modified, but
499
        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()
500
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.
501
        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()
502
503
        revision
504
            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.
505
            revision, and and difference between the source trees last revision
506
            and this one merged in.
507
508
        basis
509
            If not None, a closer copy of a tree which may have some files in
510
            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()
511
        """
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.
512
        # assumes the target bzr dir format is compatible.
513
        result = self._format.initialize(to_bzrdir)
514
        self.copy_content_into(result, revision_id)
515
        return result
516
517
    @needs_read_lock
518
    def copy_content_into(self, tree, revision_id=None):
519
        """Copy the current content and user files of this tree into tree."""
520
        if revision_id is None:
521
            transform_tree(tree, self)
522
        else:
523
            # TODO now merge from tree.last_revision to revision
524
            transform_tree(tree, self)
525
            tree.set_last_revision(revision_id)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
526
1457.1.17 by Robert Collins
Branch.commit() has moved to WorkingTree.commit(). (Robert Collins)
527
    @needs_write_lock
1593.1.1 by Robert Collins
Move responsibility for setting branch nickname in commits to the WorkingTree convenience function.
528
    def commit(self, message=None, revprops=None, *args, **kwargs):
529
        # avoid circular imports
1457.1.17 by Robert Collins
Branch.commit() has moved to WorkingTree.commit(). (Robert Collins)
530
        from bzrlib.commit import Commit
1593.1.1 by Robert Collins
Move responsibility for setting branch nickname in commits to the WorkingTree convenience function.
531
        if revprops is None:
532
            revprops = {}
533
        if not 'branch-nick' in revprops:
534
            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.
535
        # args for wt.commit start at message from the Commit.commit method,
536
        # but with branch a kwarg now, passing in args as is results in the
537
        #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.
538
        args = (DEPRECATED_PARAMETER, message, ) + args
1773.1.1 by Robert Collins
Teach WorkingTree.commit to return the committed revision id.
539
        committed_id = Commit().commit( working_tree=self, revprops=revprops,
540
            *args, **kwargs)
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
541
        self._set_inventory(self.read_working_inventory())
1773.1.1 by Robert Collins
Teach WorkingTree.commit to return the committed revision id.
542
        return committed_id
1248 by Martin Pool
- new weave based cleanup [broken]
543
544
    def id2abspath(self, file_id):
545
        return self.abspath(self.id2path(file_id))
546
1185.12.39 by abentley
Propogated has_or_had_id to Tree
547
    def has_id(self, file_id):
453 by Martin Pool
- Split WorkingTree into its own file
548
        # files that have been deleted are excluded
1185.12.39 by abentley
Propogated has_or_had_id to Tree
549
        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.
550
        if not inv.has_id(file_id):
453 by Martin Pool
- Split WorkingTree into its own file
551
            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.
552
        path = inv.id2path(file_id)
1836.1.22 by John Arbash Meinel
[merge] bzr.dev 1861
553
        return osutils.lexists(self.abspath(path))
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
554
1185.12.39 by abentley
Propogated has_or_had_id to Tree
555
    def has_or_had_id(self, file_id):
556
        if file_id == self.inventory.root.file_id:
557
            return True
558
        return self.inventory.has_id(file_id)
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
559
560
    __contains__ = has_id
561
453 by Martin Pool
- Split WorkingTree into its own file
562
    def get_file_size(self, file_id):
1248 by Martin Pool
- new weave based cleanup [broken]
563
        return os.path.getsize(self.id2abspath(file_id))
453 by Martin Pool
- Split WorkingTree into its own file
564
1185.60.6 by Aaron Bentley
Fixed hashcache
565
    @needs_read_lock
1732.1.19 by John Arbash Meinel
If you have the path, use it rather than looking it up again
566
    def get_file_sha1(self, file_id, path=None):
567
        if not path:
568
            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.
569
        return self._hashcache.get_sha1(path)
453 by Martin Pool
- Split WorkingTree into its own file
570
1740.2.5 by Aaron Bentley
Merge from bzr.dev
571
    def get_file_mtime(self, file_id, path=None):
572
        if not path:
573
            path = self._inventory.id2path(file_id)
574
        return os.lstat(self.abspath(path)).st_mtime
575
1732.1.19 by John Arbash Meinel
If you have the path, use it rather than looking it up again
576
    if not supports_executable():
577
        def is_executable(self, file_id, path=None):
1398 by Robert Collins
integrate in Gustavos x-bit patch
578
            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
579
    else:
580
        def is_executable(self, file_id, path=None):
581
            if not path:
582
                path = self._inventory.id2path(file_id)
1398 by Robert Collins
integrate in Gustavos x-bit patch
583
            mode = os.lstat(self.abspath(path)).st_mode
1733.1.4 by Robert Collins
Cosmetic niceties for debugging, extra comments etc.
584
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1398 by Robert Collins
integrate in Gustavos x-bit patch
585
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
586
    @needs_write_lock
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
587
    def add(self, files, ids=None):
588
        """Make files versioned.
589
590
        Note that the command line normally calls smart_add instead,
591
        which can automatically recurse.
592
593
        This adds the files to the inventory, so that they will be
594
        recorded by the next commit.
595
596
        files
597
            List of paths to add, relative to the base of the tree.
598
599
        ids
600
            If set, use these instead of automatically generated ids.
601
            Must be the same length as the list of files, but may
602
            contain None for ids that are to be autogenerated.
603
604
        TODO: Perhaps have an option to add the ids even if the files do
605
              not (yet) exist.
606
607
        TODO: Perhaps callback with the ids and paths as they're added.
608
        """
609
        # TODO: Re-adding a file that is removed in the working copy
610
        # should probably put it back with the previous ID.
611
        if isinstance(files, basestring):
612
            assert(ids is None or isinstance(ids, basestring))
613
            files = [files]
614
            if ids is not None:
615
                ids = [ids]
616
617
        if ids is None:
618
            ids = [None] * len(files)
619
        else:
620
            assert(len(ids) == len(files))
621
622
        inv = self.read_working_inventory()
623
        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.
624
            if self.is_control_filename(f):
1773.4.2 by Martin Pool
Cleanup of imports; undeprecate all_revision_ids()
625
                raise errors.ForbiddenControlFileError(filename=f)
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
626
627
            fp = splitpath(f)
628
629
            if len(fp) == 0:
630
                raise BzrError("cannot add top-level %r" % f)
631
1185.31.38 by John Arbash Meinel
Changing os.path.normpath to osutils.normpath
632
            fullpath = normpath(self.abspath(f))
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
633
            try:
634
                kind = file_kind(fullpath)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
635
            except OSError, e:
636
                if e.errno == errno.ENOENT:
637
                    raise NoSuchFile(fullpath)
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
638
            if not InventoryEntry.versionable_kind(kind):
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
639
                raise errors.BadFileKindError(filename=f, kind=kind)
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
640
            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'.
641
                inv.add_path(f, kind=kind)
642
            else:
643
                inv.add_path(f, kind=kind, file_id=file_id)
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
644
645
        self._write_inventory(inv)
646
647
    @needs_write_lock
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
648
    def add_pending_merge(self, *revision_ids):
649
        # TODO: Perhaps should check at this point that the
650
        # history of the revision is actually present?
651
        p = self.pending_merges()
652
        updated = False
653
        for rev_id in revision_ids:
654
            if rev_id in p:
655
                continue
656
            p.append(rev_id)
657
            updated = True
658
        if updated:
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
659
            self.set_pending_merges(p)
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
660
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
661
    @needs_read_lock
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
662
    def pending_merges(self):
663
        """Return a list of pending merges.
664
665
        These are revisions that have been merged into the working
666
        directory but not yet committed.
667
        """
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
668
        try:
1534.4.28 by Robert Collins
first cut at merge from integration.
669
            merges_file = self._control_files.get_utf8('pending-merges')
1815.2.1 by Jelmer Vernooij
Catch right exception to detect pending-merges file is missing.
670
        except NoSuchFile:
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
671
            return []
672
        p = []
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
673
        for l in merges_file.readlines():
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
674
            p.append(l.rstrip('\n'))
675
        return p
676
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
677
    @needs_write_lock
678
    def set_pending_merges(self, rev_list):
1534.4.28 by Robert Collins
first cut at merge from integration.
679
        self._control_files.put_utf8('pending-merges', '\n'.join(rev_list))
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
680
1534.7.192 by Aaron Bentley
Record hashes produced by merges
681
    @needs_write_lock
682
    def set_merge_modified(self, modified_hashes):
1534.10.3 by Aaron Bentley
Simplify set_merge_modified with rio_file
683
        def iter_stanzas():
684
            for file_id, hash in modified_hashes.iteritems():
685
                yield Stanza(file_id=file_id, hash=hash)
686
        self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
687
688
    @needs_write_lock
689
    def _put_rio(self, filename, stanzas, header):
690
        my_file = rio_file(stanzas, header)
691
        self._control_files.put(filename, my_file)
1534.7.192 by Aaron Bentley
Record hashes produced by merges
692
693
    @needs_read_lock
694
    def merge_modified(self):
695
        try:
696
            hashfile = self._control_files.get('merge-hashes')
697
        except NoSuchFile:
698
            return {}
1534.7.196 by Aaron Bentley
Switched to Rio format for merge-modified list
699
        merge_hashes = {}
700
        try:
701
            if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
702
                raise MergeModifiedFormatError()
703
        except StopIteration:
704
            raise MergeModifiedFormatError()
705
        for s in RioReader(hashfile):
1534.7.198 by Aaron Bentley
Removed spurious encode/decode
706
            file_id = s.get("file_id")
1558.12.10 by Aaron Bentley
Be robust when merge_hash file_id not in inventory
707
            if file_id not in self.inventory:
708
                continue
1534.7.196 by Aaron Bentley
Switched to Rio format for merge-modified list
709
            hash = s.get("hash")
710
            if hash == self.get_file_sha1(file_id):
711
                merge_hashes[file_id] = hash
712
        return merge_hashes
1534.7.192 by Aaron Bentley
Record hashes produced by merges
713
1092.2.6 by Robert Collins
symlink support updated to work
714
    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
715
        return os.readlink(self.id2abspath(file_id))
453 by Martin Pool
- Split WorkingTree into its own file
716
717
    def file_class(self, filename):
718
        if self.path2id(filename):
719
            return 'V'
720
        elif self.is_ignored(filename):
721
            return 'I'
722
        else:
723
            return '?'
724
1551.6.36 by Aaron Bentley
Revert --debris/--detritus changes
725
    def list_files(self):
1732.1.6 by John Arbash Meinel
Fix documentation bug in workingtree.list_files
726
        """Recursively list all files as (path, class, kind, id, entry).
453 by Martin Pool
- Split WorkingTree into its own file
727
728
        Lists, but does not descend into unversioned directories.
729
730
        This does not include files that have been deleted in this
731
        tree.
732
733
        Skips the control directory.
734
        """
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.
735
        inv = self._inventory
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
736
        # Convert these into local objects to save lookup times
1836.1.22 by John Arbash Meinel
[merge] bzr.dev 1861
737
        pathjoin = osutils.pathjoin
738
        file_kind = osutils.file_kind
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
739
740
        # transport.base ends in a slash, we want the piece
741
        # between the last two slashes
742
        transport_base_dir = self.bzrdir.transport.base.rsplit('/', 2)[1]
743
1732.1.11 by John Arbash Meinel
Trying multiple things to get WorkingTree.list_files time down
744
        fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
745
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
746
        # directory file_id, relative path, absolute path, reverse sorted children
747
        children = os.listdir(self.basedir)
748
        children.sort()
1732.1.14 by John Arbash Meinel
Some speedups by not calling pathjoin()
749
        # jam 20060527 The kernel sized tree seems equivalent whether we 
750
        # use a deque and popleft to keep them sorted, or if we use a plain
751
        # 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.
752
        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
753
        stack = [(inv.root.file_id, u'', self.basedir, children)]
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
754
        while stack:
1732.1.13 by John Arbash Meinel
A large improvement from not popping the parent off until we have done all children.
755
            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
756
757
            while children:
1732.1.13 by John Arbash Meinel
A large improvement from not popping the parent off until we have done all children.
758
                f = children.popleft()
453 by Martin Pool
- Split WorkingTree into its own file
759
                ## TODO: If we find a subdirectory with its own .bzr
760
                ## directory, then that is a separate tree and we
761
                ## should exclude it.
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
762
763
                # the bzrdir for this tree
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
764
                if transport_base_dir == f:
453 by Martin Pool
- Split WorkingTree into its own file
765
                    continue
766
1732.1.14 by John Arbash Meinel
Some speedups by not calling pathjoin()
767
                # we know that from_dir_relpath and from_dir_abspath never end in a slash
768
                # 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
769
                # than the checks of pathjoin(), all relative paths will have an extra slash
770
                # at the beginning
1732.1.14 by John Arbash Meinel
Some speedups by not calling pathjoin()
771
                fp = from_dir_relpath + '/' + f
453 by Martin Pool
- Split WorkingTree into its own file
772
773
                # absolute path
1732.1.14 by John Arbash Meinel
Some speedups by not calling pathjoin()
774
                fap = from_dir_abspath + '/' + f
453 by Martin Pool
- Split WorkingTree into its own file
775
                
776
                f_ie = inv.get_child(from_dir_id, f)
777
                if f_ie:
778
                    c = 'V'
1551.6.36 by Aaron Bentley
Revert --debris/--detritus changes
779
                elif self.is_ignored(fp[1:]):
780
                    c = 'I'
453 by Martin Pool
- Split WorkingTree into its own file
781
                else:
1830.3.3 by John Arbash Meinel
inside workingtree check for normalized filename access
782
                    # we may not have found this file, because of a unicode issue
783
                    f_norm, can_access = osutils.normalized_filename(f)
784
                    if f == f_norm or not can_access:
785
                        # No change, so treat this file normally
786
                        c = '?'
787
                    else:
788
                        # this file can be accessed by a normalized path
789
                        # check again if it is versioned
790
                        # these lines are repeated here for performance
791
                        f = f_norm
792
                        fp = from_dir_relpath + '/' + f
793
                        fap = from_dir_abspath + '/' + f
794
                        f_ie = inv.get_child(from_dir_id, f)
795
                        if f_ie:
796
                            c = 'V'
797
                        elif self.is_ignored(fp[1:]):
798
                            c = 'I'
799
                        else:
800
                            c = '?'
453 by Martin Pool
- Split WorkingTree into its own file
801
802
                fk = file_kind(fap)
803
804
                if f_ie:
805
                    if f_ie.kind != fk:
806
                        raise BzrCheckError("file %r entered as kind %r id %r, "
807
                                            "now of kind %r"
808
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
809
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
810
                # make a last minute entry
811
                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
812
                    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
813
                else:
1732.1.11 by John Arbash Meinel
Trying multiple things to get WorkingTree.list_files time down
814
                    try:
1732.1.21 by John Arbash Meinel
We don't need to strip off 2 characters, just do one, minor memory improvement
815
                        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
816
                    except KeyError:
1732.1.21 by John Arbash Meinel
We don't need to strip off 2 characters, just do one, minor memory improvement
817
                        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.
818
                    continue
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
819
                
453 by Martin Pool
- Split WorkingTree into its own file
820
                if fk != 'directory':
821
                    continue
822
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
823
                # 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.
824
                new_children = os.listdir(fap)
825
                new_children.sort()
826
                new_children = collections.deque(new_children)
827
                stack.append((f_ie.file_id, fp, fap, new_children))
1732.1.9 by John Arbash Meinel
Non-recursive implementation of WorkingTree.list_files
828
                # Break out of inner loop, so that we start outer loop with child
829
                break
1732.1.22 by John Arbash Meinel
Bug in list_files if the last entry in a directory is another directory
830
            else:
831
                # 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.
832
                stack.pop()
1732.1.13 by John Arbash Meinel
A large improvement from not popping the parent off until we have done all children.
833
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
834
835
    @needs_write_lock
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
836
    def move(self, from_paths, to_name):
837
        """Rename files.
838
839
        to_name must exist in the inventory.
840
841
        If to_name exists and is a directory, the files are moved into
842
        it, keeping their old names.  
843
844
        Note that to_name is only the last component of the new name;
845
        this doesn't change the directory.
846
847
        This returns a list of (from_path, to_path) pairs for each
848
        entry that is moved.
849
        """
850
        result = []
851
        ## TODO: Option to move IDs only
852
        assert not isinstance(from_paths, basestring)
853
        inv = self.inventory
854
        to_abs = self.abspath(to_name)
855
        if not isdir(to_abs):
856
            raise BzrError("destination %r is not a directory" % to_abs)
857
        if not self.has_filename(to_name):
858
            raise BzrError("destination %r not in working directory" % to_abs)
859
        to_dir_id = inv.path2id(to_name)
860
        if to_dir_id == None and to_name != '':
861
            raise BzrError("destination %r is not a versioned directory" % to_name)
862
        to_dir_ie = inv[to_dir_id]
863
        if to_dir_ie.kind not in ('directory', 'root_directory'):
864
            raise BzrError("destination %r is not a directory" % to_abs)
865
866
        to_idpath = inv.get_idpath(to_dir_id)
867
868
        for f in from_paths:
869
            if not self.has_filename(f):
870
                raise BzrError("%r does not exist in working tree" % f)
871
            f_id = inv.path2id(f)
872
            if f_id == None:
873
                raise BzrError("%r is not versioned" % f)
874
            name_tail = splitpath(f)[-1]
1732.1.1 by John Arbash Meinel
deprecating appendpath, it does exactly what pathjoin does
875
            dest_path = pathjoin(to_name, name_tail)
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
876
            if self.has_filename(dest_path):
877
                raise BzrError("destination %r already exists" % dest_path)
878
            if f_id in to_idpath:
879
                raise BzrError("can't move %r to a subdirectory of itself" % f)
880
881
        # OK, so there's a race here, it's possible that someone will
882
        # create a file in this interval and then the rename might be
883
        # left half-done.  But we should have caught most problems.
884
        orig_inv = deepcopy(self.inventory)
885
        try:
886
            for f in from_paths:
887
                name_tail = splitpath(f)[-1]
1732.1.1 by John Arbash Meinel
deprecating appendpath, it does exactly what pathjoin does
888
                dest_path = pathjoin(to_name, name_tail)
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
889
                result.append((f, dest_path))
890
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
891
                try:
892
                    rename(self.abspath(f), self.abspath(dest_path))
893
                except OSError, e:
894
                    raise BzrError("failed to rename %r to %r: %s" %
895
                                   (f, dest_path, e[1]),
896
                            ["rename rolled back"])
897
        except:
898
            # restore the inventory on error
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
899
            self._set_inventory(orig_inv)
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
900
            raise
901
        self._write_inventory(inv)
902
        return result
903
904
    @needs_write_lock
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
905
    def rename_one(self, from_rel, to_rel):
906
        """Rename one file.
907
908
        This can change the directory or the filename or both.
909
        """
910
        inv = self.inventory
911
        if not self.has_filename(from_rel):
912
            raise BzrError("can't rename: old working file %r does not exist" % from_rel)
913
        if self.has_filename(to_rel):
914
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
915
916
        file_id = inv.path2id(from_rel)
917
        if file_id == None:
918
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
919
920
        entry = inv[file_id]
921
        from_parent = entry.parent_id
922
        from_name = entry.name
923
        
924
        if inv.path2id(to_rel):
925
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
926
927
        to_dir, to_tail = os.path.split(to_rel)
928
        to_dir_id = inv.path2id(to_dir)
929
        if to_dir_id == None and to_dir != '':
930
            raise BzrError("can't determine destination directory id for %r" % to_dir)
931
932
        mutter("rename_one:")
933
        mutter("  file_id    {%s}" % file_id)
934
        mutter("  from_rel   %r" % from_rel)
935
        mutter("  to_rel     %r" % to_rel)
936
        mutter("  to_dir     %r" % to_dir)
937
        mutter("  to_dir_id  {%s}" % to_dir_id)
938
939
        inv.rename(file_id, to_dir_id, to_tail)
940
941
        from_abs = self.abspath(from_rel)
942
        to_abs = self.abspath(to_rel)
943
        try:
944
            rename(from_abs, to_abs)
945
        except OSError, e:
946
            inv.rename(file_id, from_parent, from_name)
947
            raise BzrError("failed to rename %r to %r: %s"
948
                    % (from_abs, to_abs, e[1]),
949
                    ["rename rolled back"])
950
        self._write_inventory(inv)
951
952
    @needs_read_lock
453 by Martin Pool
- Split WorkingTree into its own file
953
    def unknowns(self):
1508.1.6 by Robert Collins
Move Branch.unknowns() to WorkingTree.
954
        """Return all unknown files.
955
956
        These are files in the working directory that are not versioned or
957
        control files or ignored.
958
        """
453 by Martin Pool
- Split WorkingTree into its own file
959
        for subp in self.extras():
960
            if not self.is_ignored(subp):
961
                yield subp
962
1534.10.16 by Aaron Bentley
Small tweaks
963
    @deprecated_method(zero_eight)
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
964
    def iter_conflicts(self):
1534.10.16 by Aaron Bentley
Small tweaks
965
        """List all files in the tree that have text or content conflicts.
1534.10.22 by Aaron Bentley
Got ConflictList implemented
966
        DEPRECATED.  Use conflicts instead."""
1534.10.10 by Aaron Bentley
Resolve uses the new stuff.
967
        return self._iter_conflicts()
968
1534.10.9 by Aaron Bentley
Switched display functions to conflict_lines
969
    def _iter_conflicts(self):
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
970
        conflicted = set()
1732.1.11 by John Arbash Meinel
Trying multiple things to get WorkingTree.list_files time down
971
        for info in self.list_files():
972
            path = info[0]
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
973
            stem = get_conflicted_stem(path)
974
            if stem is None:
975
                continue
976
            if stem not in conflicted:
977
                conflicted.add(stem)
978
                yield stem
453 by Martin Pool
- Split WorkingTree into its own file
979
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
980
    @needs_write_lock
1185.76.1 by Erik Bågfors
Support for --revision in pull
981
    def pull(self, source, overwrite=False, stop_revision=None):
1551.2.36 by Aaron Bentley
Make pull update the progress bar more nicely
982
        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().
983
        source.lock_read()
984
        try:
1551.2.36 by Aaron Bentley
Make pull update the progress bar more nicely
985
            pp = ProgressPhase("Pull phase", 2, top_pb)
986
            pp.next_phase()
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
987
            old_revision_history = self.branch.revision_history()
1563.1.4 by Robert Collins
Fix 'bzr pull' on metadir trees.
988
            basis_tree = self.basis_tree()
1534.4.54 by Robert Collins
Merge from integration.
989
            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().
990
            new_revision_history = self.branch.revision_history()
991
            if new_revision_history != old_revision_history:
1551.2.36 by Aaron Bentley
Make pull update the progress bar more nicely
992
                pp.next_phase()
1465 by Robert Collins
Bugfix the new pull --clobber to not generate spurious conflicts.
993
                if len(old_revision_history):
994
                    other_revision = old_revision_history[-1]
995
                else:
996
                    other_revision = None
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
997
                repository = self.branch.repository
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
998
                pb = bzrlib.ui.ui_factory.nested_progress_bar()
999
                try:
1000
                    merge_inner(self.branch,
1001
                                self.branch.basis_tree(),
1002
                                basis_tree, 
1003
                                this_tree=self, 
1004
                                pb=pb)
1005
                finally:
1006
                    pb.finished()
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
1007
                self.set_last_revision(self.branch.last_revision())
1185.33.44 by Martin Pool
[patch] show number of revisions pushed/pulled/merged (Robey Pointer)
1008
            return count
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
1009
        finally:
1010
            source.unlock()
1551.2.36 by Aaron Bentley
Make pull update the progress bar more nicely
1011
            top_pb.finished()
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
1012
453 by Martin Pool
- Split WorkingTree into its own file
1013
    def extras(self):
1014
        """Yield all unknown files in this WorkingTree.
1015
1016
        If there are any unknown directories then only the directory is
1017
        returned, not all its children.  But if there are unknown files
1018
        under a versioned subdirectory, they are returned.
1019
1020
        Currently returned depth-first, sorted by name within directories.
1021
        """
1022
        ## TODO: Work from given directory downwards
1023
        for path, dir_entry in self.inventory.directories():
1711.2.101 by John Arbash Meinel
Clean up some unnecessary mutter() calls
1024
            # mutter("search for unknowns in %r", path)
453 by Martin Pool
- Split WorkingTree into its own file
1025
            dirabs = self.abspath(path)
1026
            if not isdir(dirabs):
1027
                # e.g. directory deleted
1028
                continue
1029
1030
            fl = []
1031
            for subf in os.listdir(dirabs):
1830.3.3 by John Arbash Meinel
inside workingtree check for normalized filename access
1032
                if subf == '.bzr':
1033
                    continue
1034
                if subf not in dir_entry.children:
1035
                    subf_norm, can_access = osutils.normalized_filename(subf)
1036
                    if subf_norm != subf and can_access:
1037
                        if subf_norm not in dir_entry.children:
1038
                            fl.append(subf_norm)
1039
                    else:
1040
                        fl.append(subf)
453 by Martin Pool
- Split WorkingTree into its own file
1041
            
1042
            fl.sort()
1043
            for subf in fl:
1732.1.1 by John Arbash Meinel
deprecating appendpath, it does exactly what pathjoin does
1044
                subp = pathjoin(path, subf)
453 by Martin Pool
- Split WorkingTree into its own file
1045
                yield subp
1046
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
1047
    def _translate_ignore_rule(self, rule):
1048
        """Translate a single ignore rule to a regex.
1049
1713.2.7 by Robert Collins
Better description of ignore rule types from Martin.
1050
        There are two types of ignore rules.  Those that do not contain a / are
1051
        matched against the tail of the filename (that is, they do not care
1052
        what directory the file is in.)  Rules which do contain a slash must
1053
        match the entire path.  As a special case, './' at the start of the
1054
        string counts as a slash in the string but is removed before matching
1055
        (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.
1056
1057
        :return: The translated regex.
1058
        """
1059
        if rule[:2] in ('./', '.\\'):
1060
            # rootdir rule
1061
            result = fnmatch.translate(rule[2:])
1062
        elif '/' in rule or '\\' in rule:
1063
            # path prefix 
1064
            result = fnmatch.translate(rule)
1065
        else:
1066
            # default rule style.
1067
            result = "(?:.*/)?(?!.*/)" + fnmatch.translate(rule)
1068
        assert result[-1] == '$', "fnmatch.translate did not add the expected $"
1069
        return "(" + result + ")"
1070
1071
    def _combine_ignore_rules(self, rules):
1072
        """Combine a list of ignore rules into a single regex object.
1073
1074
        Each individual rule is combined with | to form a big regex, which then
1075
        has $ added to it to form something like ()|()|()$. The group index for
1076
        each subregex's outermost group is placed in a dictionary mapping back 
1077
        to the rule. This allows quick identification of the matching rule that
1078
        triggered a match.
1713.2.5 by Robert Collins
Support more than 100 ignore rules.
1079
        :return: a list of the compiled regex and the matching-group index 
1080
        dictionaries. We return a list because python complains if you try to 
1081
        combine more than 100 regexes.
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
1082
        """
1713.2.5 by Robert Collins
Support more than 100 ignore rules.
1083
        result = []
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
1084
        groups = {}
1085
        next_group = 0
1086
        translated_rules = []
1087
        for rule in rules:
1088
            translated_rule = self._translate_ignore_rule(rule)
1089
            compiled_rule = re.compile(translated_rule)
1090
            groups[next_group] = rule
1091
            next_group += compiled_rule.groups
1092
            translated_rules.append(translated_rule)
1713.2.5 by Robert Collins
Support more than 100 ignore rules.
1093
            if next_group == 99:
1094
                result.append((re.compile("|".join(translated_rules)), groups))
1095
                groups = {}
1096
                next_group = 0
1097
                translated_rules = []
1098
        if len(translated_rules):
1099
            result.append((re.compile("|".join(translated_rules)), groups))
1100
        return result
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
1101
453 by Martin Pool
- Split WorkingTree into its own file
1102
    def ignored_files(self):
1103
        """Yield list of PATH, IGNORE_PATTERN"""
1104
        for subp in self.extras():
1105
            pat = self.is_ignored(subp)
1106
            if pat != None:
1107
                yield subp, pat
1108
1109
    def get_ignore_list(self):
1110
        """Return list of ignore patterns.
1111
1112
        Cached in the Tree object after the first call.
1113
        """
1836.1.30 by John Arbash Meinel
Change ignore functions to use sets instead of lists.
1114
        ignoreset = getattr(self, '_ignoreset', None)
1115
        if ignoreset is not None:
1116
            return ignoreset
1117
1118
        ignore_globs = set(bzrlib.DEFAULT_IGNORE)
1119
        ignore_globs.update(ignores.get_runtime_ignores())
1120
1121
        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
1122
453 by Martin Pool
- Split WorkingTree into its own file
1123
        if self.has_filename(bzrlib.IGNORE_FILENAME):
1124
            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
1125
            try:
1836.1.30 by John Arbash Meinel
Change ignore functions to use sets instead of lists.
1126
                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
1127
            finally:
1128
                f.close()
1129
1836.1.30 by John Arbash Meinel
Change ignore functions to use sets instead of lists.
1130
        self._ignoreset = ignore_globs
1836.1.4 by John Arbash Meinel
Cleanup is_ignored to handle comment lines, and a global ignore pattern
1131
        self._ignore_regex = self._combine_ignore_rules(ignore_globs)
1132
        return ignore_globs
453 by Martin Pool
- Split WorkingTree into its own file
1133
1713.2.3 by Robert Collins
Combine ignore rules into a single regex preventing pathological behaviour during add.
1134
    def _get_ignore_rules_as_regex(self):
1135
        """Return a regex of the ignore rules and a mapping dict.
1136
1137
        :return: (ignore rules compiled regex, dictionary mapping rule group 
1138
        indices to original rule.)
1139
        """
1836.1.30 by John Arbash Meinel
Change ignore functions to use sets instead of lists.
1140
        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.
1141
            self.get_ignore_list()
1142
        return self._ignore_regex
1143
453 by Martin Pool
- Split WorkingTree into its own file
1144
    def is_ignored(self, filename):
1145
        r"""Check whether the filename matches an ignore pattern.
1146
1147
        Patterns containing '/' or '\' need to match the whole path;
1148
        others match against only the last component.
1149
1150
        If the file is ignored, returns the pattern which caused it to
1151
        be ignored, otherwise None.  So this can simply be used as a
1152
        boolean if desired."""
1153
1154
        # TODO: Use '**' to match directories, and other extended
1155
        # globbing stuff from cvs/rsync.
1156
1157
        # XXX: fnmatch is actually not quite what we want: it's only
1158
        # approximately the same as real Unix fnmatch, and doesn't
1159
        # treat dotfiles correctly and allows * to match /.
1160
        # Eventually it should be replaced with something more
1161
        # accurate.
1713.2.5 by Robert Collins
Support more than 100 ignore rules.
1162
    
1163
        rules = self._get_ignore_rules_as_regex()
1164
        for regex, mapping in rules:
1165
            match = regex.match(filename)
1166
            if match is not None:
1167
                # one or more of the groups in mapping will have a non-None group 
1168
                # match.
1169
                groups = match.groups()
1170
                rules = [mapping[group] for group in 
1171
                    mapping if groups[group] is not None]
1172
                return rules[0]
1707.2.5 by Robert Collins
slightly improve add
1173
        return None
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
1174
1185.12.28 by Aaron Bentley
Removed use of readonly path for executability test
1175
    def kind(self, file_id):
1176
        return file_kind(self.id2abspath(file_id))
1177
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1178
    @needs_read_lock
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1179
    def last_revision(self):
1180
        """Return the last revision id of this working tree.
1181
1182
        In early branch formats this was == the branch last_revision,
1183
        but that cannot be relied upon - for working tree operations,
1184
        always use tree.last_revision().
1185
        """
1186
        return self.branch.last_revision()
1187
1694.2.6 by Martin Pool
[merge] bzr.dev
1188
    def is_locked(self):
1189
        return self._control_files.is_locked()
1190
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1191
    def lock_read(self):
1192
        """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.
1193
        self.branch.lock_read()
1194
        try:
1195
            return self._control_files.lock_read()
1196
        except:
1197
            self.branch.unlock()
1198
            raise
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1199
1200
    def lock_write(self):
1201
        """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.
1202
        self.branch.lock_write()
1203
        try:
1204
            return self._control_files.lock_write()
1205
        except:
1206
            self.branch.unlock()
1207
            raise
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1208
1694.2.6 by Martin Pool
[merge] bzr.dev
1209
    def get_physical_lock_status(self):
1210
        return self._control_files.get_physical_lock_status()
1211
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1212
    def _basis_inventory_name(self):
1213
        return 'basis-inventory'
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1214
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1215
    @needs_write_lock
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1216
    def set_last_revision(self, new_revision):
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1217
        """Change the last revision in the working tree."""
1218
        if self._change_last_revision(new_revision):
1219
            self._cache_basis_inventory(new_revision)
1220
1221
    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.
1222
        """Template method part of set_last_revision to perform the change.
1223
        
1224
        This is used to allow WorkingTree3 instances to not affect branch
1225
        when their last revision is set.
1226
        """
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1227
        if new_revision is None:
1228
            self.branch.set_revision_history([])
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1229
            return False
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1230
        # current format is locked in with the branch
1231
        revision_history = self.branch.revision_history()
1232
        try:
1233
            position = revision_history.index(new_revision)
1234
        except ValueError:
1235
            raise errors.NoSuchRevision(self.branch, new_revision)
1236
        self.branch.set_revision_history(revision_history[:position + 1])
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1237
        return True
1238
1239
    def _cache_basis_inventory(self, new_revision):
1240
        """Cache new_revision as the basis inventory."""
1740.2.3 by Aaron Bentley
Only reserialize the working tree basis inventory when needed.
1241
        # TODO: this should allow the ready-to-use inventory to be passed in,
1242
        # as commit already has that ready-to-use [while the format is the
1243
        # same, that is].
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1244
        try:
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1245
            # this double handles the inventory - unpack and repack - 
1246
            # but is easier to understand. We can/should put a conditional
1247
            # in here based on whether the inventory is in the latest format
1248
            # - perhaps we should repack all inventories on a repository
1249
            # upgrade ?
1740.2.3 by Aaron Bentley
Only reserialize the working tree basis inventory when needed.
1250
            # the fast path is to copy the raw xml from the repository. If the
1251
            # xml contains 'revision_id="', then we assume the right 
1252
            # revision_id is set. We must check for this full string, because a
1253
            # root node id can legitimately look like 'revision_id' but cannot
1254
            # contain a '"'.
1255
            xml = self.branch.repository.get_inventory_xml(new_revision)
1256
            if not 'revision_id="' in xml.split('\n', 1)[0]:
1257
                inv = self.branch.repository.deserialise_inventory(
1258
                    new_revision, xml)
1259
                inv.revision_id = new_revision
1260
                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.
1261
            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.
1262
            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.
1263
            sio = StringIO(xml)
1264
            self._control_files.put(path, sio)
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1265
        except WeaveRevisionNotPresent:
1266
            pass
1267
1638.1.2 by Robert Collins
Change the basis-inventory file to not have the revision-id in the file name.
1268
    def read_basis_inventory(self):
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1269
        """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.
1270
        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.
1271
        return self._control_files.get(path).read()
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
1272
        
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1273
    @needs_read_lock
1274
    def read_working_inventory(self):
1275
        """Read the working inventory."""
1276
        # ElementTree does its own conversion from UTF-8, so open in
1277
        # binary.
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1278
        result = bzrlib.xml5.serializer_v5.read_inventory(
1534.4.28 by Robert Collins
first cut at merge from integration.
1279
            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()
1280
        self._set_inventory(result)
1281
        return result
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1282
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1283
    @needs_write_lock
1685.1.77 by Wouter van Heyst
WorkingTree.remove takes an optional output file
1284
    def remove(self, files, verbose=False, to_file=None):
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1285
        """Remove nominated files from the working inventory..
1286
1287
        This does not remove their text.  This does not run on XXX on what? RBC
1288
1289
        TODO: Refuse to remove modified files unless --force is given?
1290
1291
        TODO: Do something useful with directories.
1292
1293
        TODO: Should this remove the text or not?  Tough call; not
1294
        removing may be useful and the user can just use use rm, and
1295
        is the opposite of add.  Removing it is consistent with most
1296
        other tools.  Maybe an option.
1297
        """
1298
        ## TODO: Normalize names
1299
        ## TODO: Remove nested loops; better scalability
1300
        if isinstance(files, basestring):
1301
            files = [files]
1302
1303
        inv = self.inventory
1304
1305
        # do this before any modifications
1306
        for f in files:
1307
            fid = inv.path2id(f)
1308
            if not fid:
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
1309
                # TODO: Perhaps make this just a warning, and continue?
1310
                # This tends to happen when 
1311
                raise NotVersionedError(path=f)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1312
            if verbose:
1313
                # having remove it, it must be either ignored or unknown
1314
                if self.is_ignored(f):
1315
                    new_status = 'I'
1316
                else:
1317
                    new_status = '?'
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1318
                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.
1319
            del inv[fid]
1320
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1321
        self._write_inventory(inv)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1322
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1323
    @needs_write_lock
1534.9.4 by Aaron Bentley
Added progress bars to revert.
1324
    def revert(self, filenames, old_tree=None, backups=True, 
1325
               pb=DummyProgress()):
1534.7.47 by Aaron Bentley
Started work on 'revert'
1326
        from transform import revert
1534.10.14 by Aaron Bentley
Made revert clear conflicts
1327
        from conflicts import resolve
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1328
        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()
1329
            old_tree = self.basis_tree()
1558.7.13 by Aaron Bentley
WorkingTree.revert returns conflicts
1330
        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.
1331
        if not len(filenames):
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
1332
            self.set_pending_merges([])
1534.10.14 by Aaron Bentley
Made revert clear conflicts
1333
            resolve(self)
1334
        else:
1534.10.15 by Aaron Bentley
Revert does resolve
1335
            resolve(self, filenames, ignore_misses=True)
1558.7.13 by Aaron Bentley
WorkingTree.revert returns conflicts
1336
        return conflicts
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1337
1658.1.3 by Martin Pool
Doc
1338
    # XXX: This method should be deprecated in favour of taking in a proper
1339
    # new Inventory object.
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1340
    @needs_write_lock
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1341
    def set_inventory(self, new_inventory_list):
1342
        from bzrlib.inventory import (Inventory,
1343
                                      InventoryDirectory,
1344
                                      InventoryEntry,
1345
                                      InventoryFile,
1346
                                      InventoryLink)
1347
        inv = Inventory(self.get_root_id())
1658.1.2 by Martin Pool
Revert changes to WorkingTree.set_inventory to unbreak bzrtools
1348
        for path, file_id, parent, kind in new_inventory_list:
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1349
            name = os.path.basename(path)
1350
            if name == "":
1351
                continue
1352
            # fixme, there should be a factory function inv,add_?? 
1353
            if kind == 'directory':
1354
                inv.add(InventoryDirectory(file_id, name, parent))
1355
            elif kind == 'file':
1658.1.2 by Martin Pool
Revert changes to WorkingTree.set_inventory to unbreak bzrtools
1356
                inv.add(InventoryFile(file_id, name, parent))
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1357
            elif kind == 'symlink':
1358
                inv.add(InventoryLink(file_id, name, parent))
1359
            else:
1360
                raise BzrError("unknown kind %r" % kind)
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1361
        self._write_inventory(inv)
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1362
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1363
    @needs_write_lock
1364
    def set_root_id(self, file_id):
1365
        """Set the root id for this tree."""
1366
        inv = self.read_working_inventory()
1367
        orig_root_id = inv.root.file_id
1368
        del inv._byid[inv.root.file_id]
1369
        inv.root.file_id = file_id
1370
        inv._byid[inv.root.file_id] = inv.root
1371
        for fid in inv:
1372
            entry = inv[fid]
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1373
            if entry.parent_id == orig_root_id:
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1374
                entry.parent_id = inv.root.file_id
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1375
        self._write_inventory(inv)
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1376
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1377
    def unlock(self):
1378
        """See Branch.unlock.
1379
        
1380
        WorkingTree locking just uses the Branch locking facilities.
1381
        This is current because all working trees have an embedded branch
1382
        within them. IF in the future, we were to make branch data shareable
1383
        between multiple working trees, i.e. via shared storage, then we 
1384
        would probably want to lock both the local tree, and the branch.
1385
        """
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.
1386
        raise NotImplementedError(self.unlock)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1387
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1388
    @needs_write_lock
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1389
    def update(self):
1587.1.11 by Robert Collins
Local commits appear to be working properly.
1390
        """Update a working tree along its branch.
1391
1392
        This will update the branch if its bound too, which means we have multiple trees involved:
1393
        The new basis tree of the master.
1394
        The old basis tree of the branch.
1395
        The old basis tree of the working tree.
1396
        The current working tree state.
1397
        pathologically all three may be different, and non ancestors of each other.
1398
        Conceptually we want to:
1399
        Preserve the wt.basis->wt.state changes
1400
        Transform the wt.basis to the new master basis.
1401
        Apply a merge of the old branch basis to get any 'local' changes from it into the tree.
1402
        Restore the wt.basis->wt.state changes.
1403
1404
        There isn't a single operation at the moment to do that, so we:
1405
        Merge current state -> basis tree of the master w.r.t. the old tree basis.
1406
        Do a 'normal' merge of the old branch basis if it is relevant.
1407
        """
1587.1.10 by Robert Collins
update updates working tree and branch together.
1408
        old_tip = self.branch.update()
1587.1.11 by Robert Collins
Local commits appear to be working properly.
1409
        if old_tip is not None:
1410
            self.add_pending_merge(old_tip)
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1411
        self.branch.lock_read()
1412
        try:
1587.1.11 by Robert Collins
Local commits appear to be working properly.
1413
            result = 0
1414
            if self.last_revision() != self.branch.last_revision():
1415
                # merge tree state up to new branch tip.
1416
                basis = self.basis_tree()
1417
                to_tree = self.branch.basis_tree()
1418
                result += merge_inner(self.branch,
1419
                                      to_tree,
1420
                                      basis,
1421
                                      this_tree=self)
1422
                self.set_last_revision(self.branch.last_revision())
1423
            if old_tip and old_tip != self.last_revision():
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1424
                # our last revision was not the prior branch last revision
1587.1.11 by Robert Collins
Local commits appear to be working properly.
1425
                # and we have converted that last revision to a pending merge.
1426
                # base is somewhere between the branch tip now
1427
                # and the now pending merge
1428
                from bzrlib.revision import common_ancestor
1429
                try:
1430
                    base_rev_id = common_ancestor(self.branch.last_revision(),
1431
                                                  old_tip,
1432
                                                  self.branch.repository)
1433
                except errors.NoCommonAncestor:
1434
                    base_rev_id = None
1435
                base_tree = self.branch.repository.revision_tree(base_rev_id)
1436
                other_tree = self.branch.repository.revision_tree(old_tip)
1437
                result += merge_inner(self.branch,
1438
                                      other_tree,
1439
                                      base_tree,
1440
                                      this_tree=self)
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1441
            return result
1442
        finally:
1443
            self.branch.unlock()
1444
1445
    @needs_write_lock
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1446
    def _write_inventory(self, inv):
1447
        """Write inventory as the current inventory."""
1448
        sio = StringIO()
1449
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
1450
        sio.seek(0)
1534.4.28 by Robert Collins
first cut at merge from integration.
1451
        self._control_files.put('inventory', sio)
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
1452
        self._set_inventory(inv)
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1453
        mutter('wrote working inventory')
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1454
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1455
    def set_conflicts(self, arg):
1456
        raise UnsupportedOperation(self.set_conflicts, self)
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
1457
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
1458
    def add_conflicts(self, arg):
1459
        raise UnsupportedOperation(self.add_conflicts, self)
1460
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
1461
    @needs_read_lock
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1462
    def conflicts(self):
1463
        conflicts = ConflictList()
1534.10.9 by Aaron Bentley
Switched display functions to conflict_lines
1464
        for conflicted in self._iter_conflicts():
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
1465
            text = True
1466
            try:
1467
                if file_kind(self.abspath(conflicted)) != "file":
1468
                    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.
1469
            except errors.NoSuchFile:
1470
                text = False
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
1471
            if text is True:
1472
                for suffix in ('.THIS', '.OTHER'):
1473
                    try:
1474
                        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.
1475
                        if kind != "file":
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
1476
                            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.
1477
                    except errors.NoSuchFile:
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
1478
                        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.
1479
                    if text == False:
1534.10.8 by Aaron Bentley
Implemented conflict_lines in terms of old system on WorkingTree
1480
                        break
1481
            ctype = {True: 'text conflict', False: 'contents conflict'}[text]
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1482
            conflicts.append(Conflict.factory(ctype, path=conflicted,
1483
                             file_id=self.path2id(conflicted)))
1484
        return conflicts
1485
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
1486
    def walkdirs(self, prefix=""):
1852.15.7 by Robert Collins
Start testing behaviour of unknowns in WorkingTree.walkdirs.
1487
        inventory_iterator = self._walkdirs(prefix)
1488
        disk_top = self.abspath(prefix)
1489
        if disk_top.endswith('/'):
1490
            disk_top = disk_top[:-1]
1491
        top_strip_len = len(disk_top) + 1
1492
        disk_iterator = osutils.walkdirs(disk_top, prefix)
1493
        current_inv = inventory_iterator.next()
1494
        current_disk = disk_iterator.next()
1495
        inv_finished = False
1496
        disk_finished = False
1497
        while not inv_finished or not disk_finished:
1498
            if not disk_finished:
1499
                # strip out .bzr dirs
1500
                if current_disk[0][1][top_strip_len:] == '':
1501
                    # osutils.walkdirs can be made nicer - 
1502
                    # yield the path-from-prefix rather than the pathjoined
1503
                    # value.
1504
                    bzrdir_loc = bisect_left(current_disk[1], ('.bzr', '.bzr'))
1505
                    if current_disk[1][bzrdir_loc][0] == '.bzr':
1506
                        # we dont yield the contents of, or, .bzr itself.
1507
                        del current_disk[1][bzrdir_loc]
1508
            direction = cmp(current_inv[0][0], current_disk[0][0])
1509
            if direction < 0:
1510
                # inventory is before disk - unknown.
1511
                dirblock = [(relpath, basename, kind, stat, top_path[top_strip_len:], None, None) for relpath, basename, kind, stat, top_path in current_disk[1]]
1512
                yield (current_disk[0][0], current_disk[0][1][top_strip_len:], None), dirblock
1513
                try:
1514
                    current_disk = disk_iterator.next()
1515
                except StopIteration:
1516
                    disk_finished = True
1517
            elif direction > 0:
1518
                # disk is before inventory - missing
1519
                try:
1520
                    current_inv = inventory_iterator.next()
1521
                except StopIteration:
1522
                    inv_finished = True
1523
            else:
1524
                # versioned present directory
1525
                # merge the inventory and disk data together
1526
#                dirblock = [(relpath, basename, kind, stat, top_path, None, None, None) for relpath, basename, kind, stat, top_path in current_disk[1]]
1527
#                yield current_inv
1528
                dirblock = []
1529
                for relpath, subiterator in itertools.groupby(sorted(current_inv[1] + current_disk[1]), operator.itemgetter(1)):
1530
                    path_elements = list(subiterator)
1531
                    if len(path_elements) == 2:
1532
                        # versioned, present file
1533
                        dirblock.append((path_elements[0][0], path_elements[0][1], path_elements[1][2], path_elements[1][3], path_elements[0][4], path_elements[0][5], path_elements[0][6]))
1534
                    elif len(path_elements[0]) == 5:
1535
                        # unknown disk file
1536
                        dirblock.append((path_elements[0][0], path_elements[0][1], path_elements[0][2], path_elements[0][3], path_elements[0][4][top_strip_len:], None, None))
1537
                yield current_inv[0], dirblock
1538
                try:
1539
                    current_inv = inventory_iterator.next()
1540
                except StopIteration:
1541
                    inv_finished = True
1542
                try:
1543
                    current_disk = disk_iterator.next()
1544
                except StopIteration:
1545
                    disk_finished = True
1546
1547
        #for dirinfo, dirblock in self._walkdirs(prefix):
1548
        #    yield dirinfo, dirblock
1549
1550
    def _walkdirs(self, prefix=""):
1852.15.3 by Robert Collins
Add a first-cut Tree.walkdirs method.
1551
        _directory = 'directory'
1552
        pending = [('', '', _directory, None, '', None, None)]
1553
        inv = self.inventory
1554
        while pending:
1555
            dirblock = []
1556
            currentdir = pending.pop()
1557
            # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-toppath
1558
            top = currentdir[4]
1559
            if currentdir[0]:
1560
                relroot = currentdir[0] + '/'
1561
            else:
1562
                relroot = ""
1563
            # FIXME: stash the node in pending
1564
            entry = inv[inv.path2id(top)]
1565
            for name, child in entry.sorted_children():
1566
                toppath = relroot + name
1567
                dirblock.append((toppath, name, child.kind, None, toppath,
1568
                    child.file_id, child.kind
1569
                    ))
1570
            yield (currentdir[0], top, entry.file_id), dirblock
1571
            # push the user specified dirs from dirblock
1572
            for dir in reversed(dirblock):
1573
                if dir[2] == _directory:
1574
                    pending.append(dir)
1575
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1576
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.
1577
class WorkingTree2(WorkingTree):
1578
    """This is the Format 2 working tree.
1579
1580
    This was the first weave based working tree. 
1581
     - uses os locks for locking.
1582
     - uses the branch last-revision.
1583
    """
1584
1585
    def unlock(self):
1586
        # we share control files:
1587
        if self._hashcache.needs_write and self._control_files._lock_count==3:
1588
            self._hashcache.write()
1589
        # reverse order of locking.
1590
        try:
1591
            return self._control_files.unlock()
1592
        finally:
1593
            self.branch.unlock()
1594
1595
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1596
class WorkingTree3(WorkingTree):
1597
    """This is the Format 3 working tree.
1598
1599
    This differs from the base WorkingTree by:
1600
     - having its own file lock
1601
     - having its own last-revision property.
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
1602
1603
    This is new in bzr 0.8
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1604
    """
1605
1606
    @needs_read_lock
1607
    def last_revision(self):
1608
        """See WorkingTree.last_revision."""
1609
        try:
1610
            return self._control_files.get_utf8('last-revision').read()
1611
        except NoSuchFile:
1612
            return None
1613
1614
    def _change_last_revision(self, revision_id):
1615
        """See WorkingTree._change_last_revision."""
1616
        if revision_id is None or revision_id == NULL_REVISION:
1617
            try:
1618
                self._control_files._transport.delete('last-revision')
1619
            except errors.NoSuchFile:
1620
                pass
1621
            return False
1622
        else:
1623
            try:
1624
                self.branch.revision_history().index(revision_id)
1625
            except ValueError:
1626
                raise errors.NoSuchRevision(self.branch, revision_id)
1627
            self._control_files.put_utf8('last-revision', revision_id)
1628
            return True
1629
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
1630
    @needs_write_lock
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1631
    def set_conflicts(self, conflicts):
1632
        self._put_rio('conflicts', conflicts.to_stanzas(), 
1534.10.21 by Aaron Bentley
Moved and renamed conflict functions
1633
                      CONFLICT_HEADER_1)
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
1634
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
1635
    @needs_write_lock
1636
    def add_conflicts(self, new_conflicts):
1637
        conflict_set = set(self.conflicts())
1638
        conflict_set.update(set(list(new_conflicts)))
1639
        self.set_conflicts(ConflictList(sorted(conflict_set,
1640
                                               key=Conflict.sort_key)))
1641
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
1642
    @needs_read_lock
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1643
    def conflicts(self):
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
1644
        try:
1645
            confile = self._control_files.get('conflicts')
1646
        except NoSuchFile:
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1647
            return ConflictList()
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
1648
        try:
1649
            if confile.next() != CONFLICT_HEADER_1 + '\n':
1650
                raise ConflictFormatError()
1651
        except StopIteration:
1652
            raise ConflictFormatError()
1534.10.22 by Aaron Bentley
Got ConflictList implemented
1653
        return ConflictList.from_stanzas(RioReader(confile))
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
1654
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.
1655
    def unlock(self):
1656
        if self._hashcache.needs_write and self._control_files._lock_count==1:
1657
            self._hashcache.write()
1658
        # reverse order of locking.
1659
        try:
1660
            return self._control_files.unlock()
1661
        finally:
1662
            self.branch.unlock()
1663
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
1664
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
1665
def get_conflicted_stem(path):
1666
    for suffix in CONFLICT_SUFFIXES:
1667
        if path.endswith(suffix):
1668
            return path[:-len(suffix)]
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1669
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
1670
@deprecated_function(zero_eight)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1671
def is_control_file(filename):
1534.5.5 by Robert Collins
Move is_control_file into WorkingTree.is_control_filename and test.
1672
    """See WorkingTree.is_control_filename(filename)."""
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1673
    ## FIXME: better check
1674
    filename = normpath(filename)
1675
    while filename != '':
1676
        head, tail = os.path.split(filename)
1677
        ## 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.
1678
        if tail == '.bzr':
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1679
            return True
1680
        if filename == head:
1681
            break
1682
        filename = head
1683
    return False
1684
1685
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1686
class WorkingTreeFormat(object):
1687
    """An encapsulation of the initialization and open routines for a format.
1688
1689
    Formats provide three things:
1690
     * An initialization routine,
1691
     * a format string,
1692
     * an open routine.
1693
1694
    Formats are placed in an dict by their format string for reference 
1695
    during workingtree opening. Its not required that these be instances, they
1696
    can be classes themselves with class methods - it simply depends on 
1697
    whether state is needed for a given format or not.
1698
1699
    Once a format is deprecated, just deprecate the initialize and open
1700
    methods on the format class. Do not deprecate the object, as the 
1701
    object will be created every time regardless.
1702
    """
1703
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1704
    _default_format = None
1705
    """The default format used for new trees."""
1706
1707
    _formats = {}
1708
    """The known formats."""
1709
1710
    @classmethod
1711
    def find_format(klass, a_bzrdir):
1712
        """Return the format for the working tree object in a_bzrdir."""
1713
        try:
1714
            transport = a_bzrdir.get_workingtree_transport(None)
1715
            format_string = transport.get("format").read()
1716
            return klass._formats[format_string]
1717
        except NoSuchFile:
1508.1.19 by Robert Collins
Give format3 working trees their own last-revision marker.
1718
            raise errors.NoWorkingTree(base=transport.base)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1719
        except KeyError:
1740.5.6 by Martin Pool
Clean up many exception classes.
1720
            raise errors.UnknownFormatError(format=format_string)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1721
1722
    @classmethod
1723
    def get_default_format(klass):
1724
        """Return the current default format."""
1725
        return klass._default_format
1726
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1727
    def get_format_string(self):
1728
        """Return the ASCII format string that identifies this format."""
1729
        raise NotImplementedError(self.get_format_string)
1730
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1731
    def get_format_description(self):
1732
        """Return the short description for this format."""
1733
        raise NotImplementedError(self.get_format_description)
1734
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1735
    def is_supported(self):
1736
        """Is this format supported?
1737
1738
        Supported formats can be initialized and opened.
1739
        Unsupported formats may not support initialization or committing or 
1740
        some other features depending on the reason for not being supported.
1741
        """
1742
        return True
1743
1744
    @classmethod
1745
    def register_format(klass, format):
1746
        klass._formats[format.get_format_string()] = format
1747
1748
    @classmethod
1749
    def set_default_format(klass, format):
1750
        klass._default_format = format
1751
1752
    @classmethod
1753
    def unregister_format(klass, format):
1754
        assert klass._formats[format.get_format_string()] is format
1755
        del klass._formats[format.get_format_string()]
1756
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1757
1758
1759
class WorkingTreeFormat2(WorkingTreeFormat):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1760
    """The second working tree format. 
1761
1762
    This format modified the hash cache from the format 1 hash cache.
1763
    """
1764
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1765
    def get_format_description(self):
1766
        """See WorkingTreeFormat.get_format_description()."""
1767
        return "Working tree format 2"
1768
1692.7.9 by Martin Pool
Don't create broken standalone branches over sftp (Malone #43064)
1769
    def stub_initialize_remote(self, control_files):
1770
        """As a special workaround create critical control files for a remote working tree
1771
        
1772
        This ensures that it can later be updated and dealt with locally,
1773
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with 
1774
        no working tree.  (See bug #43064).
1775
        """
1776
        sio = StringIO()
1777
        inv = Inventory()
1778
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
1779
        sio.seek(0)
1780
        control_files.put('inventory', sio)
1781
1782
        control_files.put_utf8('pending-merges', '')
1783
        
1784
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
1785
    def initialize(self, a_bzrdir, revision_id=None):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1786
        """See WorkingTreeFormat.initialize()."""
1787
        if not isinstance(a_bzrdir.transport, LocalTransport):
1788
            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.
1789
        branch = a_bzrdir.open_branch()
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
1790
        if revision_id is not None:
1791
            branch.lock_write()
1792
            try:
1793
                revision_history = branch.revision_history()
1794
                try:
1795
                    position = revision_history.index(revision_id)
1796
                except ValueError:
1797
                    raise errors.NoSuchRevision(branch, revision_id)
1798
                branch.set_revision_history(revision_history[:position + 1])
1799
            finally:
1800
                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.
1801
        revision = branch.last_revision()
1534.7.165 by Aaron Bentley
Switched to build_tree instead of revert
1802
        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.
1803
        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.
1804
                         branch,
1805
                         inv,
1806
                         _internal=True,
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
1807
                         _format=self,
1808
                         _bzrdir=a_bzrdir)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1809
        wt._write_inventory(inv)
1810
        wt.set_root_id(inv.root.file_id)
1811
        wt.set_last_revision(revision)
1812
        wt.set_pending_merges([])
1534.7.165 by Aaron Bentley
Switched to build_tree instead of revert
1813
        build_tree(wt.basis_tree(), wt)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1814
        return wt
1815
1816
    def __init__(self):
1817
        super(WorkingTreeFormat2, self).__init__()
1818
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1819
1820
    def open(self, a_bzrdir, _found=False):
1821
        """Return the WorkingTree object for a_bzrdir
1822
1823
        _found is a private parameter, do not use it. It is used to indicate
1824
               if format probing has already been done.
1825
        """
1826
        if not _found:
1827
            # we are being called directly and must probe.
1828
            raise NotImplementedError
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1829
        if not isinstance(a_bzrdir.transport, LocalTransport):
1830
            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.
1831
        return WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
1832
                           _internal=True,
1833
                           _format=self,
1834
                           _bzrdir=a_bzrdir)
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1835
1836
1837
class WorkingTreeFormat3(WorkingTreeFormat):
1838
    """The second working tree format updated to record a format marker.
1839
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
1840
    This format:
1841
        - exists within a metadir controlling .bzr
1842
        - includes an explicit version marker for the workingtree control
1843
          files, separate from the BzrDir format
1844
        - modifies the hash cache format
1845
        - is new in bzr 0.8
1852.3.1 by Robert Collins
Trivial cleanups to workingtree.py
1846
        - uses a LockDir to guard access for writes.
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1847
    """
1848
1849
    def get_format_string(self):
1850
        """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
1851
        return "Bazaar-NG Working Tree format 3"
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1852
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
1853
    def get_format_description(self):
1854
        """See WorkingTreeFormat.get_format_description()."""
1855
        return "Working tree format 3"
1856
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
1857
    _lock_file_name = 'lock'
1858
    _lock_class = LockDir
1859
1860
    def _open_control_files(self, a_bzrdir):
1861
        transport = a_bzrdir.get_workingtree_transport(None)
1862
        return LockableFiles(transport, self._lock_file_name, 
1863
                             self._lock_class)
1864
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
1865
    def initialize(self, a_bzrdir, revision_id=None):
1866
        """See WorkingTreeFormat.initialize().
1867
        
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1868
        revision_id allows creating a working tree at a different
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
1869
        revision than the branch is at.
1870
        """
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1871
        if not isinstance(a_bzrdir.transport, LocalTransport):
1872
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1873
        transport = a_bzrdir.get_workingtree_transport(self)
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
1874
        control_files = self._open_control_files(a_bzrdir)
1875
        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.
1876
        control_files.lock_write()
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1877
        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.
1878
        branch = a_bzrdir.open_branch()
1508.1.21 by Robert Collins
Implement -r limit for checkout command.
1879
        if revision_id is None:
1880
            revision_id = branch.last_revision()
1534.7.165 by Aaron Bentley
Switched to build_tree instead of revert
1881
        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
1882
        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.
1883
                         branch,
1884
                         inv,
1885
                         _internal=True,
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
1886
                         _format=self,
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
1887
                         _bzrdir=a_bzrdir,
1888
                         _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.
1889
        wt.lock_write()
1890
        try:
1891
            wt._write_inventory(inv)
1892
            wt.set_root_id(inv.root.file_id)
1893
            wt.set_last_revision(revision_id)
1894
            wt.set_pending_merges([])
1895
            build_tree(wt.basis_tree(), wt)
1896
        finally:
1897
            wt.unlock()
1898
            control_files.unlock()
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1899
        return wt
1900
1901
    def __init__(self):
1902
        super(WorkingTreeFormat3, self).__init__()
1903
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1904
1905
    def open(self, a_bzrdir, _found=False):
1906
        """Return the WorkingTree object for a_bzrdir
1907
1908
        _found is a private parameter, do not use it. It is used to indicate
1909
               if format probing has already been done.
1910
        """
1911
        if not _found:
1912
            # we are being called directly and must probe.
1913
            raise NotImplementedError
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1914
        if not isinstance(a_bzrdir.transport, LocalTransport):
1915
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1852.3.1 by Robert Collins
Trivial cleanups to workingtree.py
1916
        return self._open(a_bzrdir, self._open_control_files(a_bzrdir))
1917
1918
    def _open(self, a_bzrdir, control_files):
1919
        """Open the tree itself.
1920
        
1921
        :param a_bzrdir: the dir for the tree.
1922
        :param control_files: the control files for the tree.
1923
        """
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
1924
        return WorkingTree3(a_bzrdir.root_transport.local_abspath('.'),
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
1925
                           _internal=True,
1926
                           _format=self,
1553.5.74 by Martin Pool
Convert WorkingTree format3 to use LockDirs
1927
                           _bzrdir=a_bzrdir,
1928
                           _control_files=control_files)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1929
1534.5.1 by Robert Collins
Give info some reasonable output and tests.
1930
    def __str__(self):
1931
        return self.get_format_string()
1932
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1933
1934
# formats which have no format string are not discoverable
1935
# and not independently creatable, so are not registered.
1936
__default_format = WorkingTreeFormat3()
1937
WorkingTreeFormat.register_format(__default_format)
1938
WorkingTreeFormat.set_default_format(__default_format)
1939
_legacy_formats = [WorkingTreeFormat2(),
1940
                   ]
1941
1942
1943
class WorkingTreeTestProviderAdapter(object):
1944
    """A tool to generate a suite testing multiple workingtree formats at once.
1945
1946
    This is done by copying the test once for each transport and injecting
1947
    the transport_server, transport_readonly_server, and workingtree_format
1948
    classes into each copy. Each copy is also given a new id() to make it
1949
    easy to identify.
1950
    """
1951
1952
    def __init__(self, transport_server, transport_readonly_server, formats):
1953
        self._transport_server = transport_server
1954
        self._transport_readonly_server = transport_readonly_server
1955
        self._formats = formats
1956
    
1852.6.1 by Robert Collins
Start tree implementation tests.
1957
    def _clone_test(self, test, bzrdir_format, workingtree_format, variation):
1958
        """Clone test for adaption."""
1959
        new_test = deepcopy(test)
1960
        new_test.transport_server = self._transport_server
1961
        new_test.transport_readonly_server = self._transport_readonly_server
1962
        new_test.bzrdir_format = bzrdir_format
1963
        new_test.workingtree_format = workingtree_format
1964
        def make_new_test_id():
1965
            new_id = "%s(%s)" % (test.id(), variation)
1966
            return lambda: new_id
1967
        new_test.id = make_new_test_id()
1968
        return new_test
1969
    
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1970
    def adapt(self, test):
1971
        from bzrlib.tests import TestSuite
1972
        result = TestSuite()
1973
        for workingtree_format, bzrdir_format in self._formats:
1852.6.1 by Robert Collins
Start tree implementation tests.
1974
            new_test = self._clone_test(
1975
                test,
1976
                bzrdir_format,
1977
                workingtree_format, workingtree_format.__class__.__name__)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1978
            result.addTest(new_test)
1979
        return result