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