~bzr-pqm/bzr/bzr.dev

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