/brz/remove-bazaar

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