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