/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.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
28
To get a WorkingTree, call WorkingTree(dir[, branch])
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
29
"""
30
31
956 by Martin Pool
doc
32
# 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
33
# good idea, because destructors are considered poor taste in Python, and it's
34
# not predictable when it will be written out.
35
36
# TODO: Give the workingtree sole responsibility for the working inventory;
37
# remove the variable and references to it from the branch.  This may require
38
# updating the commit code so as to update the inventory within the working
39
# copy, and making sure there's only one WorkingTree for any directory on disk.
40
# At the momenthey may alias the inventory and have old copies of it in memory.
956 by Martin Pool
doc
41
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
42
from copy import deepcopy
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
43
from cStringIO import StringIO
44
import errno
45
import fnmatch
453 by Martin Pool
- Split WorkingTree into its own file
46
import os
1398 by Robert Collins
integrate in Gustavos x-bit patch
47
import stat
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
48
 
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
49
50
from bzrlib.atomicfile import AtomicFile
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
51
from bzrlib.branch import (Branch,
1534.4.28 by Robert Collins
first cut at merge from integration.
52
                           BzrBranchFormat4,
53
                           BzrBranchFormat5,
54
                           BzrBranchFormat6,
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
55
                           is_control_file,
56
                           quotefn)
1534.4.28 by Robert Collins
first cut at merge from integration.
57
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()
58
import bzrlib.errors as errors
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
59
from bzrlib.errors import (BzrCheckError,
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
60
                           BzrError,
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
61
                           DivergedBranches,
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
62
                           WeaveRevisionNotPresent,
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
63
                           NotBranchError,
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
64
                           NoSuchFile,
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
65
                           NotVersionedError)
66
from bzrlib.inventory import InventoryEntry
1534.4.28 by Robert Collins
first cut at merge from integration.
67
from bzrlib.lockable_files import LockableFiles
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
68
from bzrlib.osutils import (appendpath,
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
69
                            compact_date,
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
70
                            file_kind,
71
                            isdir,
1185.31.39 by John Arbash Meinel
Replacing os.getcwdu() with osutils.getcwd(),
72
                            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 \
73
                            pathjoin,
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
74
                            pumpfile,
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
75
                            safe_unicode,
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
76
                            splitpath,
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
77
                            rand_bytes,
1185.31.37 by John Arbash Meinel
Switched os.path.abspath and os.path.realpath to osutils.* (still passes on cygwin)
78
                            abspath,
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,
82
                            rename)
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
83
from bzrlib.symbol_versioning import *
1185.33.92 by Martin Pool
[patch] fix for 'bzr rm -v' (Wouter van Heyst)
84
from bzrlib.textui import show_status
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
85
import bzrlib.tree
1140 by Martin Pool
- lift out import statements within WorkingTree
86
from bzrlib.trace import mutter
1534.4.28 by Robert Collins
first cut at merge from integration.
87
from bzrlib.transport import get_transport
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
88
import bzrlib.xml5
453 by Martin Pool
- Split WorkingTree into its own file
89
1465 by Robert Collins
Bugfix the new pull --clobber to not generate spurious conflicts.
90
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
91
def gen_file_id(name):
92
    """Return new file id.
93
94
    This should probably generate proper UUIDs, but for the moment we
95
    cope with just randomness because running uuidgen every time is
96
    slow."""
97
    import re
98
    from binascii import hexlify
99
    from time import time
100
101
    # get last component
102
    idx = name.rfind('/')
103
    if idx != -1:
104
        name = name[idx+1 : ]
105
    idx = name.rfind('\\')
106
    if idx != -1:
107
        name = name[idx+1 : ]
108
109
    # make it not a hidden file
110
    name = name.lstrip('.')
111
112
    # remove any wierd characters; we don't escape them but rather
113
    # just pull them out
114
    name = re.sub(r'[^\w.]', '', name)
115
116
    s = hexlify(rand_bytes(8))
117
    return '-'.join((name, compact_date(time()), s))
118
119
120
def gen_root_id():
121
    """Return a new tree-root file id."""
122
    return gen_file_id('TREE_ROOT')
123
124
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
125
class TreeEntry(object):
126
    """An entry that implements the minium interface used by commands.
127
128
    This needs further inspection, it may be better to have 
129
    InventoryEntries without ids - though that seems wrong. For now,
130
    this is a parallel hierarchy to InventoryEntry, and needs to become
131
    one of several things: decorates to that hierarchy, children of, or
132
    parents of it.
1399.1.3 by Robert Collins
move change detection for text and metadata from delta to entry.detect_changes
133
    Another note is that these objects are currently only used when there is
134
    no InventoryEntry available - i.e. for unversioned objects.
135
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
136
    """
137
 
138
    def __eq__(self, other):
139
        # yes, this us ugly, TODO: best practice __eq__ style.
140
        return (isinstance(other, TreeEntry)
141
                and other.__class__ == self.__class__)
142
 
143
    def kind_character(self):
144
        return "???"
145
146
147
class TreeDirectory(TreeEntry):
148
    """See TreeEntry. This is a directory in a working tree."""
149
150
    def __eq__(self, other):
151
        return (isinstance(other, TreeDirectory)
152
                and other.__class__ == self.__class__)
153
154
    def kind_character(self):
155
        return "/"
156
157
158
class TreeFile(TreeEntry):
159
    """See TreeEntry. This is a regular file in a working tree."""
160
161
    def __eq__(self, other):
162
        return (isinstance(other, TreeFile)
163
                and other.__class__ == self.__class__)
164
165
    def kind_character(self):
166
        return ''
167
168
169
class TreeLink(TreeEntry):
170
    """See TreeEntry. This is a symlink in a working tree."""
171
172
    def __eq__(self, other):
173
        return (isinstance(other, TreeLink)
174
                and other.__class__ == self.__class__)
175
176
    def kind_character(self):
177
        return ''
178
179
453 by Martin Pool
- Split WorkingTree into its own file
180
class WorkingTree(bzrlib.tree.Tree):
181
    """Working copy tree.
182
183
    The inventory is held in the `Branch` working-inventory, and the
184
    files are in a directory on disk.
185
186
    It is possible for a `WorkingTree` to have a filename which is
187
    not listed in the Inventory and vice versa.
188
    """
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
189
1534.4.28 by Robert Collins
first cut at merge from integration.
190
    def __init__(self, basedir='.', branch=None, _inventory=None, _control_files=None):
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
191
        """Construct a WorkingTree for basedir.
192
193
        If the branch is not supplied, it is opened automatically.
194
        If the branch is supplied, it must be the branch for this basedir.
195
        (branch.base is not cross checked, because for remote branches that
196
        would be meaningless).
197
        """
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.
198
        from bzrlib.hashcache import HashCache
199
        from bzrlib.trace import note, mutter
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
200
        assert isinstance(basedir, basestring), \
201
            "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.
202
        basedir = safe_unicode(basedir)
1534.4.28 by Robert Collins
first cut at merge from integration.
203
        mutter("openeing working tree %r", basedir)
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
204
        if branch is None:
205
            branch = Branch.open(basedir)
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
206
        assert isinstance(branch, Branch), \
207
            "branch %r is not a Branch" % branch
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
208
        self.branch = branch
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
209
        self.basedir = realpath(basedir)
1534.4.28 by Robert Collins
first cut at merge from integration.
210
        # if branch is at our basedir and is a format 6 or less
211
        if (isinstance(self.branch._branch_format,
212
                       (BzrBranchFormat4, BzrBranchFormat5, BzrBranchFormat6))
213
            # might be able to share control object
214
            and self.branch.base.split('/')[-2] == self.basedir.split('/')[-1]):
215
            self._control_files = self.branch.control_files
216
        elif _control_files is not None:
217
            assert False, "not done yet"
218
#            self._control_files = _control_files
219
        else:
220
            self._control_files = LockableFiles(
221
                get_transport(self.basedir).clone(bzrlib.BZRDIR), 'branch-lock')
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
222
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.
223
        # update the whole cache up front and write to disk if anything changed;
224
        # in the future we might want to do this more selectively
1467 by Robert Collins
WorkingTree.__del__ has been removed.
225
        # two possible ways offer themselves : in self._unlock, write the cache
226
        # if needed, or, when the cache sees a change, append it to the hash
227
        # cache file, and have the parser take the most recent entry for a
228
        # given path only.
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.
229
        hc = self._hashcache = HashCache(basedir)
230
        hc.read()
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
231
        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.
232
233
        if hc.needs_write:
234
            mutter("write hc")
235
            hc.write()
453 by Martin Pool
- Split WorkingTree into its own file
236
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
237
        if _inventory is None:
238
            self._set_inventory(self.read_working_inventory())
239
        else:
240
            self._set_inventory(_inventory)
1185.60.6 by Aaron Bentley
Fixed hashcache
241
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
242
    def _set_inventory(self, inv):
243
        self._inventory = inv
244
        self.path2id = self._inventory.path2id
245
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
246
    @staticmethod
247
    def open_containing(path=None):
248
        """Open an existing working tree which has its root about path.
249
        
250
        This probes for a working tree at path and searches upwards from there.
251
252
        Basically we keep looking up until we find the control directory or
253
        run into /.  If there isn't one, raises NotBranchError.
254
        TODO: give this a new exception.
255
        If there is one, it is returned, along with the unused portion of path.
256
        """
257
        if path is None:
1185.31.39 by John Arbash Meinel
Replacing os.getcwdu() with osutils.getcwd(),
258
            path = getcwd()
1508.1.3 by Robert Collins
Do not consider urls to be relative paths within working trees.
259
        else:
260
            # sanity check.
261
            if path.find('://') != -1:
262
                raise NotBranchError(path=path)
1185.31.37 by John Arbash Meinel
Switched os.path.abspath and os.path.realpath to osutils.* (still passes on cygwin)
263
        path = abspath(path)
1185.62.15 by John Arbash Meinel
Adding fix + test for correct error message when not in branch.
264
        orig_path = path[:]
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
265
        tail = u''
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
266
        while True:
267
            try:
268
                return WorkingTree(path), tail
269
            except NotBranchError:
270
                pass
271
            if tail:
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 \
272
                tail = pathjoin(os.path.basename(path), tail)
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
273
            else:
274
                tail = os.path.basename(path)
1185.31.41 by John Arbash Meinel
Creating a PathNotChild exception, and using relpath in HTTPTestUtil
275
            lastpath = path
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
276
            path = os.path.dirname(path)
1185.31.41 by John Arbash Meinel
Creating a PathNotChild exception, and using relpath in HTTPTestUtil
277
            if lastpath == path:
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
278
                # reached the root, whatever that may be
1185.62.15 by John Arbash Meinel
Adding fix + test for correct error message when not in branch.
279
                raise NotBranchError(path=orig_path)
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
280
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
281
    def __iter__(self):
282
        """Iterate through file_ids for this tree.
283
284
        file_ids are in a WorkingTree if they are in the working inventory
285
        and the working file exists.
286
        """
287
        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.
288
        for path, ie in inv.iter_entries():
1092.2.6 by Robert Collins
symlink support updated to work
289
            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.
290
                yield ie.file_id
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
291
453 by Martin Pool
- Split WorkingTree into its own file
292
    def __repr__(self):
293
        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
294
                               getattr(self, 'basedir', None))
453 by Martin Pool
- Split WorkingTree into its own file
295
296
    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 \
297
        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()
298
    
299
    def basis_tree(self):
300
        """Return RevisionTree for the current last revision."""
301
        revision_id = self.last_revision()
302
        if revision_id is not None:
303
            try:
304
                xml = self.read_basis_inventory(revision_id)
305
                inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
306
                return bzrlib.tree.RevisionTree(self.branch.repository, inv,
307
                                                revision_id)
308
            except NoSuchFile:
309
                pass
310
        return self.branch.repository.revision_tree(revision_id)
453 by Martin Pool
- Split WorkingTree into its own file
311
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
312
    @staticmethod
313
    def create(branch, directory):
314
        """Create a workingtree for branch at directory.
315
316
        If existing_directory already exists it must have a .bzr directory.
317
        If it does not exist, it will be created.
318
319
        This returns a new WorkingTree object for the new checkout.
320
321
        TODO FIXME RBC 20060124 when we have checkout formats in place this
322
        should accept an optional revisionid to checkout [and reject this if
323
        checking out into the same dir as a pre-checkout-aware branch format.]
324
        """
325
        try:
326
            os.mkdir(directory)
327
        except OSError, e:
328
            if e.errno != errno.EEXIST:
329
                raise
330
        try:
331
            os.mkdir(pathjoin(directory, '.bzr'))
332
        except OSError, e:
333
            if e.errno != errno.EEXIST:
334
                raise
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
335
        revision_tree = branch.repository.revision_tree(branch.last_revision())
336
        inv = revision_tree.inventory
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
337
        wt = WorkingTree(directory, branch, inv)
338
        wt._write_inventory(inv)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
339
        wt.set_root_id(revision_tree.inventory.root.file_id)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
340
        if branch.last_revision() is not None:
341
            wt.set_last_revision(branch.last_revision())
342
        wt.set_pending_merges([])
343
        wt.revert([])
344
        return wt
345
 
346
    @staticmethod
347
    def create_standalone(directory):
348
        """Create a checkout and a branch at directory.
349
350
        Directory must exist and be empty.
351
        """
352
        directory = safe_unicode(directory)
353
        b = Branch.create(directory)
354
        return WorkingTree.create(b, directory)
355
1185.31.37 by John Arbash Meinel
Switched os.path.abspath and os.path.realpath to osutils.* (still passes on cygwin)
356
    def relpath(self, abs):
1457.1.3 by Robert Collins
make Branch.relpath delegate to the working tree.
357
        """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)
358
        return relpath(self.basedir, abs)
1457.1.3 by Robert Collins
make Branch.relpath delegate to the working tree.
359
453 by Martin Pool
- Split WorkingTree into its own file
360
    def has_filename(self, filename):
1092.2.6 by Robert Collins
symlink support updated to work
361
        return bzrlib.osutils.lexists(self.abspath(filename))
453 by Martin Pool
- Split WorkingTree into its own file
362
363
    def get_file(self, file_id):
364
        return self.get_file_byname(self.id2path(file_id))
365
366
    def get_file_byname(self, filename):
367
        return file(self.abspath(filename), 'rb')
368
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
369
    def get_root_id(self):
370
        """Return the id of this trees root"""
371
        inv = self.read_working_inventory()
372
        return inv.root.file_id
373
        
453 by Martin Pool
- Split WorkingTree into its own file
374
    def _get_store_filename(self, file_id):
1508.1.1 by Robert Collins
Provide a open_containing for WorkingTree.
375
        ## XXX: badly named; this is not in the store at all
453 by Martin Pool
- Split WorkingTree into its own file
376
        return self.abspath(self.id2path(file_id))
377
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
378
    @needs_read_lock
379
    def clone(self, to_directory, revision=None):
380
        """Copy this working tree to a new directory.
381
        
382
        Currently this will make a new standalone branch at to_directory,
383
        but it is planned to change this to use the same branch style that this
384
        current tree uses (standalone if standalone, repository if repository)
385
        - so that this really is a clone. FIXME RBC 20060127 do this.
386
        FIXME MORE RBC 20060127 failed to reach consensus on this in #bzr.
387
388
        If you want a standalone branch, please use branch.clone(to_directory)
389
        followed by WorkingTree.create(cloned_branch, to_directory) which is
390
        the supported api to produce that.
391
392
        revision
393
            If not None, the cloned tree will have its last revision set to 
394
            revision, and if a branch is being copied it will be informed
395
            of the revision to result in. 
396
    
397
        to_directory -- The destination directory: Must not exist.
398
        """
399
        to_directory = safe_unicode(to_directory)
400
        os.mkdir(to_directory)
401
        # FIXME here is where the decision to clone the branch should happen.
402
        if revision is None:
403
            revision = self.last_revision()
404
        cloned_branch = self.branch.clone(to_directory, revision)
405
        return  WorkingTree.create(cloned_branch, to_directory)
406
1457.1.17 by Robert Collins
Branch.commit() has moved to WorkingTree.commit(). (Robert Collins)
407
    @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.
408
    def commit(self, *args, **kwargs):
1457.1.17 by Robert Collins
Branch.commit() has moved to WorkingTree.commit(). (Robert Collins)
409
        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.
410
        # args for wt.commit start at message from the Commit.commit method,
411
        # but with branch a kwarg now, passing in args as is results in the
412
        #message being used for the branch
1534.4.32 by Robert Collins
Rename deprecated_nonce to DEPRECATED_PARAMETER
413
        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.
414
        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)
415
        self._set_inventory(self.read_working_inventory())
1248 by Martin Pool
- new weave based cleanup [broken]
416
417
    def id2abspath(self, file_id):
418
        return self.abspath(self.id2path(file_id))
419
1185.12.39 by abentley
Propogated has_or_had_id to Tree
420
    def has_id(self, file_id):
453 by Martin Pool
- Split WorkingTree into its own file
421
        # files that have been deleted are excluded
1185.12.39 by abentley
Propogated has_or_had_id to Tree
422
        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.
423
        if not inv.has_id(file_id):
453 by Martin Pool
- Split WorkingTree into its own file
424
            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.
425
        path = inv.id2path(file_id)
1092.2.6 by Robert Collins
symlink support updated to work
426
        return bzrlib.osutils.lexists(self.abspath(path))
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
427
1185.12.39 by abentley
Propogated has_or_had_id to Tree
428
    def has_or_had_id(self, file_id):
429
        if file_id == self.inventory.root.file_id:
430
            return True
431
        return self.inventory.has_id(file_id)
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
432
433
    __contains__ = has_id
434
453 by Martin Pool
- Split WorkingTree into its own file
435
    def get_file_size(self, file_id):
1248 by Martin Pool
- new weave based cleanup [broken]
436
        return os.path.getsize(self.id2abspath(file_id))
453 by Martin Pool
- Split WorkingTree into its own file
437
1185.60.6 by Aaron Bentley
Fixed hashcache
438
    @needs_read_lock
453 by Martin Pool
- Split WorkingTree into its own file
439
    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.
440
        path = self._inventory.id2path(file_id)
441
        return self._hashcache.get_sha1(path)
453 by Martin Pool
- Split WorkingTree into its own file
442
1398 by Robert Collins
integrate in Gustavos x-bit patch
443
    def is_executable(self, file_id):
444
        if os.name == "nt":
445
            return self._inventory[file_id].executable
446
        else:
447
            path = self._inventory.id2path(file_id)
448
            mode = os.lstat(self.abspath(path)).st_mode
449
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
450
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
451
    @needs_write_lock
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
452
    def add(self, files, ids=None):
453
        """Make files versioned.
454
455
        Note that the command line normally calls smart_add instead,
456
        which can automatically recurse.
457
458
        This adds the files to the inventory, so that they will be
459
        recorded by the next commit.
460
461
        files
462
            List of paths to add, relative to the base of the tree.
463
464
        ids
465
            If set, use these instead of automatically generated ids.
466
            Must be the same length as the list of files, but may
467
            contain None for ids that are to be autogenerated.
468
469
        TODO: Perhaps have an option to add the ids even if the files do
470
              not (yet) exist.
471
472
        TODO: Perhaps callback with the ids and paths as they're added.
473
        """
474
        # TODO: Re-adding a file that is removed in the working copy
475
        # should probably put it back with the previous ID.
476
        if isinstance(files, basestring):
477
            assert(ids is None or isinstance(ids, basestring))
478
            files = [files]
479
            if ids is not None:
480
                ids = [ids]
481
482
        if ids is None:
483
            ids = [None] * len(files)
484
        else:
485
            assert(len(ids) == len(files))
486
487
        inv = self.read_working_inventory()
488
        for f,file_id in zip(files, ids):
489
            if is_control_file(f):
490
                raise BzrError("cannot add control file %s" % quotefn(f))
491
492
            fp = splitpath(f)
493
494
            if len(fp) == 0:
495
                raise BzrError("cannot add top-level %r" % f)
496
1185.31.38 by John Arbash Meinel
Changing os.path.normpath to osutils.normpath
497
            fullpath = normpath(self.abspath(f))
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
498
499
            try:
500
                kind = file_kind(fullpath)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
501
            except OSError, e:
502
                if e.errno == errno.ENOENT:
503
                    raise NoSuchFile(fullpath)
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
504
                # maybe something better?
505
                raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
506
507
            if not InventoryEntry.versionable_kind(kind):
508
                raise BzrError('cannot add: not a versionable file ('
509
                               'i.e. regular file, symlink or directory): %s' % quotefn(f))
510
511
            if file_id is None:
512
                file_id = gen_file_id(f)
513
            inv.add_path(f, kind=kind, file_id=file_id)
514
515
            mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
516
        self._write_inventory(inv)
517
518
    @needs_write_lock
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
519
    def add_pending_merge(self, *revision_ids):
520
        # TODO: Perhaps should check at this point that the
521
        # history of the revision is actually present?
522
        p = self.pending_merges()
523
        updated = False
524
        for rev_id in revision_ids:
525
            if rev_id in p:
526
                continue
527
            p.append(rev_id)
528
            updated = True
529
        if updated:
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
530
            self.set_pending_merges(p)
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
531
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
532
    @needs_read_lock
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
533
    def pending_merges(self):
534
        """Return a list of pending merges.
535
536
        These are revisions that have been merged into the working
537
        directory but not yet committed.
538
        """
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
539
        try:
1534.4.28 by Robert Collins
first cut at merge from integration.
540
            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.
541
        except OSError, e:
542
            if e.errno != errno.ENOENT:
543
                raise
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
544
            return []
545
        p = []
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
546
        for l in merges_file.readlines():
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
547
            p.append(l.rstrip('\n'))
548
        return p
549
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
550
    @needs_write_lock
551
    def set_pending_merges(self, rev_list):
1534.4.28 by Robert Collins
first cut at merge from integration.
552
        self._control_files.put_utf8('pending-merges', '\n'.join(rev_list))
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
553
1092.2.6 by Robert Collins
symlink support updated to work
554
    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
555
        return os.readlink(self.id2abspath(file_id))
453 by Martin Pool
- Split WorkingTree into its own file
556
557
    def file_class(self, filename):
558
        if self.path2id(filename):
559
            return 'V'
560
        elif self.is_ignored(filename):
561
            return 'I'
562
        else:
563
            return '?'
564
565
566
    def list_files(self):
567
        """Recursively list all files as (path, class, kind, id).
568
569
        Lists, but does not descend into unversioned directories.
570
571
        This does not include files that have been deleted in this
572
        tree.
573
574
        Skips the control directory.
575
        """
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.
576
        inv = self._inventory
453 by Martin Pool
- Split WorkingTree into its own file
577
578
        def descend(from_dir_relpath, from_dir_id, dp):
579
            ls = os.listdir(dp)
580
            ls.sort()
581
            for f in ls:
582
                ## TODO: If we find a subdirectory with its own .bzr
583
                ## directory, then that is a separate tree and we
584
                ## should exclude it.
585
                if bzrlib.BZRDIR == f:
586
                    continue
587
588
                # path within tree
589
                fp = appendpath(from_dir_relpath, f)
590
591
                # absolute path
592
                fap = appendpath(dp, f)
593
                
594
                f_ie = inv.get_child(from_dir_id, f)
595
                if f_ie:
596
                    c = 'V'
597
                elif self.is_ignored(fp):
598
                    c = 'I'
599
                else:
600
                    c = '?'
601
602
                fk = file_kind(fap)
603
604
                if f_ie:
605
                    if f_ie.kind != fk:
606
                        raise BzrCheckError("file %r entered as kind %r id %r, "
607
                                            "now of kind %r"
608
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
609
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
610
                # make a last minute entry
611
                if f_ie:
612
                    entry = f_ie
613
                else:
614
                    if fk == 'directory':
615
                        entry = TreeDirectory()
616
                    elif fk == 'file':
617
                        entry = TreeFile()
618
                    elif fk == 'symlink':
619
                        entry = TreeLink()
620
                    else:
621
                        entry = TreeEntry()
622
                
623
                yield fp, c, fk, (f_ie and f_ie.file_id), entry
453 by Martin Pool
- Split WorkingTree into its own file
624
625
                if fk != 'directory':
626
                    continue
627
628
                if c != 'V':
629
                    # don't descend unversioned directories
630
                    continue
631
                
632
                for ff in descend(fp, f_ie.file_id, fap):
633
                    yield ff
634
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
635
        for f in descend(u'', inv.root.file_id, self.basedir):
453 by Martin Pool
- Split WorkingTree into its own file
636
            yield f
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
637
638
    @needs_write_lock
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
639
    def move(self, from_paths, to_name):
640
        """Rename files.
641
642
        to_name must exist in the inventory.
643
644
        If to_name exists and is a directory, the files are moved into
645
        it, keeping their old names.  
646
647
        Note that to_name is only the last component of the new name;
648
        this doesn't change the directory.
649
650
        This returns a list of (from_path, to_path) pairs for each
651
        entry that is moved.
652
        """
653
        result = []
654
        ## TODO: Option to move IDs only
655
        assert not isinstance(from_paths, basestring)
656
        inv = self.inventory
657
        to_abs = self.abspath(to_name)
658
        if not isdir(to_abs):
659
            raise BzrError("destination %r is not a directory" % to_abs)
660
        if not self.has_filename(to_name):
661
            raise BzrError("destination %r not in working directory" % to_abs)
662
        to_dir_id = inv.path2id(to_name)
663
        if to_dir_id == None and to_name != '':
664
            raise BzrError("destination %r is not a versioned directory" % to_name)
665
        to_dir_ie = inv[to_dir_id]
666
        if to_dir_ie.kind not in ('directory', 'root_directory'):
667
            raise BzrError("destination %r is not a directory" % to_abs)
668
669
        to_idpath = inv.get_idpath(to_dir_id)
670
671
        for f in from_paths:
672
            if not self.has_filename(f):
673
                raise BzrError("%r does not exist in working tree" % f)
674
            f_id = inv.path2id(f)
675
            if f_id == None:
676
                raise BzrError("%r is not versioned" % f)
677
            name_tail = splitpath(f)[-1]
678
            dest_path = appendpath(to_name, name_tail)
679
            if self.has_filename(dest_path):
680
                raise BzrError("destination %r already exists" % dest_path)
681
            if f_id in to_idpath:
682
                raise BzrError("can't move %r to a subdirectory of itself" % f)
683
684
        # OK, so there's a race here, it's possible that someone will
685
        # create a file in this interval and then the rename might be
686
        # left half-done.  But we should have caught most problems.
687
        orig_inv = deepcopy(self.inventory)
688
        try:
689
            for f in from_paths:
690
                name_tail = splitpath(f)[-1]
691
                dest_path = appendpath(to_name, name_tail)
692
                result.append((f, dest_path))
693
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
694
                try:
695
                    rename(self.abspath(f), self.abspath(dest_path))
696
                except OSError, e:
697
                    raise BzrError("failed to rename %r to %r: %s" %
698
                                   (f, dest_path, e[1]),
699
                            ["rename rolled back"])
700
        except:
701
            # restore the inventory on error
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
702
            self._set_inventory(orig_inv)
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
703
            raise
704
        self._write_inventory(inv)
705
        return result
706
707
    @needs_write_lock
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
708
    def rename_one(self, from_rel, to_rel):
709
        """Rename one file.
710
711
        This can change the directory or the filename or both.
712
        """
713
        inv = self.inventory
714
        if not self.has_filename(from_rel):
715
            raise BzrError("can't rename: old working file %r does not exist" % from_rel)
716
        if self.has_filename(to_rel):
717
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
718
719
        file_id = inv.path2id(from_rel)
720
        if file_id == None:
721
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
722
723
        entry = inv[file_id]
724
        from_parent = entry.parent_id
725
        from_name = entry.name
726
        
727
        if inv.path2id(to_rel):
728
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
729
730
        to_dir, to_tail = os.path.split(to_rel)
731
        to_dir_id = inv.path2id(to_dir)
732
        if to_dir_id == None and to_dir != '':
733
            raise BzrError("can't determine destination directory id for %r" % to_dir)
734
735
        mutter("rename_one:")
736
        mutter("  file_id    {%s}" % file_id)
737
        mutter("  from_rel   %r" % from_rel)
738
        mutter("  to_rel     %r" % to_rel)
739
        mutter("  to_dir     %r" % to_dir)
740
        mutter("  to_dir_id  {%s}" % to_dir_id)
741
742
        inv.rename(file_id, to_dir_id, to_tail)
743
744
        from_abs = self.abspath(from_rel)
745
        to_abs = self.abspath(to_rel)
746
        try:
747
            rename(from_abs, to_abs)
748
        except OSError, e:
749
            inv.rename(file_id, from_parent, from_name)
750
            raise BzrError("failed to rename %r to %r: %s"
751
                    % (from_abs, to_abs, e[1]),
752
                    ["rename rolled back"])
753
        self._write_inventory(inv)
754
755
    @needs_read_lock
453 by Martin Pool
- Split WorkingTree into its own file
756
    def unknowns(self):
1508.1.6 by Robert Collins
Move Branch.unknowns() to WorkingTree.
757
        """Return all unknown files.
758
759
        These are files in the working directory that are not versioned or
760
        control files or ignored.
761
        
762
        >>> from bzrlib.branch import ScratchBranch
763
        >>> b = ScratchBranch(files=['foo', 'foo~'])
764
        >>> tree = WorkingTree(b.base, b)
765
        >>> map(str, tree.unknowns())
766
        ['foo']
767
        >>> tree.add('foo')
768
        >>> list(b.unknowns())
769
        []
770
        >>> tree.remove('foo')
771
        >>> list(b.unknowns())
772
        [u'foo']
773
        """
453 by Martin Pool
- Split WorkingTree into its own file
774
        for subp in self.extras():
775
            if not self.is_ignored(subp):
776
                yield subp
777
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
778
    def iter_conflicts(self):
779
        conflicted = set()
780
        for path in (s[0] for s in self.list_files()):
781
            stem = get_conflicted_stem(path)
782
            if stem is None:
783
                continue
784
            if stem not in conflicted:
785
                conflicted.add(stem)
786
                yield stem
453 by Martin Pool
- Split WorkingTree into its own file
787
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
788
    @needs_write_lock
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
789
    def pull(self, source, overwrite=False):
1465 by Robert Collins
Bugfix the new pull --clobber to not generate spurious conflicts.
790
        from bzrlib.merge import merge_inner
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
791
        source.lock_read()
792
        try:
793
            old_revision_history = self.branch.revision_history()
1185.33.44 by Martin Pool
[patch] show number of revisions pushed/pulled/merged (Robey Pointer)
794
            count = self.branch.pull(source, overwrite)
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
795
            new_revision_history = self.branch.revision_history()
796
            if new_revision_history != old_revision_history:
1465 by Robert Collins
Bugfix the new pull --clobber to not generate spurious conflicts.
797
                if len(old_revision_history):
798
                    other_revision = old_revision_history[-1]
799
                else:
800
                    other_revision = None
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
801
                repository = self.branch.repository
1465 by Robert Collins
Bugfix the new pull --clobber to not generate spurious conflicts.
802
                merge_inner(self.branch,
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
803
                            self.basis_tree(), 
1534.4.28 by Robert Collins
first cut at merge from integration.
804
                            repository.revision_tree(other_revision),
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
805
                            this_tree=self)
806
                self.set_last_revision(self.branch.last_revision())
1185.33.44 by Martin Pool
[patch] show number of revisions pushed/pulled/merged (Robey Pointer)
807
            return count
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
808
        finally:
809
            source.unlock()
810
453 by Martin Pool
- Split WorkingTree into its own file
811
    def extras(self):
812
        """Yield all unknown files in this WorkingTree.
813
814
        If there are any unknown directories then only the directory is
815
        returned, not all its children.  But if there are unknown files
816
        under a versioned subdirectory, they are returned.
817
818
        Currently returned depth-first, sorted by name within directories.
819
        """
820
        ## TODO: Work from given directory downwards
821
        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.
822
            mutter("search for unknowns in %r", path)
453 by Martin Pool
- Split WorkingTree into its own file
823
            dirabs = self.abspath(path)
824
            if not isdir(dirabs):
825
                # e.g. directory deleted
826
                continue
827
828
            fl = []
829
            for subf in os.listdir(dirabs):
830
                if (subf != '.bzr'
831
                    and (subf not in dir_entry.children)):
832
                    fl.append(subf)
833
            
834
            fl.sort()
835
            for subf in fl:
836
                subp = appendpath(path, subf)
837
                yield subp
838
839
840
    def ignored_files(self):
841
        """Yield list of PATH, IGNORE_PATTERN"""
842
        for subp in self.extras():
843
            pat = self.is_ignored(subp)
844
            if pat != None:
845
                yield subp, pat
846
847
848
    def get_ignore_list(self):
849
        """Return list of ignore patterns.
850
851
        Cached in the Tree object after the first call.
852
        """
853
        if hasattr(self, '_ignorelist'):
854
            return self._ignorelist
855
856
        l = bzrlib.DEFAULT_IGNORE[:]
857
        if self.has_filename(bzrlib.IGNORE_FILENAME):
858
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
859
            l.extend([line.rstrip("\n\r") for line in f.readlines()])
860
        self._ignorelist = l
861
        return l
862
863
864
    def is_ignored(self, filename):
865
        r"""Check whether the filename matches an ignore pattern.
866
867
        Patterns containing '/' or '\' need to match the whole path;
868
        others match against only the last component.
869
870
        If the file is ignored, returns the pattern which caused it to
871
        be ignored, otherwise None.  So this can simply be used as a
872
        boolean if desired."""
873
874
        # TODO: Use '**' to match directories, and other extended
875
        # globbing stuff from cvs/rsync.
876
877
        # XXX: fnmatch is actually not quite what we want: it's only
878
        # approximately the same as real Unix fnmatch, and doesn't
879
        # treat dotfiles correctly and allows * to match /.
880
        # Eventually it should be replaced with something more
881
        # accurate.
882
        
883
        for pat in self.get_ignore_list():
884
            if '/' in pat or '\\' in pat:
885
                
886
                # as a special case, you can put ./ at the start of a
887
                # pattern; this is good to match in the top-level
888
                # only;
889
                
890
                if (pat[:2] == './') or (pat[:2] == '.\\'):
891
                    newpat = pat[2:]
892
                else:
893
                    newpat = pat
894
                if fnmatch.fnmatchcase(filename, newpat):
895
                    return pat
896
            else:
897
                if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
898
                    return pat
899
        else:
900
            return None
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
901
1185.12.28 by Aaron Bentley
Removed use of readonly path for executability test
902
    def kind(self, file_id):
903
        return file_kind(self.id2abspath(file_id))
904
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
905
    def last_revision(self):
906
        """Return the last revision id of this working tree.
907
908
        In early branch formats this was == the branch last_revision,
909
        but that cannot be relied upon - for working tree operations,
910
        always use tree.last_revision().
911
        """
912
        return self.branch.last_revision()
913
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
914
    def lock_read(self):
915
        """See Branch.lock_read, and WorkingTree.unlock."""
916
        return self.branch.lock_read()
917
918
    def lock_write(self):
919
        """See Branch.lock_write, and WorkingTree.unlock."""
920
        return self.branch.lock_write()
921
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
922
    def _basis_inventory_name(self, revision_id):
923
        return 'basis-inventory.%s' % revision_id
924
925
    def set_last_revision(self, new_revision, old_revision=None):
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
926
        if old_revision is not None:
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
927
            try:
928
                path = self._basis_inventory_name(old_revision)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
929
                path = self._control_files._escape(path)
930
                self._control_files._transport.delete(path)
1185.65.17 by Robert Collins
Merge from integration, mode-changes are broken.
931
            except NoSuchFile:
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
932
                pass
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
933
        if new_revision is None:
934
            self.branch.set_revision_history([])
935
            return
936
        # current format is locked in with the branch
937
        revision_history = self.branch.revision_history()
938
        try:
939
            position = revision_history.index(new_revision)
940
        except ValueError:
941
            raise errors.NoSuchRevision(self.branch, new_revision)
942
        self.branch.set_revision_history(revision_history[:position + 1])
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
943
        try:
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
944
            xml = self.branch.repository.get_inventory_xml(new_revision)
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
945
            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()
946
            self._control_files.put_utf8(path, xml)
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
947
        except WeaveRevisionNotPresent:
948
            pass
949
950
    def read_basis_inventory(self, revision_id):
951
        """Read the cached basis inventory."""
952
        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()
953
        return self._control_files.get_utf8(path).read()
1185.33.59 by Martin Pool
[patch] keep a cached basis inventory (Johan Rydberg)
954
        
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
955
    @needs_read_lock
956
    def read_working_inventory(self):
957
        """Read the working inventory."""
958
        # ElementTree does its own conversion from UTF-8, so open in
959
        # binary.
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
960
        result = bzrlib.xml5.serializer_v5.read_inventory(
1534.4.28 by Robert Collins
first cut at merge from integration.
961
            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()
962
        self._set_inventory(result)
963
        return result
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
964
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
965
    @needs_write_lock
966
    def remove(self, files, verbose=False):
967
        """Remove nominated files from the working inventory..
968
969
        This does not remove their text.  This does not run on XXX on what? RBC
970
971
        TODO: Refuse to remove modified files unless --force is given?
972
973
        TODO: Do something useful with directories.
974
975
        TODO: Should this remove the text or not?  Tough call; not
976
        removing may be useful and the user can just use use rm, and
977
        is the opposite of add.  Removing it is consistent with most
978
        other tools.  Maybe an option.
979
        """
980
        ## TODO: Normalize names
981
        ## TODO: Remove nested loops; better scalability
982
        if isinstance(files, basestring):
983
            files = [files]
984
985
        inv = self.inventory
986
987
        # do this before any modifications
988
        for f in files:
989
            fid = inv.path2id(f)
990
            if not fid:
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
991
                # TODO: Perhaps make this just a warning, and continue?
992
                # This tends to happen when 
993
                raise NotVersionedError(path=f)
1185.31.4 by John Arbash Meinel
Fixing mutter() calls to not have to do string processing.
994
            mutter("remove inventory entry %s {%s}", quotefn(f), fid)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
995
            if verbose:
996
                # having remove it, it must be either ignored or unknown
997
                if self.is_ignored(f):
998
                    new_status = 'I'
999
                else:
1000
                    new_status = '?'
1001
                show_status(new_status, inv[fid].kind, quotefn(f))
1002
            del inv[fid]
1003
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1004
        self._write_inventory(inv)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1005
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1006
    @needs_write_lock
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1007
    def revert(self, filenames, old_tree=None, backups=True):
1457.1.8 by Robert Collins
Replace the WorkingTree.revert method algorithm with a call to merge_inner.
1008
        from bzrlib.merge import merge_inner
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1009
        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()
1010
            old_tree = self.basis_tree()
1457.1.8 by Robert Collins
Replace the WorkingTree.revert method algorithm with a call to merge_inner.
1011
        merge_inner(self.branch, old_tree,
1012
                    self, ignore_zero=True,
1013
                    backup_files=backups, 
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
1014
                    interesting_files=filenames,
1015
                    this_tree=self)
1457.1.8 by Robert Collins
Replace the WorkingTree.revert method algorithm with a call to merge_inner.
1016
        if not len(filenames):
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
1017
            self.set_pending_merges([])
1501 by Robert Collins
Move revert from Branch to WorkingTree.
1018
1019
    @needs_write_lock
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1020
    def set_inventory(self, new_inventory_list):
1021
        from bzrlib.inventory import (Inventory,
1022
                                      InventoryDirectory,
1023
                                      InventoryEntry,
1024
                                      InventoryFile,
1025
                                      InventoryLink)
1026
        inv = Inventory(self.get_root_id())
1027
        for path, file_id, parent, kind in new_inventory_list:
1028
            name = os.path.basename(path)
1029
            if name == "":
1030
                continue
1031
            # fixme, there should be a factory function inv,add_?? 
1032
            if kind == 'directory':
1033
                inv.add(InventoryDirectory(file_id, name, parent))
1034
            elif kind == 'file':
1035
                inv.add(InventoryFile(file_id, name, parent))
1036
            elif kind == 'symlink':
1037
                inv.add(InventoryLink(file_id, name, parent))
1038
            else:
1039
                raise BzrError("unknown kind %r" % kind)
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1040
        self._write_inventory(inv)
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1041
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1042
    @needs_write_lock
1043
    def set_root_id(self, file_id):
1044
        """Set the root id for this tree."""
1045
        inv = self.read_working_inventory()
1046
        orig_root_id = inv.root.file_id
1047
        del inv._byid[inv.root.file_id]
1048
        inv.root.file_id = file_id
1049
        inv._byid[inv.root.file_id] = inv.root
1050
        for fid in inv:
1051
            entry = inv[fid]
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1052
            if entry.parent_id == orig_root_id:
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1053
                entry.parent_id = inv.root.file_id
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1054
        self._write_inventory(inv)
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
1055
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1056
    def unlock(self):
1057
        """See Branch.unlock.
1058
        
1059
        WorkingTree locking just uses the Branch locking facilities.
1060
        This is current because all working trees have an embedded branch
1061
        within them. IF in the future, we were to make branch data shareable
1062
        between multiple working trees, i.e. via shared storage, then we 
1063
        would probably want to lock both the local tree, and the branch.
1064
        """
1185.70.3 by Martin Pool
Various updates to make storage branch mergeable:
1065
        # FIXME: We want to write out the hashcache only when the last lock on
1066
        # this working copy is released.  Peeking at the lock count is a bit
1067
        # of a nasty hack; probably it's better to have a transaction object,
1068
        # which can do some finalization when it's either successfully or
1069
        # unsuccessfully completed.  (Denys's original patch did that.)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1070
        if self._hashcache.needs_write and self._control_files._lock_count==1:
1185.60.6 by Aaron Bentley
Fixed hashcache
1071
            self._hashcache.write()
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1072
        return self.branch.unlock()
1073
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1074
    @needs_write_lock
1075
    def _write_inventory(self, inv):
1076
        """Write inventory as the current inventory."""
1077
        sio = StringIO()
1078
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
1079
        sio.seek(0)
1534.4.28 by Robert Collins
first cut at merge from integration.
1080
        self._control_files.put('inventory', sio)
1508.1.10 by Robert Collins
bzrlib.add.smart_add_branch is now smart_add_tree. (Robert Collins)
1081
        self._set_inventory(inv)
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
1082
        mutter('wrote working inventory')
1083
            
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
1084
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
1085
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
1086
def get_conflicted_stem(path):
1087
    for suffix in CONFLICT_SUFFIXES:
1088
        if path.endswith(suffix):
1089
            return path[:-len(suffix)]