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