/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/workingtree.py

Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.

Show diffs side-by-side

added added

removed removed

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