/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
453 by Martin Pool
- Split WorkingTree into its own file
1
# Copyright (C) 2005 Canonical Ltd
2
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
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
32
956 by Martin Pool
doc
33
# FIXME: I don't know if writing out the cache from the destructor is really a
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
34
# good idea, because destructors are considered poor taste in Python, and it's
35
# not predictable when it will be written out.
36
37
# TODO: Give the workingtree sole responsibility for the working inventory;
38
# remove the variable and references to it from the branch.  This may require
39
# updating the commit code so as to update the inventory within the working
40
# copy, and making sure there's only one WorkingTree for any directory on disk.
41
# At the momenthey may alias the inventory and have old copies of it in memory.
956 by Martin Pool
doc
42
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
43
from copy import deepcopy
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
44
from cStringIO import StringIO
45
import errno
46
import fnmatch
453 by Martin Pool
- Split WorkingTree into its own file
47
import os
1398 by Robert Collins
integrate in Gustavos x-bit patch
48
import stat
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
49
 
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
50
51
from bzrlib.atomicfile import AtomicFile
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
52
from bzrlib.branch import (Branch,
53
                           quotefn)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
54
import bzrlib.bzrdir as bzrdir
1534.4.28 by Robert Collins
first cut at merge from integration.
55
from bzrlib.decorators import needs_read_lock, needs_write_lock
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
56
import bzrlib.errors as errors
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
57
from bzrlib.errors import (BzrCheckError,
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
58
                           BzrError,
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
59
                           DivergedBranches,
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
60
                           WeaveRevisionNotPresent,
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
61
                           NotBranchError,
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
62
                           NoSuchFile,
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
63
                           NotVersionedError)
64
from bzrlib.inventory import InventoryEntry
1534.4.28 by Robert Collins
first cut at merge from integration.
65
from bzrlib.lockable_files import LockableFiles
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.
66
from bzrlib.merge import merge_inner, transform_tree
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
67
from bzrlib.osutils import (appendpath,
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
68
                            compact_date,
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
69
                            file_kind,
70
                            isdir,
1185.31.39 by John Arbash Meinel
Replacing os.getcwdu() with osutils.getcwd(),
71
                            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 \
72
                            pathjoin,
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
73
                            pumpfile,
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
74
                            safe_unicode,
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
75
                            splitpath,
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
76
                            rand_bytes,
1185.31.37 by John Arbash Meinel
Switched os.path.abspath and os.path.realpath to osutils.* (still passes on cygwin)
77
                            abspath,
1185.31.38 by John Arbash Meinel
Changing os.path.normpath to osutils.normpath
78
                            normpath,
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
79
                            realpath,
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
80
                            relpath,
81
                            rename)
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.
82
from bzrlib.symbol_versioning import *
1185.33.92 by Martin Pool
[patch] fix for 'bzr rm -v' (Wouter van Heyst)
83
from bzrlib.textui import show_status
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
84
import bzrlib.tree
1140 by Martin Pool
- lift out import statements within WorkingTree
85
from bzrlib.trace import mutter
1534.4.28 by Robert Collins
first cut at merge from integration.
86
from bzrlib.transport import get_transport
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
87
from bzrlib.transport.local import LocalTransport
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
88
import bzrlib.xml5
453 by Martin Pool
- Split WorkingTree into its own file
89
1465 by Robert Collins
Bugfix the new pull --clobber to not generate spurious conflicts.
90
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
91
def gen_file_id(name):
92
    """Return new file id.
93
94
    This should probably generate proper UUIDs, but for the moment we
95
    cope with just randomness because running uuidgen every time is
96
    slow."""
97
    import re
98
    from binascii import hexlify
99
    from time import time
100
101
    # get last component
102
    idx = name.rfind('/')
103
    if idx != -1:
104
        name = name[idx+1 : ]
105
    idx = name.rfind('\\')
106
    if idx != -1:
107
        name = name[idx+1 : ]
108
109
    # make it not a hidden file
110
    name = name.lstrip('.')
111
112
    # remove any wierd characters; we don't escape them but rather
113
    # just pull them out
114
    name = re.sub(r'[^\w.]', '', name)
115
116
    s = hexlify(rand_bytes(8))
117
    return '-'.join((name, compact_date(time()), s))
118
119
120
def gen_root_id():
121
    """Return a new tree-root file id."""
122
    return gen_file_id('TREE_ROOT')
123
124
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
125
class TreeEntry(object):
126
    """An entry that implements the minium interface used by commands.
127
128
    This needs further inspection, it may be better to have 
129
    InventoryEntries without ids - though that seems wrong. For now,
130
    this is a parallel hierarchy to InventoryEntry, and needs to become
131
    one of several things: decorates to that hierarchy, children of, or
132
    parents of it.
1399.1.3 by Robert Collins
move change detection for text and metadata from delta to entry.detect_changes
133
    Another note is that these objects are currently only used when there is
134
    no InventoryEntry available - i.e. for unversioned objects.
135
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
136
    """
137
 
138
    def __eq__(self, other):
139
        # yes, this us ugly, TODO: best practice __eq__ style.
140
        return (isinstance(other, TreeEntry)
141
                and other.__class__ == self.__class__)
142
 
143
    def kind_character(self):
144
        return "???"
145
146
147
class TreeDirectory(TreeEntry):
148
    """See TreeEntry. This is a directory in a working tree."""
149
150
    def __eq__(self, other):
151
        return (isinstance(other, TreeDirectory)
152
                and other.__class__ == self.__class__)
153
154
    def kind_character(self):
155
        return "/"
156
157
158
class TreeFile(TreeEntry):
159
    """See TreeEntry. This is a regular file in a working tree."""
160
161
    def __eq__(self, other):
162
        return (isinstance(other, TreeFile)
163
                and other.__class__ == self.__class__)
164
165
    def kind_character(self):
166
        return ''
167
168
169
class TreeLink(TreeEntry):
170
    """See TreeEntry. This is a symlink in a working tree."""
171
172
    def __eq__(self, other):
173
        return (isinstance(other, TreeLink)
174
                and other.__class__ == self.__class__)
175
176
    def kind_character(self):
177
        return ''
178
179
453 by Martin Pool
- Split WorkingTree into its own file
180
class WorkingTree(bzrlib.tree.Tree):
181
    """Working copy tree.
182
183
    The inventory is held in the `Branch` working-inventory, and the
184
    files are in a directory on disk.
185
186
    It is possible for a `WorkingTree` to have a filename which is
187
    not listed in the Inventory and vice versa.
188
    """
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
189
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
190
    def __init__(self, basedir='.',
191
                 branch=None,
192
                 _inventory=None,
193
                 _control_files=None,
194
                 _internal=False,
195
                 _format=None,
196
                 _bzrdir=None):
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
197
        """Construct a WorkingTree for basedir.
198
199
        If the branch is not supplied, it is opened automatically.
200
        If the branch is supplied, it must be the branch for this basedir.
201
        (branch.base is not cross checked, because for remote branches that
202
        would be meaningless).
203
        """
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.
204
        self._format = _format
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
205
        self.bzrdir = _bzrdir
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
206
        if not _internal:
207
            # created via open etc.
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.
208
            wt = WorkingTree.open(basedir)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
209
            self.branch = wt.branch
210
            self.basedir = wt.basedir
211
            self._control_files = wt._control_files
212
            self._hashcache = wt._hashcache
213
            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.
214
            self._format = wt._format
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
215
            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.
216
        from bzrlib.hashcache import HashCache
217
        from bzrlib.trace import note, mutter
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
218
        assert isinstance(basedir, basestring), \
219
            "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.
220
        basedir = safe_unicode(basedir)
1534.4.28 by Robert Collins
first cut at merge from integration.
221
        mutter("openeing working tree %r", basedir)
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
222
        if branch is None:
223
            branch = Branch.open(basedir)
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
224
        assert isinstance(branch, Branch), \
225
            "branch %r is not a Branch" % branch
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
226
        self.branch = branch
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
227
        self.basedir = realpath(basedir)
1534.4.28 by Robert Collins
first cut at merge from integration.
228
        # 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.
229
        if isinstance(self._format, WorkingTreeFormat2):
230
            # share control object
1534.4.28 by Robert Collins
first cut at merge from integration.
231
            self._control_files = self.branch.control_files
232
        elif _control_files is not None:
233
            assert False, "not done yet"
234
#            self._control_files = _control_files
235
        else:
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
236
            # only ready for format 3
237
            assert isinstance(self._format, WorkingTreeFormat3)
1534.4.28 by Robert Collins
first cut at merge from integration.
238
            self._control_files = LockableFiles(
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
239
                self.bzrdir.get_workingtree_transport(None),
240
                'lock')
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
241
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.
242
        # update the whole cache up front and write to disk if anything changed;
243
        # in the future we might want to do this more selectively
1467 by Robert Collins
WorkingTree.__del__ has been removed.
244
        # two possible ways offer themselves : in self._unlock, write the cache
245
        # if needed, or, when the cache sees a change, append it to the hash
246
        # cache file, and have the parser take the most recent entry for a
247
        # given path only.
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
248
        cache_filename = self.bzrdir.get_workingtree_transport(None).abspath('stat-cache')
249
        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.
250
        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.
251
        # is this scan needed ? it makes things kinda slow.
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
252
        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.
253
254
        if hc.needs_write:
255
            mutter("write hc")
256
            hc.write()
453 by Martin Pool
- Split WorkingTree into its own file
257
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
258
        if _inventory is None:
259
            self._set_inventory(self.read_working_inventory())
260
        else:
261
            self._set_inventory(_inventory)
1185.60.6 by Aaron Bentley
Fixed hashcache
262
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
263
    def _set_inventory(self, inv):
264
        self._inventory = inv
265
        self.path2id = self._inventory.path2id
266
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
267
    @staticmethod
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
268
    def open(path=None, _unsupported=False):
269
        """Open an existing working tree at path.
270
271
        """
272
        if path is None:
273
            path = os.path.getcwdu()
274
        control = bzrdir.BzrDir.open(path, _unsupported)
275
        return control.open_workingtree(_unsupported)
276
        
277
    @staticmethod
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
278
    def open_containing(path=None):
279
        """Open an existing working tree which has its root about path.
280
        
281
        This probes for a working tree at path and searches upwards from there.
282
283
        Basically we keep looking up until we find the control directory or
284
        run into /.  If there isn't one, raises NotBranchError.
285
        TODO: give this a new exception.
286
        If there is one, it is returned, along with the unused portion of path.
287
        """
288
        if path is None:
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
289
            path = os.getcwdu()
290
        control, relpath = bzrdir.BzrDir.open_containing(path)
291
        return control.open_workingtree(), relpath
292
293
    @staticmethod
294
    def open_downlevel(path=None):
295
        """Open an unsupported working tree.
296
297
        Only intended for advanced situations like upgrading part of a bzrdir.
298
        """
299
        return WorkingTree.open(path, _unsupported=True)
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
300
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
301
    def __iter__(self):
302
        """Iterate through file_ids for this tree.
303
304
        file_ids are in a WorkingTree if they are in the working inventory
305
        and the working file exists.
306
        """
307
        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.
308
        for path, ie in inv.iter_entries():
1092.2.6 by Robert Collins
symlink support updated to work
309
            if bzrlib.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.
310
                yield ie.file_id
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
311
453 by Martin Pool
- Split WorkingTree into its own file
312
    def __repr__(self):
313
        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
314
                               getattr(self, 'basedir', None))
453 by Martin Pool
- Split WorkingTree into its own file
315
316
    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 \
317
        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()
318
    
319
    def basis_tree(self):
320
        """Return RevisionTree for the current last revision."""
321
        revision_id = self.last_revision()
322
        if revision_id is not None:
323
            try:
324
                xml = self.read_basis_inventory(revision_id)
325
                inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
326
                return bzrlib.tree.RevisionTree(self.branch.repository, inv,
327
                                                revision_id)
328
            except NoSuchFile:
329
                pass
330
        return self.branch.repository.revision_tree(revision_id)
453 by Martin Pool
- Split WorkingTree into its own file
331
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
332
    @staticmethod
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
333
    @deprecated_method(zero_eight)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
334
    def create(branch, directory):
335
        """Create a workingtree for branch at directory.
336
337
        If existing_directory already exists it must have a .bzr directory.
338
        If it does not exist, it will be created.
339
340
        This returns a new WorkingTree object for the new checkout.
341
342
        TODO FIXME RBC 20060124 when we have checkout formats in place this
343
        should accept an optional revisionid to checkout [and reject this if
344
        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
345
346
        XXX: When BzrDir is present, these should be created through that 
347
        interface instead.
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
348
        """
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
349
        warn('delete WorkingTree.create', stacklevel=3)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
350
        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.
351
        if branch.bzrdir.root_transport.base == transport.base:
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
352
            # same dir 
353
            return branch.bzrdir.create_workingtree()
354
        # different directory, 
355
        # create a branch reference
356
        # and now a working tree.
357
        raise NotImplementedError
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
358
 
359
    @staticmethod
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
360
    @deprecated_method(zero_eight)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
361
    def create_standalone(directory):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
362
        """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.
363
364
        Directory must exist and be empty.
1551.1.2 by Martin Pool
Deprecation warnings for popular APIs that will change in BzrDir
365
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
366
        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.
367
        """
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
368
        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.
369
1185.31.37 by John Arbash Meinel
Switched os.path.abspath and os.path.realpath to osutils.* (still passes on cygwin)
370
    def relpath(self, abs):
1457.1.3 by Robert Collins
make Branch.relpath delegate to the working tree.
371
        """Return the local path portion from a given absolute path."""
1185.31.37 by John Arbash Meinel
Switched os.path.abspath and os.path.realpath to osutils.* (still passes on cygwin)
372
        return relpath(self.basedir, abs)
1457.1.3 by Robert Collins
make Branch.relpath delegate to the working tree.
373
453 by Martin Pool
- Split WorkingTree into its own file
374
    def has_filename(self, filename):
1092.2.6 by Robert Collins
symlink support updated to work
375
        return bzrlib.osutils.lexists(self.abspath(filename))
453 by Martin Pool
- Split WorkingTree into its own file
376
377
    def get_file(self, file_id):
378
        return self.get_file_byname(self.id2path(file_id))
379
380
    def get_file_byname(self, filename):
381
        return file(self.abspath(filename), 'rb')
382
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
383
    def get_root_id(self):
384
        """Return the id of this trees root"""
385
        inv = self.read_working_inventory()
386
        return inv.root.file_id
387
        
453 by Martin Pool
- Split WorkingTree into its own file
388
    def _get_store_filename(self, file_id):
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
389
        ## XXX: badly named; this is not in the store at all
453 by Martin Pool
- Split WorkingTree into its own file
390
        return self.abspath(self.id2path(file_id))
391
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
392
    @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.
393
    def clone(self, to_bzrdir, revision_id=None, basis=None):
394
        """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()
395
        
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.
396
        Specifically modified files are kept as modified, but
397
        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()
398
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.
399
        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()
400
401
        revision
402
            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.
403
            revision, and and difference between the source trees last revision
404
            and this one merged in.
405
406
        basis
407
            If not None, a closer copy of a tree which may have some files in
408
            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()
409
        """
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.
410
        # assumes the target bzr dir format is compatible.
411
        result = self._format.initialize(to_bzrdir)
412
        self.copy_content_into(result, revision_id)
413
        return result
414
415
    @needs_read_lock
416
    def copy_content_into(self, tree, revision_id=None):
417
        """Copy the current content and user files of this tree into tree."""
418
        if revision_id is None:
419
            transform_tree(tree, self)
420
        else:
421
            # TODO now merge from tree.last_revision to revision
422
            transform_tree(tree, self)
423
            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()
424
1457.1.17 by Robert Collins
Branch.commit() has moved to WorkingTree.commit(). (Robert Collins)
425
    @needs_write_lock
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.
426
    def commit(self, *args, **kwargs):
1457.1.17 by Robert Collins
Branch.commit() has moved to WorkingTree.commit(). (Robert Collins)
427
        from bzrlib.commit import Commit
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.
428
        # args for wt.commit start at message from the Commit.commit method,
429
        # but with branch a kwarg now, passing in args as is results in the
430
        #message being used for the branch
1534.4.32 by Robert Collins
Rename deprecated_nonce to DEPRECATED_PARAMETER
431
        args = (DEPRECATED_PARAMETER, ) + args
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.
432
        Commit().commit(working_tree=self, *args, **kwargs)
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
433
        self._set_inventory(self.read_working_inventory())
1248 by Martin Pool
- new weave based cleanup [broken]
434
435
    def id2abspath(self, file_id):
436
        return self.abspath(self.id2path(file_id))
437
1185.12.39 by abentley
Propogated has_or_had_id to Tree
438
    def has_id(self, file_id):
453 by Martin Pool
- Split WorkingTree into its own file
439
        # files that have been deleted are excluded
1185.12.39 by abentley
Propogated has_or_had_id to Tree
440
        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.
441
        if not inv.has_id(file_id):
453 by Martin Pool
- Split WorkingTree into its own file
442
            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.
443
        path = inv.id2path(file_id)
1092.2.6 by Robert Collins
symlink support updated to work
444
        return bzrlib.osutils.lexists(self.abspath(path))
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
445
1185.12.39 by abentley
Propogated has_or_had_id to Tree
446
    def has_or_had_id(self, file_id):
447
        if file_id == self.inventory.root.file_id:
448
            return True
449
        return self.inventory.has_id(file_id)
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
450
451
    __contains__ = has_id
452
453 by Martin Pool
- Split WorkingTree into its own file
453
    def get_file_size(self, file_id):
1248 by Martin Pool
- new weave based cleanup [broken]
454
        return os.path.getsize(self.id2abspath(file_id))
453 by Martin Pool
- Split WorkingTree into its own file
455
1185.60.6 by Aaron Bentley
Fixed hashcache
456
    @needs_read_lock
453 by Martin Pool
- Split WorkingTree into its own file
457
    def get_file_sha1(self, 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.
458
        path = self._inventory.id2path(file_id)
459
        return self._hashcache.get_sha1(path)
453 by Martin Pool
- Split WorkingTree into its own file
460
1398 by Robert Collins
integrate in Gustavos x-bit patch
461
    def is_executable(self, file_id):
462
        if os.name == "nt":
463
            return self._inventory[file_id].executable
464
        else:
465
            path = self._inventory.id2path(file_id)
466
            mode = os.lstat(self.abspath(path)).st_mode
467
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
468
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
469
    @needs_write_lock
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
470
    def add(self, files, ids=None):
471
        """Make files versioned.
472
473
        Note that the command line normally calls smart_add instead,
474
        which can automatically recurse.
475
476
        This adds the files to the inventory, so that they will be
477
        recorded by the next commit.
478
479
        files
480
            List of paths to add, relative to the base of the tree.
481
482
        ids
483
            If set, use these instead of automatically generated ids.
484
            Must be the same length as the list of files, but may
485
            contain None for ids that are to be autogenerated.
486
487
        TODO: Perhaps have an option to add the ids even if the files do
488
              not (yet) exist.
489
490
        TODO: Perhaps callback with the ids and paths as they're added.
491
        """
492
        # TODO: Re-adding a file that is removed in the working copy
493
        # should probably put it back with the previous ID.
494
        if isinstance(files, basestring):
495
            assert(ids is None or isinstance(ids, basestring))
496
            files = [files]
497
            if ids is not None:
498
                ids = [ids]
499
500
        if ids is None:
501
            ids = [None] * len(files)
502
        else:
503
            assert(len(ids) == len(files))
504
505
        inv = self.read_working_inventory()
506
        for f,file_id in zip(files, ids):
507
            if is_control_file(f):
508
                raise BzrError("cannot add control file %s" % quotefn(f))
509
510
            fp = splitpath(f)
511
512
            if len(fp) == 0:
513
                raise BzrError("cannot add top-level %r" % f)
514
1185.31.38 by John Arbash Meinel
Changing os.path.normpath to osutils.normpath
515
            fullpath = normpath(self.abspath(f))
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
516
517
            try:
518
                kind = file_kind(fullpath)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
519
            except OSError, e:
520
                if e.errno == errno.ENOENT:
521
                    raise NoSuchFile(fullpath)
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
522
                # maybe something better?
523
                raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
524
525
            if not InventoryEntry.versionable_kind(kind):
526
                raise BzrError('cannot add: not a versionable file ('
527
                               'i.e. regular file, symlink or directory): %s' % quotefn(f))
528
529
            if file_id is None:
530
                file_id = gen_file_id(f)
531
            inv.add_path(f, kind=kind, file_id=file_id)
532
533
            mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
534
        self._write_inventory(inv)
535
536
    @needs_write_lock
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
537
    def add_pending_merge(self, *revision_ids):
538
        # TODO: Perhaps should check at this point that the
539
        # history of the revision is actually present?
540
        p = self.pending_merges()
541
        updated = False
542
        for rev_id in revision_ids:
543
            if rev_id in p:
544
                continue
545
            p.append(rev_id)
546
            updated = True
547
        if updated:
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
548
            self.set_pending_merges(p)
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
549
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
550
    @needs_read_lock
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
551
    def pending_merges(self):
552
        """Return a list of pending merges.
553
554
        These are revisions that have been merged into the working
555
        directory but not yet committed.
556
        """
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
557
        try:
1534.4.28 by Robert Collins
first cut at merge from integration.
558
            merges_file = self._control_files.get_utf8('pending-merges')
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
559
        except OSError, e:
560
            if e.errno != errno.ENOENT:
561
                raise
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
562
            return []
563
        p = []
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
564
        for l in merges_file.readlines():
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
565
            p.append(l.rstrip('\n'))
566
        return p
567
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
568
    @needs_write_lock
569
    def set_pending_merges(self, rev_list):
1534.4.28 by Robert Collins
first cut at merge from integration.
570
        self._control_files.put_utf8('pending-merges', '\n'.join(rev_list))
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
571
1092.2.6 by Robert Collins
symlink support updated to work
572
    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
573
        return os.readlink(self.id2abspath(file_id))
453 by Martin Pool
- Split WorkingTree into its own file
574
575
    def file_class(self, filename):
576
        if self.path2id(filename):
577
            return 'V'
578
        elif self.is_ignored(filename):
579
            return 'I'
580
        else:
581
            return '?'
582
583
    def list_files(self):
584
        """Recursively list all files as (path, class, kind, id).
585
586
        Lists, but does not descend into unversioned directories.
587
588
        This does not include files that have been deleted in this
589
        tree.
590
591
        Skips the control directory.
592
        """
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.
593
        inv = self._inventory
453 by Martin Pool
- Split WorkingTree into its own file
594
595
        def descend(from_dir_relpath, from_dir_id, dp):
596
            ls = os.listdir(dp)
597
            ls.sort()
598
            for f in ls:
599
                ## TODO: If we find a subdirectory with its own .bzr
600
                ## directory, then that is a separate tree and we
601
                ## should exclude it.
602
                if bzrlib.BZRDIR == f:
603
                    continue
604
605
                # path within tree
606
                fp = appendpath(from_dir_relpath, f)
607
608
                # absolute path
609
                fap = appendpath(dp, f)
610
                
611
                f_ie = inv.get_child(from_dir_id, f)
612
                if f_ie:
613
                    c = 'V'
614
                elif self.is_ignored(fp):
615
                    c = 'I'
616
                else:
617
                    c = '?'
618
619
                fk = file_kind(fap)
620
621
                if f_ie:
622
                    if f_ie.kind != fk:
623
                        raise BzrCheckError("file %r entered as kind %r id %r, "
624
                                            "now of kind %r"
625
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
626
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
627
                # make a last minute entry
628
                if f_ie:
629
                    entry = f_ie
630
                else:
631
                    if fk == 'directory':
632
                        entry = TreeDirectory()
633
                    elif fk == 'file':
634
                        entry = TreeFile()
635
                    elif fk == 'symlink':
636
                        entry = TreeLink()
637
                    else:
638
                        entry = TreeEntry()
639
                
640
                yield fp, c, fk, (f_ie and f_ie.file_id), entry
453 by Martin Pool
- Split WorkingTree into its own file
641
642
                if fk != 'directory':
643
                    continue
644
645
                if c != 'V':
646
                    # don't descend unversioned directories
647
                    continue
648
                
649
                for ff in descend(fp, f_ie.file_id, fap):
650
                    yield ff
651
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
652
        for f in descend(u'', inv.root.file_id, self.basedir):
453 by Martin Pool
- Split WorkingTree into its own file
653
            yield f
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
654
655
    @needs_write_lock
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
656
    def move(self, from_paths, to_name):
657
        """Rename files.
658
659
        to_name must exist in the inventory.
660
661
        If to_name exists and is a directory, the files are moved into
662
        it, keeping their old names.  
663
664
        Note that to_name is only the last component of the new name;
665
        this doesn't change the directory.
666
667
        This returns a list of (from_path, to_path) pairs for each
668
        entry that is moved.
669
        """
670
        result = []
671
        ## TODO: Option to move IDs only
672
        assert not isinstance(from_paths, basestring)
673
        inv = self.inventory
674
        to_abs = self.abspath(to_name)
675
        if not isdir(to_abs):
676
            raise BzrError("destination %r is not a directory" % to_abs)
677
        if not self.has_filename(to_name):
678
            raise BzrError("destination %r not in working directory" % to_abs)
679
        to_dir_id = inv.path2id(to_name)
680
        if to_dir_id == None and to_name != '':
681
            raise BzrError("destination %r is not a versioned directory" % to_name)
682
        to_dir_ie = inv[to_dir_id]
683
        if to_dir_ie.kind not in ('directory', 'root_directory'):
684
            raise BzrError("destination %r is not a directory" % to_abs)
685
686
        to_idpath = inv.get_idpath(to_dir_id)
687
688
        for f in from_paths:
689
            if not self.has_filename(f):
690
                raise BzrError("%r does not exist in working tree" % f)
691
            f_id = inv.path2id(f)
692
            if f_id == None:
693
                raise BzrError("%r is not versioned" % f)
694
            name_tail = splitpath(f)[-1]
695
            dest_path = appendpath(to_name, name_tail)
696
            if self.has_filename(dest_path):
697
                raise BzrError("destination %r already exists" % dest_path)
698
            if f_id in to_idpath:
699
                raise BzrError("can't move %r to a subdirectory of itself" % f)
700
701
        # OK, so there's a race here, it's possible that someone will
702
        # create a file in this interval and then the rename might be
703
        # left half-done.  But we should have caught most problems.
704
        orig_inv = deepcopy(self.inventory)
705
        try:
706
            for f in from_paths:
707
                name_tail = splitpath(f)[-1]
708
                dest_path = appendpath(to_name, name_tail)
709
                result.append((f, dest_path))
710
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
711
                try:
712
                    rename(self.abspath(f), self.abspath(dest_path))
713
                except OSError, e:
714
                    raise BzrError("failed to rename %r to %r: %s" %
715
                                   (f, dest_path, e[1]),
716
                            ["rename rolled back"])
717
        except:
718
            # restore the inventory on error
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
719
            self._set_inventory(orig_inv)
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
720
            raise
721
        self._write_inventory(inv)
722
        return result
723
724
    @needs_write_lock
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
725
    def rename_one(self, from_rel, to_rel):
726
        """Rename one file.
727
728
        This can change the directory or the filename or both.
729
        """
730
        inv = self.inventory
731
        if not self.has_filename(from_rel):
732
            raise BzrError("can't rename: old working file %r does not exist" % from_rel)
733
        if self.has_filename(to_rel):
734
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
735
736
        file_id = inv.path2id(from_rel)
737
        if file_id == None:
738
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
739
740
        entry = inv[file_id]
741
        from_parent = entry.parent_id
742
        from_name = entry.name
743
        
744
        if inv.path2id(to_rel):
745
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
746
747
        to_dir, to_tail = os.path.split(to_rel)
748
        to_dir_id = inv.path2id(to_dir)
749
        if to_dir_id == None and to_dir != '':
750
            raise BzrError("can't determine destination directory id for %r" % to_dir)
751
752
        mutter("rename_one:")
753
        mutter("  file_id    {%s}" % file_id)
754
        mutter("  from_rel   %r" % from_rel)
755
        mutter("  to_rel     %r" % to_rel)
756
        mutter("  to_dir     %r" % to_dir)
757
        mutter("  to_dir_id  {%s}" % to_dir_id)
758
759
        inv.rename(file_id, to_dir_id, to_tail)
760
761
        from_abs = self.abspath(from_rel)
762
        to_abs = self.abspath(to_rel)
763
        try:
764
            rename(from_abs, to_abs)
765
        except OSError, e:
766
            inv.rename(file_id, from_parent, from_name)
767
            raise BzrError("failed to rename %r to %r: %s"
768
                    % (from_abs, to_abs, e[1]),
769
                    ["rename rolled back"])
770
        self._write_inventory(inv)
771
772
    @needs_read_lock
453 by Martin Pool
- Split WorkingTree into its own file
773
    def unknowns(self):
1508.1.6 by Robert Collins
Move Branch.unknowns() to WorkingTree.
774
        """Return all unknown files.
775
776
        These are files in the working directory that are not versioned or
777
        control files or ignored.
778
        
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
779
        >>> from bzrlib.bzrdir import ScratchDir
780
        >>> d = ScratchDir(files=['foo', 'foo~'])
781
        >>> b = d.open_branch()
1508.1.6 by Robert Collins
Move Branch.unknowns() to WorkingTree.
782
        >>> tree = WorkingTree(b.base, b)
783
        >>> map(str, tree.unknowns())
784
        ['foo']
785
        >>> tree.add('foo')
786
        >>> list(b.unknowns())
787
        []
788
        >>> tree.remove('foo')
789
        >>> list(b.unknowns())
790
        [u'foo']
791
        """
453 by Martin Pool
- Split WorkingTree into its own file
792
        for subp in self.extras():
793
            if not self.is_ignored(subp):
794
                yield subp
795
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
796
    def iter_conflicts(self):
797
        conflicted = set()
798
        for path in (s[0] for s in self.list_files()):
799
            stem = get_conflicted_stem(path)
800
            if stem is None:
801
                continue
802
            if stem not in conflicted:
803
                conflicted.add(stem)
804
                yield stem
453 by Martin Pool
- Split WorkingTree into its own file
805
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
806
    @needs_write_lock
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
807
    def pull(self, source, overwrite=False):
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
808
        source.lock_read()
809
        try:
810
            old_revision_history = self.branch.revision_history()
1185.33.44 by Martin Pool
[patch] show number of revisions pushed/pulled/merged (Robey Pointer)
811
            count = self.branch.pull(source, overwrite)
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
812
            new_revision_history = self.branch.revision_history()
813
            if new_revision_history != old_revision_history:
1465 by Robert Collins
Bugfix the new pull --clobber to not generate spurious conflicts.
814
                if len(old_revision_history):
815
                    other_revision = old_revision_history[-1]
816
                else:
817
                    other_revision = None
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
818
                repository = self.branch.repository
1465 by Robert Collins
Bugfix the new pull --clobber to not generate spurious conflicts.
819
                merge_inner(self.branch,
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
820
                            self.basis_tree(), 
1534.4.28 by Robert Collins
first cut at merge from integration.
821
                            repository.revision_tree(other_revision),
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
822
                            this_tree=self)
823
                self.set_last_revision(self.branch.last_revision())
1185.33.44 by Martin Pool
[patch] show number of revisions pushed/pulled/merged (Robey Pointer)
824
            return count
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
825
        finally:
826
            source.unlock()
827
453 by Martin Pool
- Split WorkingTree into its own file
828
    def extras(self):
829
        """Yield all unknown files in this WorkingTree.
830
831
        If there are any unknown directories then only the directory is
832
        returned, not all its children.  But if there are unknown files
833
        under a versioned subdirectory, they are returned.
834
835
        Currently returned depth-first, sorted by name within directories.
836
        """
837
        ## TODO: Work from given directory downwards
838
        for path, dir_entry in self.inventory.directories():
1185.31.4 by John Arbash Meinel
Fixing mutter() calls to not have to do string processing.
839
            mutter("search for unknowns in %r", path)
453 by Martin Pool
- Split WorkingTree into its own file
840
            dirabs = self.abspath(path)
841
            if not isdir(dirabs):
842
                # e.g. directory deleted
843
                continue
844
845
            fl = []
846
            for subf in os.listdir(dirabs):
847
                if (subf != '.bzr'
848
                    and (subf not in dir_entry.children)):
849
                    fl.append(subf)
850
            
851
            fl.sort()
852
            for subf in fl:
853
                subp = appendpath(path, subf)
854
                yield subp
855
856
857
    def ignored_files(self):
858
        """Yield list of PATH, IGNORE_PATTERN"""
859
        for subp in self.extras():
860
            pat = self.is_ignored(subp)
861
            if pat != None:
862
                yield subp, pat
863
864
865
    def get_ignore_list(self):
866
        """Return list of ignore patterns.
867
868
        Cached in the Tree object after the first call.
869
        """
870
        if hasattr(self, '_ignorelist'):
871
            return self._ignorelist
872
873
        l = bzrlib.DEFAULT_IGNORE[:]
874
        if self.has_filename(bzrlib.IGNORE_FILENAME):
875
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
876
            l.extend([line.rstrip("\n\r") for line in f.readlines()])
877
        self._ignorelist = l
878
        return l
879
880
881
    def is_ignored(self, filename):
882
        r"""Check whether the filename matches an ignore pattern.
883
884
        Patterns containing '/' or '\' need to match the whole path;
885
        others match against only the last component.
886
887
        If the file is ignored, returns the pattern which caused it to
888
        be ignored, otherwise None.  So this can simply be used as a
889
        boolean if desired."""
890
891
        # TODO: Use '**' to match directories, and other extended
892
        # globbing stuff from cvs/rsync.
893
894
        # XXX: fnmatch is actually not quite what we want: it's only
895
        # approximately the same as real Unix fnmatch, and doesn't
896
        # treat dotfiles correctly and allows * to match /.
897
        # Eventually it should be replaced with something more
898
        # accurate.
899
        
900
        for pat in self.get_ignore_list():
901
            if '/' in pat or '\\' in pat:
902
                
903
                # as a special case, you can put ./ at the start of a
904
                # pattern; this is good to match in the top-level
905
                # only;
906
                
907
                if (pat[:2] == './') or (pat[:2] == '.\\'):
908
                    newpat = pat[2:]
909
                else:
910
                    newpat = pat
911
                if fnmatch.fnmatchcase(filename, newpat):
912
                    return pat
913
            else:
914
                if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
915
                    return pat
916
        else:
917
            return None
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
918
1185.12.28 by Aaron Bentley
Removed use of readonly path for executability test
919
    def kind(self, file_id):
920
        return file_kind(self.id2abspath(file_id))
921
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
922
    def last_revision(self):
923
        """Return the last revision id of this working tree.
924
925
        In early branch formats this was == the branch last_revision,
926
        but that cannot be relied upon - for working tree operations,
927
        always use tree.last_revision().
928
        """
929
        return self.branch.last_revision()
930
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
931
    def lock_read(self):
932
        """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.
933
        self.branch.lock_read()
934
        try:
935
            return self._control_files.lock_read()
936
        except:
937
            self.branch.unlock()
938
            raise
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
939
940
    def lock_write(self):
941
        """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.
942
        self.branch.lock_write()
943
        try:
944
            return self._control_files.lock_write()
945
        except:
946
            self.branch.unlock()
947
            raise
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
948
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
949
    def _basis_inventory_name(self, revision_id):
950
        return 'basis-inventory.%s' % revision_id
951
952
    def set_last_revision(self, new_revision, old_revision=None):
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
953
        if old_revision is not None:
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
954
            try:
955
                path = self._basis_inventory_name(old_revision)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
956
                path = self._control_files._escape(path)
957
                self._control_files._transport.delete(path)
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
958
            except NoSuchFile:
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
959
                pass
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
960
        if new_revision is None:
961
            self.branch.set_revision_history([])
962
            return
963
        # current format is locked in with the branch
964
        revision_history = self.branch.revision_history()
965
        try:
966
            position = revision_history.index(new_revision)
967
        except ValueError:
968
            raise errors.NoSuchRevision(self.branch, new_revision)
969
        self.branch.set_revision_history(revision_history[:position + 1])
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
970
        try:
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
971
            xml = self.branch.repository.get_inventory_xml(new_revision)
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
972
            path = self._basis_inventory_name(new_revision)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
973
            self._control_files.put_utf8(path, xml)
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
974
        except WeaveRevisionNotPresent:
975
            pass
976
977
    def read_basis_inventory(self, revision_id):
978
        """Read the cached basis inventory."""
979
        path = self._basis_inventory_name(revision_id)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
980
        return self._control_files.get_utf8(path).read()
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
981
        
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
982
    @needs_read_lock
983
    def read_working_inventory(self):
984
        """Read the working inventory."""
985
        # ElementTree does its own conversion from UTF-8, so open in
986
        # binary.
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
987
        result = bzrlib.xml5.serializer_v5.read_inventory(
1534.4.28 by Robert Collins
first cut at merge from integration.
988
            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()
989
        self._set_inventory(result)
990
        return result
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
991
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
992
    @needs_write_lock
993
    def remove(self, files, verbose=False):
994
        """Remove nominated files from the working inventory..
995
996
        This does not remove their text.  This does not run on XXX on what? RBC
997
998
        TODO: Refuse to remove modified files unless --force is given?
999
1000
        TODO: Do something useful with directories.
1001
1002
        TODO: Should this remove the text or not?  Tough call; not
1003
        removing may be useful and the user can just use use rm, and
1004
        is the opposite of add.  Removing it is consistent with most
1005
        other tools.  Maybe an option.
1006
        """
1007
        ## TODO: Normalize names
1008
        ## TODO: Remove nested loops; better scalability
1009
        if isinstance(files, basestring):
1010
            files = [files]
1011
1012
        inv = self.inventory
1013
1014
        # do this before any modifications
1015
        for f in files:
1016
            fid = inv.path2id(f)
1017
            if not fid:
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
1018
                # TODO: Perhaps make this just a warning, and continue?
1019
                # This tends to happen when 
1020
                raise NotVersionedError(path=f)
1185.31.4 by John Arbash Meinel
Fixing mutter() calls to not have to do string processing.
1021
            mutter("remove inventory entry %s {%s}", quotefn(f), fid)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1022
            if verbose:
1023
                # having remove it, it must be either ignored or unknown
1024
                if self.is_ignored(f):
1025
                    new_status = 'I'
1026
                else:
1027
                    new_status = '?'
1028
                show_status(new_status, inv[fid].kind, quotefn(f))
1029
            del inv[fid]
1030
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1031
        self._write_inventory(inv)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1032
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1033
    @needs_write_lock
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1034
    def revert(self, filenames, old_tree=None, backups=True):
1457.1.8 by Robert Collins
Replace the WorkingTree.revert method algorithm with a call to merge_inner.
1035
        from bzrlib.merge import merge_inner
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1036
        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()
1037
            old_tree = self.basis_tree()
1457.1.8 by Robert Collins
Replace the WorkingTree.revert method algorithm with a call to merge_inner.
1038
        merge_inner(self.branch, old_tree,
1039
                    self, ignore_zero=True,
1040
                    backup_files=backups, 
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
1041
                    interesting_files=filenames,
1042
                    this_tree=self)
1457.1.8 by Robert Collins
Replace the WorkingTree.revert method algorithm with a call to merge_inner.
1043
        if not len(filenames):
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
1044
            self.set_pending_merges([])
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1045
1046
    @needs_write_lock
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1047
    def set_inventory(self, new_inventory_list):
1048
        from bzrlib.inventory import (Inventory,
1049
                                      InventoryDirectory,
1050
                                      InventoryEntry,
1051
                                      InventoryFile,
1052
                                      InventoryLink)
1053
        inv = Inventory(self.get_root_id())
1054
        for path, file_id, parent, kind in new_inventory_list:
1055
            name = os.path.basename(path)
1056
            if name == "":
1057
                continue
1058
            # fixme, there should be a factory function inv,add_?? 
1059
            if kind == 'directory':
1060
                inv.add(InventoryDirectory(file_id, name, parent))
1061
            elif kind == 'file':
1062
                inv.add(InventoryFile(file_id, name, parent))
1063
            elif kind == 'symlink':
1064
                inv.add(InventoryLink(file_id, name, parent))
1065
            else:
1066
                raise BzrError("unknown kind %r" % kind)
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1067
        self._write_inventory(inv)
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1068
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1069
    @needs_write_lock
1070
    def set_root_id(self, file_id):
1071
        """Set the root id for this tree."""
1072
        inv = self.read_working_inventory()
1073
        orig_root_id = inv.root.file_id
1074
        del inv._byid[inv.root.file_id]
1075
        inv.root.file_id = file_id
1076
        inv._byid[inv.root.file_id] = inv.root
1077
        for fid in inv:
1078
            entry = inv[fid]
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1079
            if entry.parent_id == orig_root_id:
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1080
                entry.parent_id = inv.root.file_id
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1081
        self._write_inventory(inv)
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1082
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1083
    def unlock(self):
1084
        """See Branch.unlock.
1085
        
1086
        WorkingTree locking just uses the Branch locking facilities.
1087
        This is current because all working trees have an embedded branch
1088
        within them. IF in the future, we were to make branch data shareable
1089
        between multiple working trees, i.e. via shared storage, then we 
1090
        would probably want to lock both the local tree, and the branch.
1091
        """
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
1092
        # FIXME: We want to write out the hashcache only when the last lock on
1093
        # this working copy is released.  Peeking at the lock count is a bit
1094
        # of a nasty hack; probably it's better to have a transaction object,
1095
        # which can do some finalization when it's either successfully or
1096
        # unsuccessfully completed.  (Denys's original patch did that.)
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.
1097
        # RBC 20060206 hookinhg into transaction will couple lock and transaction
1098
        # wrongly. Hookinh into unllock on the control files object is fine though.
1099
        
1100
        # TODO: split this per format so there is no ugly if block
1101
        if self._hashcache.needs_write and (
1102
            self._control_files._lock_count==1 or 
1103
            (self._control_files is self.branch.control_files and 
1104
             self._control_files._lock_count==2)):
1185.60.6 by Aaron Bentley
Fixed hashcache
1105
            self._hashcache.write()
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.
1106
        # reverse order of locking.
1107
        result = self._control_files.unlock()
1108
        try:
1109
            self.branch.unlock()
1110
        finally:
1111
            return result
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1112
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1113
    @needs_write_lock
1114
    def _write_inventory(self, inv):
1115
        """Write inventory as the current inventory."""
1116
        sio = StringIO()
1117
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
1118
        sio.seek(0)
1534.4.28 by Robert Collins
first cut at merge from integration.
1119
        self._control_files.put('inventory', sio)
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
1120
        self._set_inventory(inv)
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1121
        mutter('wrote working inventory')
1122
            
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1123
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
1124
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
1125
def get_conflicted_stem(path):
1126
    for suffix in CONFLICT_SUFFIXES:
1127
        if path.endswith(suffix):
1128
            return path[:-len(suffix)]
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1129
1130
def is_control_file(filename):
1131
    ## FIXME: better check
1132
    filename = normpath(filename)
1133
    while filename != '':
1134
        head, tail = os.path.split(filename)
1135
        ## mutter('check %r for control file' % ((head, tail),))
1136
        if tail == bzrlib.BZRDIR:
1137
            return True
1138
        if filename == head:
1139
            break
1140
        filename = head
1141
    return False
1142
1143
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1144
class WorkingTreeFormat(object):
1145
    """An encapsulation of the initialization and open routines for a format.
1146
1147
    Formats provide three things:
1148
     * An initialization routine,
1149
     * a format string,
1150
     * an open routine.
1151
1152
    Formats are placed in an dict by their format string for reference 
1153
    during workingtree opening. Its not required that these be instances, they
1154
    can be classes themselves with class methods - it simply depends on 
1155
    whether state is needed for a given format or not.
1156
1157
    Once a format is deprecated, just deprecate the initialize and open
1158
    methods on the format class. Do not deprecate the object, as the 
1159
    object will be created every time regardless.
1160
    """
1161
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1162
    _default_format = None
1163
    """The default format used for new trees."""
1164
1165
    _formats = {}
1166
    """The known formats."""
1167
1168
    @classmethod
1169
    def find_format(klass, a_bzrdir):
1170
        """Return the format for the working tree object in a_bzrdir."""
1171
        try:
1172
            transport = a_bzrdir.get_workingtree_transport(None)
1173
            format_string = transport.get("format").read()
1174
            return klass._formats[format_string]
1175
        except NoSuchFile:
1176
            raise errors.NotBranchError(path=transport.base)
1177
        except KeyError:
1178
            raise errors.UnknownFormatError(format_string)
1179
1180
    @classmethod
1181
    def get_default_format(klass):
1182
        """Return the current default format."""
1183
        return klass._default_format
1184
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1185
    def get_format_string(self):
1186
        """Return the ASCII format string that identifies this format."""
1187
        raise NotImplementedError(self.get_format_string)
1188
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1189
    def is_supported(self):
1190
        """Is this format supported?
1191
1192
        Supported formats can be initialized and opened.
1193
        Unsupported formats may not support initialization or committing or 
1194
        some other features depending on the reason for not being supported.
1195
        """
1196
        return True
1197
1198
    @classmethod
1199
    def register_format(klass, format):
1200
        klass._formats[format.get_format_string()] = format
1201
1202
    @classmethod
1203
    def set_default_format(klass, format):
1204
        klass._default_format = format
1205
1206
    @classmethod
1207
    def unregister_format(klass, format):
1208
        assert klass._formats[format.get_format_string()] is format
1209
        del klass._formats[format.get_format_string()]
1210
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1211
1212
1213
class WorkingTreeFormat2(WorkingTreeFormat):
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1214
    """The second working tree format. 
1215
1216
    This format modified the hash cache from the format 1 hash cache.
1217
    """
1218
1219
    def initialize(self, a_bzrdir):
1220
        """See WorkingTreeFormat.initialize()."""
1221
        if not isinstance(a_bzrdir.transport, LocalTransport):
1222
            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.
1223
        branch = a_bzrdir.open_branch()
1224
        revision = branch.last_revision()
1225
        basis_tree = branch.repository.revision_tree(revision)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1226
        inv = basis_tree.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.
1227
        wt = WorkingTree(a_bzrdir.root_transport.base,
1228
                         branch,
1229
                         inv,
1230
                         _internal=True,
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
1231
                         _format=self,
1232
                         _bzrdir=a_bzrdir)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1233
        wt._write_inventory(inv)
1234
        wt.set_root_id(inv.root.file_id)
1235
        wt.set_last_revision(revision)
1236
        wt.set_pending_merges([])
1237
        wt.revert([])
1238
        return wt
1239
1240
    def __init__(self):
1241
        super(WorkingTreeFormat2, self).__init__()
1242
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1534.4.42 by Robert Collins
add working tree to the BzrDir facilities.
1243
1244
    def open(self, a_bzrdir, _found=False):
1245
        """Return the WorkingTree object for a_bzrdir
1246
1247
        _found is a private parameter, do not use it. It is used to indicate
1248
               if format probing has already been done.
1249
        """
1250
        if not _found:
1251
            # we are being called directly and must probe.
1252
            raise NotImplementedError
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1253
        if not isinstance(a_bzrdir.transport, LocalTransport):
1254
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
1255
        return WorkingTree(a_bzrdir.root_transport.base,
1256
                           _internal=True,
1257
                           _format=self,
1258
                           _bzrdir=a_bzrdir)
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1259
1260
1261
class WorkingTreeFormat3(WorkingTreeFormat):
1262
    """The second working tree format updated to record a format marker.
1263
1264
    This format modified the hash cache from the format 1 hash cache.
1265
    """
1266
1267
    def get_format_string(self):
1268
        """See WorkingTreeFormat.get_format_string()."""
1269
        return "Bazaar-NG Working Tree format 3"
1270
1271
    def initialize(self, a_bzrdir):
1272
        """See WorkingTreeFormat.initialize()."""
1273
        if not isinstance(a_bzrdir.transport, LocalTransport):
1274
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1275
        transport = a_bzrdir.get_workingtree_transport(self)
1276
        control_files = LockableFiles(transport, 'lock')
1277
        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.
1278
        branch = a_bzrdir.open_branch()
1279
        revision = branch.last_revision()
1280
        basis_tree = branch.repository.revision_tree(revision)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1281
        inv = basis_tree.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.
1282
        wt = WorkingTree(a_bzrdir.root_transport.base,
1283
                         branch,
1284
                         inv,
1285
                         _internal=True,
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
1286
                         _format=self,
1287
                         _bzrdir=a_bzrdir)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1288
        wt._write_inventory(inv)
1289
        wt.set_root_id(inv.root.file_id)
1290
        wt.set_last_revision(revision)
1291
        wt.set_pending_merges([])
1292
        wt.revert([])
1293
        return wt
1294
1295
    def __init__(self):
1296
        super(WorkingTreeFormat3, self).__init__()
1297
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1534.4.45 by Robert Collins
Start WorkingTree -> .bzr/checkout transition
1298
1299
    def open(self, a_bzrdir, _found=False):
1300
        """Return the WorkingTree object for a_bzrdir
1301
1302
        _found is a private parameter, do not use it. It is used to indicate
1303
               if format probing has already been done.
1304
        """
1305
        if not _found:
1306
            # we are being called directly and must probe.
1307
            raise NotImplementedError
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1308
        if not isinstance(a_bzrdir.transport, LocalTransport):
1309
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
1310
        return WorkingTree(a_bzrdir.root_transport.base,
1311
                           _internal=True,
1312
                           _format=self,
1313
                           _bzrdir=a_bzrdir)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1314
1315
1316
# formats which have no format string are not discoverable
1317
# and not independently creatable, so are not registered.
1318
__default_format = WorkingTreeFormat3()
1319
WorkingTreeFormat.register_format(__default_format)
1320
WorkingTreeFormat.set_default_format(__default_format)
1321
_legacy_formats = [WorkingTreeFormat2(),
1322
                   ]
1323
1324
1325
class WorkingTreeTestProviderAdapter(object):
1326
    """A tool to generate a suite testing multiple workingtree formats at once.
1327
1328
    This is done by copying the test once for each transport and injecting
1329
    the transport_server, transport_readonly_server, and workingtree_format
1330
    classes into each copy. Each copy is also given a new id() to make it
1331
    easy to identify.
1332
    """
1333
1334
    def __init__(self, transport_server, transport_readonly_server, formats):
1335
        self._transport_server = transport_server
1336
        self._transport_readonly_server = transport_readonly_server
1337
        self._formats = formats
1338
    
1339
    def adapt(self, test):
1340
        from bzrlib.tests import TestSuite
1341
        result = TestSuite()
1342
        for workingtree_format, bzrdir_format in self._formats:
1343
            new_test = deepcopy(test)
1344
            new_test.transport_server = self._transport_server
1345
            new_test.transport_readonly_server = self._transport_readonly_server
1346
            new_test.bzrdir_format = bzrdir_format
1347
            new_test.workingtree_format = workingtree_format
1348
            def make_new_test_id():
1349
                new_id = "%s(%s)" % (new_test.id(), workingtree_format.__class__.__name__)
1350
                return lambda: new_id
1351
            new_test.id = make_new_test_id()
1352
            result.addTest(new_test)
1353
        return result