/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

  • Committer: Martin Pool
  • Date: 2007-03-22 07:04:04 UTC
  • mto: (2323.5.2 0.15)
  • mto: This revision was merged to the branch mainline in revision 2390.
  • Revision ID: mbp@sourcefrog.net-20070322070404-zzhbluric9k4wox1
Move responsibility for suggesting upgrades to ui object

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007 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
# TODO: Give the workingtree sole responsibility for the working inventory;
 
33
# remove the variable and references to it from the branch.  This may require
 
34
# updating the commit code so as to update the inventory within the working
 
35
# copy, and making sure there's only one WorkingTree for any directory on disk.
 
36
# At the moment they may alias the inventory and have old copies of it in
 
37
# memory.  (Now done? -- mbp 20060309)
 
38
 
 
39
from cStringIO import StringIO
 
40
import os
 
41
 
 
42
from bzrlib.lazy_import import lazy_import
 
43
lazy_import(globals(), """
 
44
from bisect import bisect_left
 
45
import collections
 
46
from copy import deepcopy
 
47
import errno
 
48
import itertools
 
49
import operator
 
50
import stat
 
51
from time import time
 
52
import warnings
 
53
import re
 
54
 
 
55
import bzrlib
 
56
from bzrlib import (
 
57
    branch,
 
58
    bzrdir,
 
59
    conflicts as _mod_conflicts,
 
60
    dirstate,
 
61
    errors,
 
62
    generate_ids,
 
63
    globbing,
 
64
    hashcache,
 
65
    ignores,
 
66
    merge,
 
67
    osutils,
 
68
    revisiontree,
 
69
    repository,
 
70
    textui,
 
71
    trace,
 
72
    transform,
 
73
    ui,
 
74
    urlutils,
 
75
    xml5,
 
76
    xml6,
 
77
    xml7,
 
78
    )
 
79
import bzrlib.branch
 
80
from bzrlib.transport import get_transport
 
81
import bzrlib.ui
 
82
from bzrlib.workingtree_4 import WorkingTreeFormat4
 
83
""")
 
84
 
 
85
from bzrlib import symbol_versioning
 
86
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
87
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, TreeReference
 
88
from bzrlib.lockable_files import LockableFiles, TransportLock
 
89
from bzrlib.lockdir import LockDir
 
90
import bzrlib.mutabletree
 
91
from bzrlib.mutabletree import needs_tree_write_lock
 
92
from bzrlib.osutils import (
 
93
    compact_date,
 
94
    file_kind,
 
95
    isdir,
 
96
    normpath,
 
97
    pathjoin,
 
98
    rand_chars,
 
99
    realpath,
 
100
    safe_unicode,
 
101
    splitpath,
 
102
    supports_executable,
 
103
    )
 
104
from bzrlib.trace import mutter, note
 
105
from bzrlib.transport.local import LocalTransport
 
106
from bzrlib.progress import DummyProgress, ProgressPhase
 
107
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
 
108
from bzrlib.rio import RioReader, rio_file, Stanza
 
109
from bzrlib.symbol_versioning import (deprecated_passed,
 
110
        deprecated_method,
 
111
        deprecated_function,
 
112
        DEPRECATED_PARAMETER,
 
113
        zero_eight,
 
114
        zero_eleven,
 
115
        zero_thirteen,
 
116
        )
 
117
 
 
118
 
 
119
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
 
120
CONFLICT_HEADER_1 = "BZR conflict list format 1"
 
121
 
 
122
 
 
123
@deprecated_function(zero_thirteen)
 
124
def gen_file_id(name):
 
125
    """Return new file id for the basename 'name'.
 
126
 
 
127
    Use bzrlib.generate_ids.gen_file_id() instead
 
128
    """
 
129
    return generate_ids.gen_file_id(name)
 
130
 
 
131
 
 
132
@deprecated_function(zero_thirteen)
 
133
def gen_root_id():
 
134
    """Return a new tree-root file id.
 
135
 
 
136
    This has been deprecated in favor of bzrlib.generate_ids.gen_root_id()
 
137
    """
 
138
    return generate_ids.gen_root_id()
 
139
 
 
140
 
 
141
class TreeEntry(object):
 
142
    """An entry that implements the minimum interface used by commands.
 
143
 
 
144
    This needs further inspection, it may be better to have 
 
145
    InventoryEntries without ids - though that seems wrong. For now,
 
146
    this is a parallel hierarchy to InventoryEntry, and needs to become
 
147
    one of several things: decorates to that hierarchy, children of, or
 
148
    parents of it.
 
149
    Another note is that these objects are currently only used when there is
 
150
    no InventoryEntry available - i.e. for unversioned objects.
 
151
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
 
152
    """
 
153
 
 
154
    def __eq__(self, other):
 
155
        # yes, this us ugly, TODO: best practice __eq__ style.
 
156
        return (isinstance(other, TreeEntry)
 
157
                and other.__class__ == self.__class__)
 
158
 
 
159
    def kind_character(self):
 
160
        return "???"
 
161
 
 
162
 
 
163
class TreeDirectory(TreeEntry):
 
164
    """See TreeEntry. This is a directory in a working tree."""
 
165
 
 
166
    def __eq__(self, other):
 
167
        return (isinstance(other, TreeDirectory)
 
168
                and other.__class__ == self.__class__)
 
169
 
 
170
    def kind_character(self):
 
171
        return "/"
 
172
 
 
173
 
 
174
class TreeFile(TreeEntry):
 
175
    """See TreeEntry. This is a regular file in a working tree."""
 
176
 
 
177
    def __eq__(self, other):
 
178
        return (isinstance(other, TreeFile)
 
179
                and other.__class__ == self.__class__)
 
180
 
 
181
    def kind_character(self):
 
182
        return ''
 
183
 
 
184
 
 
185
class TreeLink(TreeEntry):
 
186
    """See TreeEntry. This is a symlink in a working tree."""
 
187
 
 
188
    def __eq__(self, other):
 
189
        return (isinstance(other, TreeLink)
 
190
                and other.__class__ == self.__class__)
 
191
 
 
192
    def kind_character(self):
 
193
        return ''
 
194
 
 
195
 
 
196
class WorkingTree(bzrlib.mutabletree.MutableTree):
 
197
    """Working copy tree.
 
198
 
 
199
    The inventory is held in the `Branch` working-inventory, and the
 
200
    files are in a directory on disk.
 
201
 
 
202
    It is possible for a `WorkingTree` to have a filename which is
 
203
    not listed in the Inventory and vice versa.
 
204
    """
 
205
 
 
206
    def __init__(self, basedir='.',
 
207
                 branch=DEPRECATED_PARAMETER,
 
208
                 _inventory=None,
 
209
                 _control_files=None,
 
210
                 _internal=False,
 
211
                 _format=None,
 
212
                 _bzrdir=None):
 
213
        """Construct a WorkingTree for basedir.
 
214
 
 
215
        If the branch is not supplied, it is opened automatically.
 
216
        If the branch is supplied, it must be the branch for this basedir.
 
217
        (branch.base is not cross checked, because for remote branches that
 
218
        would be meaningless).
 
219
        """
 
220
        self._format = _format
 
221
        self.bzrdir = _bzrdir
 
222
        if not _internal:
 
223
            # not created via open etc.
 
224
            warnings.warn("WorkingTree() is deprecated as of bzr version 0.8. "
 
225
                 "Please use bzrdir.open_workingtree or WorkingTree.open().",
 
226
                 DeprecationWarning,
 
227
                 stacklevel=2)
 
228
            wt = WorkingTree.open(basedir)
 
229
            self._branch = wt.branch
 
230
            self.basedir = wt.basedir
 
231
            self._control_files = wt._control_files
 
232
            self._hashcache = wt._hashcache
 
233
            self._set_inventory(wt._inventory, dirty=False)
 
234
            self._format = wt._format
 
235
            self.bzrdir = wt.bzrdir
 
236
        assert isinstance(basedir, basestring), \
 
237
            "base directory %r is not a string" % basedir
 
238
        basedir = safe_unicode(basedir)
 
239
        mutter("opening working tree %r", basedir)
 
240
        if deprecated_passed(branch):
 
241
            if not _internal:
 
242
                warnings.warn("WorkingTree(..., branch=XXX) is deprecated"
 
243
                     " as of bzr 0.8. Please use bzrdir.open_workingtree() or"
 
244
                     " WorkingTree.open().",
 
245
                     DeprecationWarning,
 
246
                     stacklevel=2
 
247
                     )
 
248
            self._branch = branch
 
249
        else:
 
250
            self._branch = self.bzrdir.open_branch()
 
251
        self.basedir = realpath(basedir)
 
252
        # if branch is at our basedir and is a format 6 or less
 
253
        if isinstance(self._format, WorkingTreeFormat2):
 
254
            # share control object
 
255
            self._control_files = self.branch.control_files
 
256
        else:
 
257
            # assume all other formats have their own control files.
 
258
            assert isinstance(_control_files, LockableFiles), \
 
259
                    "_control_files must be a LockableFiles, not %r" \
 
260
                    % _control_files
 
261
            self._control_files = _control_files
 
262
        # update the whole cache up front and write to disk if anything changed;
 
263
        # in the future we might want to do this more selectively
 
264
        # two possible ways offer themselves : in self._unlock, write the cache
 
265
        # if needed, or, when the cache sees a change, append it to the hash
 
266
        # cache file, and have the parser take the most recent entry for a
 
267
        # given path only.
 
268
        wt_trans = self.bzrdir.get_workingtree_transport(None)
 
269
        cache_filename = wt_trans.local_abspath('stat-cache')
 
270
        self._hashcache = hashcache.HashCache(basedir, cache_filename,
 
271
                                              self._control_files._file_mode)
 
272
        hc = self._hashcache
 
273
        hc.read()
 
274
        # is this scan needed ? it makes things kinda slow.
 
275
        #hc.scan()
 
276
 
 
277
        if hc.needs_write:
 
278
            mutter("write hc")
 
279
            hc.write()
 
280
 
 
281
        if _inventory is None:
 
282
            self._inventory_is_modified = False
 
283
            self.read_working_inventory()
 
284
        else:
 
285
            # the caller of __init__ has provided an inventory,
 
286
            # we assume they know what they are doing - as its only
 
287
            # the Format factory and creation methods that are
 
288
            # permitted to do this.
 
289
            self._set_inventory(_inventory, dirty=False)
 
290
        self._after_opening()
 
291
 
 
292
    def _after_opening(self):
 
293
        """Called after the workingtree is opened.
 
294
        """
 
295
        self._warn_deprecated_format()
 
296
 
 
297
    branch = property(
 
298
        fget=lambda self: self._branch,
 
299
        doc="""The branch this WorkingTree is connected to.
 
300
 
 
301
            This cannot be set - it is reflective of the actual disk structure
 
302
            the working tree has been constructed from.
 
303
            """)
 
304
 
 
305
    def break_lock(self):
 
306
        """Break a lock if one is present from another instance.
 
307
 
 
308
        Uses the ui factory to ask for confirmation if the lock may be from
 
309
        an active process.
 
310
 
 
311
        This will probe the repository for its lock as well.
 
312
        """
 
313
        self._control_files.break_lock()
 
314
        self.branch.break_lock()
 
315
 
 
316
    def requires_rich_root(self):
 
317
        return self._format.requires_rich_root
 
318
 
 
319
    def supports_tree_reference(self):
 
320
        return False
 
321
 
 
322
    def _set_inventory(self, inv, dirty):
 
323
        """Set the internal cached inventory.
 
324
 
 
325
        :param inv: The inventory to set.
 
326
        :param dirty: A boolean indicating whether the inventory is the same
 
327
            logical inventory as whats on disk. If True the inventory is not
 
328
            the same and should be written to disk or data will be lost, if
 
329
            False then the inventory is the same as that on disk and any
 
330
            serialisation would be unneeded overhead.
 
331
        """
 
332
        assert inv.root is not None
 
333
        self._inventory = inv
 
334
        self._inventory_is_modified = dirty
 
335
 
 
336
    @staticmethod
 
337
    def open(path=None, _unsupported=False):
 
338
        """Open an existing working tree at path.
 
339
 
 
340
        """
 
341
        if path is None:
 
342
            path = os.path.getcwdu()
 
343
        control = bzrdir.BzrDir.open(path, _unsupported)
 
344
        return control.open_workingtree(_unsupported)
 
345
        
 
346
    @staticmethod
 
347
    def open_containing(path=None):
 
348
        """Open an existing working tree which has its root about path.
 
349
        
 
350
        This probes for a working tree at path and searches upwards from there.
 
351
 
 
352
        Basically we keep looking up until we find the control directory or
 
353
        run into /.  If there isn't one, raises NotBranchError.
 
354
        TODO: give this a new exception.
 
355
        If there is one, it is returned, along with the unused portion of path.
 
356
 
 
357
        :return: The WorkingTree that contains 'path', and the rest of path
 
358
        """
 
359
        if path is None:
 
360
            path = osutils.getcwd()
 
361
        control, relpath = bzrdir.BzrDir.open_containing(path)
 
362
 
 
363
        return control.open_workingtree(), relpath
 
364
 
 
365
    @staticmethod
 
366
    def open_downlevel(path=None):
 
367
        """Open an unsupported working tree.
 
368
 
 
369
        Only intended for advanced situations like upgrading part of a bzrdir.
 
370
        """
 
371
        return WorkingTree.open(path, _unsupported=True)
 
372
 
 
373
    # should be deprecated - this is slow and in any case treating them as a
 
374
    # container is (we now know) bad style -- mbp 20070302
 
375
    ## @deprecated_method(zero_fifteen)
 
376
    def __iter__(self):
 
377
        """Iterate through file_ids for this tree.
 
378
 
 
379
        file_ids are in a WorkingTree if they are in the working inventory
 
380
        and the working file exists.
 
381
        """
 
382
        inv = self._inventory
 
383
        for path, ie in inv.iter_entries():
 
384
            if osutils.lexists(self.abspath(path)):
 
385
                yield ie.file_id
 
386
 
 
387
    def __repr__(self):
 
388
        return "<%s of %s>" % (self.__class__.__name__,
 
389
                               getattr(self, 'basedir', None))
 
390
 
 
391
    def abspath(self, filename):
 
392
        return pathjoin(self.basedir, filename)
 
393
    
 
394
    def basis_tree(self):
 
395
        """Return RevisionTree for the current last revision.
 
396
        
 
397
        If the left most parent is a ghost then the returned tree will be an
 
398
        empty tree - one obtained by calling repository.revision_tree(None).
 
399
        """
 
400
        try:
 
401
            revision_id = self.get_parent_ids()[0]
 
402
        except IndexError:
 
403
            # no parents, return an empty revision tree.
 
404
            # in the future this should return the tree for
 
405
            # 'empty:' - the implicit root empty tree.
 
406
            return self.branch.repository.revision_tree(None)
 
407
        try:
 
408
            return self.revision_tree(revision_id)
 
409
        except errors.NoSuchRevision:
 
410
            pass
 
411
        # No cached copy available, retrieve from the repository.
 
412
        # FIXME? RBC 20060403 should we cache the inventory locally
 
413
        # at this point ?
 
414
        try:
 
415
            return self.branch.repository.revision_tree(revision_id)
 
416
        except errors.RevisionNotPresent:
 
417
            # the basis tree *may* be a ghost or a low level error may have
 
418
            # occured. If the revision is present, its a problem, if its not
 
419
            # its a ghost.
 
420
            if self.branch.repository.has_revision(revision_id):
 
421
                raise
 
422
            # the basis tree is a ghost so return an empty tree.
 
423
            return self.branch.repository.revision_tree(None)
 
424
 
 
425
    @staticmethod
 
426
    @deprecated_method(zero_eight)
 
427
    def create(branch, directory):
 
428
        """Create a workingtree for branch at directory.
 
429
 
 
430
        If existing_directory already exists it must have a .bzr directory.
 
431
        If it does not exist, it will be created.
 
432
 
 
433
        This returns a new WorkingTree object for the new checkout.
 
434
 
 
435
        TODO FIXME RBC 20060124 when we have checkout formats in place this
 
436
        should accept an optional revisionid to checkout [and reject this if
 
437
        checking out into the same dir as a pre-checkout-aware branch format.]
 
438
 
 
439
        XXX: When BzrDir is present, these should be created through that 
 
440
        interface instead.
 
441
        """
 
442
        warnings.warn('delete WorkingTree.create', stacklevel=3)
 
443
        transport = get_transport(directory)
 
444
        if branch.bzrdir.root_transport.base == transport.base:
 
445
            # same dir 
 
446
            return branch.bzrdir.create_workingtree()
 
447
        # different directory, 
 
448
        # create a branch reference
 
449
        # and now a working tree.
 
450
        raise NotImplementedError
 
451
 
 
452
    @staticmethod
 
453
    @deprecated_method(zero_eight)
 
454
    def create_standalone(directory):
 
455
        """Create a checkout and a branch and a repo at directory.
 
456
 
 
457
        Directory must exist and be empty.
 
458
 
 
459
        please use BzrDir.create_standalone_workingtree
 
460
        """
 
461
        return bzrdir.BzrDir.create_standalone_workingtree(directory)
 
462
 
 
463
    def relpath(self, path):
 
464
        """Return the local path portion from a given path.
 
465
        
 
466
        The path may be absolute or relative. If its a relative path it is 
 
467
        interpreted relative to the python current working directory.
 
468
        """
 
469
        return osutils.relpath(self.basedir, path)
 
470
 
 
471
    def has_filename(self, filename):
 
472
        return osutils.lexists(self.abspath(filename))
 
473
 
 
474
    def get_file(self, file_id):
 
475
        file_id = osutils.safe_file_id(file_id)
 
476
        return self.get_file_byname(self.id2path(file_id))
 
477
 
 
478
    def get_file_text(self, file_id):
 
479
        file_id = osutils.safe_file_id(file_id)
 
480
        return self.get_file(file_id).read()
 
481
 
 
482
    def get_file_byname(self, filename):
 
483
        return file(self.abspath(filename), 'rb')
 
484
 
 
485
    @needs_read_lock
 
486
    def annotate_iter(self, file_id):
 
487
        """See Tree.annotate_iter
 
488
 
 
489
        This implementation will use the basis tree implementation if possible.
 
490
        Lines not in the basis are attributed to CURRENT_REVISION
 
491
 
 
492
        If there are pending merges, lines added by those merges will be
 
493
        incorrectly attributed to CURRENT_REVISION (but after committing, the
 
494
        attribution will be correct).
 
495
        """
 
496
        file_id = osutils.safe_file_id(file_id)
 
497
        basis = self.basis_tree()
 
498
        basis.lock_read()
 
499
        try:
 
500
            changes = self._iter_changes(basis, True, [self.id2path(file_id)],
 
501
                require_versioned=True).next()
 
502
            changed_content, kind = changes[2], changes[6]
 
503
            if not changed_content:
 
504
                return basis.annotate_iter(file_id)
 
505
            if kind[1] is None:
 
506
                return None
 
507
            import annotate
 
508
            if kind[0] != 'file':
 
509
                old_lines = []
 
510
            else:
 
511
                old_lines = list(basis.annotate_iter(file_id))
 
512
            old = [old_lines]
 
513
            for tree in self.branch.repository.revision_trees(
 
514
                self.get_parent_ids()[1:]):
 
515
                if file_id not in tree:
 
516
                    continue
 
517
                old.append(list(tree.annotate_iter(file_id)))
 
518
            return annotate.reannotate(old, self.get_file(file_id).readlines(),
 
519
                                       CURRENT_REVISION)
 
520
        finally:
 
521
            basis.unlock()
 
522
 
 
523
    def get_parent_ids(self):
 
524
        """See Tree.get_parent_ids.
 
525
        
 
526
        This implementation reads the pending merges list and last_revision
 
527
        value and uses that to decide what the parents list should be.
 
528
        """
 
529
        last_rev = self._last_revision()
 
530
        if last_rev is None:
 
531
            parents = []
 
532
        else:
 
533
            parents = [last_rev]
 
534
        try:
 
535
            merges_file = self._control_files.get('pending-merges')
 
536
        except errors.NoSuchFile:
 
537
            pass
 
538
        else:
 
539
            for l in merges_file.readlines():
 
540
                revision_id = osutils.safe_revision_id(l.rstrip('\n'))
 
541
                parents.append(revision_id)
 
542
        return parents
 
543
 
 
544
    @needs_read_lock
 
545
    def get_root_id(self):
 
546
        """Return the id of this trees root"""
 
547
        return self._inventory.root.file_id
 
548
        
 
549
    def _get_store_filename(self, file_id):
 
550
        ## XXX: badly named; this is not in the store at all
 
551
        file_id = osutils.safe_file_id(file_id)
 
552
        return self.abspath(self.id2path(file_id))
 
553
 
 
554
    @needs_read_lock
 
555
    def clone(self, to_bzrdir, revision_id=None, basis=None):
 
556
        """Duplicate this working tree into to_bzr, including all state.
 
557
        
 
558
        Specifically modified files are kept as modified, but
 
559
        ignored and unknown files are discarded.
 
560
 
 
561
        If you want to make a new line of development, see bzrdir.sprout()
 
562
 
 
563
        revision
 
564
            If not None, the cloned tree will have its last revision set to 
 
565
            revision, and and difference between the source trees last revision
 
566
            and this one merged in.
 
567
 
 
568
        basis
 
569
            If not None, a closer copy of a tree which may have some files in
 
570
            common, and which file content should be preferentially copied from.
 
571
        """
 
572
        # assumes the target bzr dir format is compatible.
 
573
        result = self._format.initialize(to_bzrdir)
 
574
        self.copy_content_into(result, revision_id)
 
575
        return result
 
576
 
 
577
    @needs_read_lock
 
578
    def copy_content_into(self, tree, revision_id=None):
 
579
        """Copy the current content and user files of this tree into tree."""
 
580
        tree.set_root_id(self.get_root_id())
 
581
        if revision_id is None:
 
582
            merge.transform_tree(tree, self)
 
583
        else:
 
584
            # TODO now merge from tree.last_revision to revision (to preserve
 
585
            # user local changes)
 
586
            merge.transform_tree(tree, self)
 
587
            tree.set_parent_ids([revision_id])
 
588
 
 
589
    def id2abspath(self, file_id):
 
590
        file_id = osutils.safe_file_id(file_id)
 
591
        return self.abspath(self.id2path(file_id))
 
592
 
 
593
    def has_id(self, file_id):
 
594
        # files that have been deleted are excluded
 
595
        file_id = osutils.safe_file_id(file_id)
 
596
        inv = self.inventory
 
597
        if not inv.has_id(file_id):
 
598
            return False
 
599
        path = inv.id2path(file_id)
 
600
        return osutils.lexists(self.abspath(path))
 
601
 
 
602
    def has_or_had_id(self, file_id):
 
603
        file_id = osutils.safe_file_id(file_id)
 
604
        if file_id == self.inventory.root.file_id:
 
605
            return True
 
606
        return self.inventory.has_id(file_id)
 
607
 
 
608
    __contains__ = has_id
 
609
 
 
610
    def get_file_size(self, file_id):
 
611
        file_id = osutils.safe_file_id(file_id)
 
612
        return os.path.getsize(self.id2abspath(file_id))
 
613
 
 
614
    @needs_read_lock
 
615
    def get_file_sha1(self, file_id, path=None, stat_value=None):
 
616
        file_id = osutils.safe_file_id(file_id)
 
617
        if not path:
 
618
            path = self._inventory.id2path(file_id)
 
619
        return self._hashcache.get_sha1(path, stat_value)
 
620
 
 
621
    def get_file_mtime(self, file_id, path=None):
 
622
        file_id = osutils.safe_file_id(file_id)
 
623
        if not path:
 
624
            path = self.inventory.id2path(file_id)
 
625
        return os.lstat(self.abspath(path)).st_mtime
 
626
 
 
627
    if not supports_executable():
 
628
        def is_executable(self, file_id, path=None):
 
629
            file_id = osutils.safe_file_id(file_id)
 
630
            return self._inventory[file_id].executable
 
631
    else:
 
632
        def is_executable(self, file_id, path=None):
 
633
            if not path:
 
634
                file_id = osutils.safe_file_id(file_id)
 
635
                path = self.id2path(file_id)
 
636
            mode = os.lstat(self.abspath(path)).st_mode
 
637
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
638
 
 
639
    @needs_tree_write_lock
 
640
    def _add(self, files, ids, kinds):
 
641
        """See MutableTree._add."""
 
642
        # TODO: Re-adding a file that is removed in the working copy
 
643
        # should probably put it back with the previous ID.
 
644
        # the read and write working inventory should not occur in this 
 
645
        # function - they should be part of lock_write and unlock.
 
646
        inv = self.read_working_inventory()
 
647
        for f, file_id, kind in zip(files, ids, kinds):
 
648
            assert kind is not None
 
649
            if file_id is None:
 
650
                inv.add_path(f, kind=kind)
 
651
            else:
 
652
                file_id = osutils.safe_file_id(file_id)
 
653
                inv.add_path(f, kind=kind, file_id=file_id)
 
654
        self._write_inventory(inv)
 
655
 
 
656
    @needs_tree_write_lock
 
657
    def _gather_kinds(self, files, kinds):
 
658
        """See MutableTree._gather_kinds."""
 
659
        for pos, f in enumerate(files):
 
660
            if kinds[pos] is None:
 
661
                fullpath = normpath(self.abspath(f))
 
662
                try:
 
663
                    kinds[pos] = file_kind(fullpath)
 
664
                except OSError, e:
 
665
                    if e.errno == errno.ENOENT:
 
666
                        raise errors.NoSuchFile(fullpath)
 
667
 
 
668
    @needs_write_lock
 
669
    def add_parent_tree_id(self, revision_id, allow_leftmost_as_ghost=False):
 
670
        """Add revision_id as a parent.
 
671
 
 
672
        This is equivalent to retrieving the current list of parent ids
 
673
        and setting the list to its value plus revision_id.
 
674
 
 
675
        :param revision_id: The revision id to add to the parent list. It may
 
676
        be a ghost revision as long as its not the first parent to be added,
 
677
        or the allow_leftmost_as_ghost parameter is set True.
 
678
        :param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
 
679
        """
 
680
        parents = self.get_parent_ids() + [revision_id]
 
681
        self.set_parent_ids(parents, allow_leftmost_as_ghost=len(parents) > 1
 
682
            or allow_leftmost_as_ghost)
 
683
 
 
684
    @needs_tree_write_lock
 
685
    def add_parent_tree(self, parent_tuple, allow_leftmost_as_ghost=False):
 
686
        """Add revision_id, tree tuple as a parent.
 
687
 
 
688
        This is equivalent to retrieving the current list of parent trees
 
689
        and setting the list to its value plus parent_tuple. See also
 
690
        add_parent_tree_id - if you only have a parent id available it will be
 
691
        simpler to use that api. If you have the parent already available, using
 
692
        this api is preferred.
 
693
 
 
694
        :param parent_tuple: The (revision id, tree) to add to the parent list.
 
695
            If the revision_id is a ghost, pass None for the tree.
 
696
        :param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
 
697
        """
 
698
        parent_ids = self.get_parent_ids() + [parent_tuple[0]]
 
699
        if len(parent_ids) > 1:
 
700
            # the leftmost may have already been a ghost, preserve that if it
 
701
            # was.
 
702
            allow_leftmost_as_ghost = True
 
703
        self.set_parent_ids(parent_ids,
 
704
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
 
705
 
 
706
    @needs_tree_write_lock
 
707
    def add_pending_merge(self, *revision_ids):
 
708
        # TODO: Perhaps should check at this point that the
 
709
        # history of the revision is actually present?
 
710
        parents = self.get_parent_ids()
 
711
        updated = False
 
712
        for rev_id in revision_ids:
 
713
            if rev_id in parents:
 
714
                continue
 
715
            parents.append(rev_id)
 
716
            updated = True
 
717
        if updated:
 
718
            self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
 
719
 
 
720
    @deprecated_method(zero_eleven)
 
721
    @needs_read_lock
 
722
    def pending_merges(self):
 
723
        """Return a list of pending merges.
 
724
 
 
725
        These are revisions that have been merged into the working
 
726
        directory but not yet committed.
 
727
 
 
728
        As of 0.11 this is deprecated. Please see WorkingTree.get_parent_ids()
 
729
        instead - which is available on all tree objects.
 
730
        """
 
731
        return self.get_parent_ids()[1:]
 
732
 
 
733
    def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
 
734
        """Common ghost checking functionality from set_parent_*.
 
735
 
 
736
        This checks that the left hand-parent exists if there are any
 
737
        revisions present.
 
738
        """
 
739
        if len(revision_ids) > 0:
 
740
            leftmost_id = revision_ids[0]
 
741
            if (not allow_leftmost_as_ghost and not
 
742
                self.branch.repository.has_revision(leftmost_id)):
 
743
                raise errors.GhostRevisionUnusableHere(leftmost_id)
 
744
 
 
745
    def _set_merges_from_parent_ids(self, parent_ids):
 
746
        merges = parent_ids[1:]
 
747
        self._control_files.put_bytes('pending-merges', '\n'.join(merges))
 
748
 
 
749
    @needs_tree_write_lock
 
750
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
 
751
        """Set the parent ids to revision_ids.
 
752
        
 
753
        See also set_parent_trees. This api will try to retrieve the tree data
 
754
        for each element of revision_ids from the trees repository. If you have
 
755
        tree data already available, it is more efficient to use
 
756
        set_parent_trees rather than set_parent_ids. set_parent_ids is however
 
757
        an easier API to use.
 
758
 
 
759
        :param revision_ids: The revision_ids to set as the parent ids of this
 
760
            working tree. Any of these may be ghosts.
 
761
        """
 
762
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
 
763
        self._check_parents_for_ghosts(revision_ids,
 
764
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
 
765
 
 
766
        if len(revision_ids) > 0:
 
767
            self.set_last_revision(revision_ids[0])
 
768
        else:
 
769
            self.set_last_revision(None)
 
770
 
 
771
        self._set_merges_from_parent_ids(revision_ids)
 
772
 
 
773
    @needs_tree_write_lock
 
774
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
 
775
        """See MutableTree.set_parent_trees."""
 
776
        parent_ids = [osutils.safe_revision_id(rev) for (rev, tree) in parents_list]
 
777
 
 
778
        self._check_parents_for_ghosts(parent_ids,
 
779
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
 
780
 
 
781
        if len(parent_ids) == 0:
 
782
            leftmost_parent_id = None
 
783
            leftmost_parent_tree = None
 
784
        else:
 
785
            leftmost_parent_id, leftmost_parent_tree = parents_list[0]
 
786
 
 
787
        if self._change_last_revision(leftmost_parent_id):
 
788
            if leftmost_parent_tree is None:
 
789
                # If we don't have a tree, fall back to reading the
 
790
                # parent tree from the repository.
 
791
                self._cache_basis_inventory(leftmost_parent_id)
 
792
            else:
 
793
                inv = leftmost_parent_tree.inventory
 
794
                xml = self._create_basis_xml_from_inventory(
 
795
                                        leftmost_parent_id, inv)
 
796
                self._write_basis_inventory(xml)
 
797
        self._set_merges_from_parent_ids(parent_ids)
 
798
 
 
799
    @needs_tree_write_lock
 
800
    def set_pending_merges(self, rev_list):
 
801
        parents = self.get_parent_ids()
 
802
        leftmost = parents[:1]
 
803
        new_parents = leftmost + rev_list
 
804
        self.set_parent_ids(new_parents)
 
805
 
 
806
    @needs_tree_write_lock
 
807
    def set_merge_modified(self, modified_hashes):
 
808
        def iter_stanzas():
 
809
            for file_id, hash in modified_hashes.iteritems():
 
810
                yield Stanza(file_id=file_id.decode('utf8'), hash=hash)
 
811
        self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
 
812
 
 
813
    def _put_rio(self, filename, stanzas, header):
 
814
        self._must_be_locked()
 
815
        my_file = rio_file(stanzas, header)
 
816
        self._control_files.put(filename, my_file)
 
817
 
 
818
    @needs_write_lock # because merge pulls data into the branch.
 
819
    def merge_from_branch(self, branch, to_revision=None):
 
820
        """Merge from a branch into this working tree.
 
821
 
 
822
        :param branch: The branch to merge from.
 
823
        :param to_revision: If non-None, the merge will merge to to_revision,
 
824
            but not beyond it. to_revision does not need to be in the history
 
825
            of the branch when it is supplied. If None, to_revision defaults to
 
826
            branch.last_revision().
 
827
        """
 
828
        from bzrlib.merge import Merger, Merge3Merger
 
829
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
830
        try:
 
831
            merger = Merger(self.branch, this_tree=self, pb=pb)
 
832
            merger.pp = ProgressPhase("Merge phase", 5, pb)
 
833
            merger.pp.next_phase()
 
834
            # check that there are no
 
835
            # local alterations
 
836
            merger.check_basis(check_clean=True, require_commits=False)
 
837
            if to_revision is None:
 
838
                to_revision = branch.last_revision()
 
839
            else:
 
840
                to_revision = osutils.safe_revision_id(to_revision)
 
841
            merger.other_rev_id = to_revision
 
842
            if merger.other_rev_id is None:
 
843
                raise error.NoCommits(branch)
 
844
            self.branch.fetch(branch, last_revision=merger.other_rev_id)
 
845
            merger.other_basis = merger.other_rev_id
 
846
            merger.other_tree = self.branch.repository.revision_tree(
 
847
                merger.other_rev_id)
 
848
            merger.other_branch = branch
 
849
            merger.pp.next_phase()
 
850
            merger.find_base()
 
851
            if merger.base_rev_id == merger.other_rev_id:
 
852
                raise errors.PointlessMerge
 
853
            merger.backup_files = False
 
854
            merger.merge_type = Merge3Merger
 
855
            merger.set_interesting_files(None)
 
856
            merger.show_base = False
 
857
            merger.reprocess = False
 
858
            conflicts = merger.do_merge()
 
859
            merger.set_pending()
 
860
        finally:
 
861
            pb.finished()
 
862
        return conflicts
 
863
 
 
864
    @needs_read_lock
 
865
    def merge_modified(self):
 
866
        """Return a dictionary of files modified by a merge.
 
867
 
 
868
        The list is initialized by WorkingTree.set_merge_modified, which is 
 
869
        typically called after we make some automatic updates to the tree
 
870
        because of a merge.
 
871
 
 
872
        This returns a map of file_id->sha1, containing only files which are
 
873
        still in the working inventory and have that text hash.
 
874
        """
 
875
        try:
 
876
            hashfile = self._control_files.get('merge-hashes')
 
877
        except errors.NoSuchFile:
 
878
            return {}
 
879
        merge_hashes = {}
 
880
        try:
 
881
            if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
 
882
                raise errors.MergeModifiedFormatError()
 
883
        except StopIteration:
 
884
            raise errors.MergeModifiedFormatError()
 
885
        for s in RioReader(hashfile):
 
886
            # RioReader reads in Unicode, so convert file_ids back to utf8
 
887
            file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
 
888
            if file_id not in self.inventory:
 
889
                continue
 
890
            text_hash = s.get("hash")
 
891
            if text_hash == self.get_file_sha1(file_id):
 
892
                merge_hashes[file_id] = text_hash
 
893
        return merge_hashes
 
894
 
 
895
    @needs_write_lock
 
896
    def mkdir(self, path, file_id=None):
 
897
        """See MutableTree.mkdir()."""
 
898
        if file_id is None:
 
899
            file_id = generate_ids.gen_file_id(os.path.basename(path))
 
900
        os.mkdir(self.abspath(path))
 
901
        self.add(path, file_id, 'directory')
 
902
        return file_id
 
903
 
 
904
    def get_symlink_target(self, file_id):
 
905
        file_id = osutils.safe_file_id(file_id)
 
906
        return os.readlink(self.id2abspath(file_id))
 
907
 
 
908
    @needs_write_lock
 
909
    def subsume(self, other_tree):
 
910
        def add_children(inventory, entry):
 
911
            for child_entry in entry.children.values():
 
912
                inventory._byid[child_entry.file_id] = child_entry
 
913
                if child_entry.kind == 'directory':
 
914
                    add_children(inventory, child_entry)
 
915
        if other_tree.get_root_id() == self.get_root_id():
 
916
            raise errors.BadSubsumeSource(self, other_tree,
 
917
                                          'Trees have the same root')
 
918
        try:
 
919
            other_tree_path = self.relpath(other_tree.basedir)
 
920
        except errors.PathNotChild:
 
921
            raise errors.BadSubsumeSource(self, other_tree,
 
922
                'Tree is not contained by the other')
 
923
        new_root_parent = self.path2id(osutils.dirname(other_tree_path))
 
924
        if new_root_parent is None:
 
925
            raise errors.BadSubsumeSource(self, other_tree,
 
926
                'Parent directory is not versioned.')
 
927
        # We need to ensure that the result of a fetch will have a
 
928
        # versionedfile for the other_tree root, and only fetching into
 
929
        # RepositoryKnit2 guarantees that.
 
930
        if not self.branch.repository.supports_rich_root():
 
931
            raise errors.SubsumeTargetNeedsUpgrade(other_tree)
 
932
        other_tree.lock_tree_write()
 
933
        try:
 
934
            new_parents = other_tree.get_parent_ids()
 
935
            other_root = other_tree.inventory.root
 
936
            other_root.parent_id = new_root_parent
 
937
            other_root.name = osutils.basename(other_tree_path)
 
938
            self.inventory.add(other_root)
 
939
            add_children(self.inventory, other_root)
 
940
            self._write_inventory(self.inventory)
 
941
            # normally we don't want to fetch whole repositories, but i think
 
942
            # here we really do want to consolidate the whole thing.
 
943
            for parent_id in other_tree.get_parent_ids():
 
944
                self.branch.fetch(other_tree.branch, parent_id)
 
945
                self.add_parent_tree_id(parent_id)
 
946
        finally:
 
947
            other_tree.unlock()
 
948
        other_tree.bzrdir.retire_bzrdir()
 
949
 
 
950
    @needs_tree_write_lock
 
951
    def extract(self, file_id, format=None):
 
952
        """Extract a subtree from this tree.
 
953
        
 
954
        A new branch will be created, relative to the path for this tree.
 
955
        """
 
956
        self.flush()
 
957
        def mkdirs(path):
 
958
            segments = osutils.splitpath(path)
 
959
            transport = self.branch.bzrdir.root_transport
 
960
            for name in segments:
 
961
                transport = transport.clone(name)
 
962
                try:
 
963
                    transport.mkdir('.')
 
964
                except errors.FileExists:
 
965
                    pass
 
966
            return transport
 
967
            
 
968
        sub_path = self.id2path(file_id)
 
969
        branch_transport = mkdirs(sub_path)
 
970
        if format is None:
 
971
            format = bzrdir.format_registry.make_bzrdir('dirstate-with-subtree')
 
972
        try:
 
973
            branch_transport.mkdir('.')
 
974
        except errors.FileExists:
 
975
            pass
 
976
        branch_bzrdir = format.initialize_on_transport(branch_transport)
 
977
        try:
 
978
            repo = branch_bzrdir.find_repository()
 
979
        except errors.NoRepositoryPresent:
 
980
            repo = branch_bzrdir.create_repository()
 
981
            assert repo.supports_rich_root()
 
982
        else:
 
983
            if not repo.supports_rich_root():
 
984
                raise errors.RootNotRich()
 
985
        new_branch = branch_bzrdir.create_branch()
 
986
        new_branch.pull(self.branch)
 
987
        for parent_id in self.get_parent_ids():
 
988
            new_branch.fetch(self.branch, parent_id)
 
989
        tree_transport = self.bzrdir.root_transport.clone(sub_path)
 
990
        if tree_transport.base != branch_transport.base:
 
991
            tree_bzrdir = format.initialize_on_transport(tree_transport)
 
992
            branch.BranchReferenceFormat().initialize(tree_bzrdir, new_branch)
 
993
        else:
 
994
            tree_bzrdir = branch_bzrdir
 
995
        wt = tree_bzrdir.create_workingtree(NULL_REVISION)
 
996
        wt.set_parent_ids(self.get_parent_ids())
 
997
        my_inv = self.inventory
 
998
        child_inv = Inventory(root_id=None)
 
999
        new_root = my_inv[file_id]
 
1000
        my_inv.remove_recursive_id(file_id)
 
1001
        new_root.parent_id = None
 
1002
        child_inv.add(new_root)
 
1003
        self._write_inventory(my_inv)
 
1004
        wt._write_inventory(child_inv)
 
1005
        return wt
 
1006
 
 
1007
    def _serialize(self, inventory, out_file):
 
1008
        xml5.serializer_v5.write_inventory(self._inventory, out_file)
 
1009
 
 
1010
    def _deserialize(selt, in_file):
 
1011
        return xml5.serializer_v5.read_inventory(in_file)
 
1012
 
 
1013
    def flush(self):
 
1014
        """Write the in memory inventory to disk."""
 
1015
        # TODO: Maybe this should only write on dirty ?
 
1016
        if self._control_files._lock_mode != 'w':
 
1017
            raise errors.NotWriteLocked(self)
 
1018
        sio = StringIO()
 
1019
        self._serialize(self._inventory, sio)
 
1020
        sio.seek(0)
 
1021
        self._control_files.put('inventory', sio)
 
1022
        self._inventory_is_modified = False
 
1023
 
 
1024
    def _kind(self, relpath):
 
1025
        return osutils.file_kind(self.abspath(relpath))
 
1026
 
 
1027
    def list_files(self, include_root=False):
 
1028
        """Recursively list all files as (path, class, kind, id, entry).
 
1029
 
 
1030
        Lists, but does not descend into unversioned directories.
 
1031
 
 
1032
        This does not include files that have been deleted in this
 
1033
        tree.
 
1034
 
 
1035
        Skips the control directory.
 
1036
        """
 
1037
        # list_files is an iterator, so @needs_read_lock doesn't work properly
 
1038
        # with it. So callers should be careful to always read_lock the tree.
 
1039
        if not self.is_locked():
 
1040
            raise errors.ObjectNotLocked(self)
 
1041
 
 
1042
        inv = self.inventory
 
1043
        if include_root is True:
 
1044
            yield ('', 'V', 'directory', inv.root.file_id, inv.root)
 
1045
        # Convert these into local objects to save lookup times
 
1046
        pathjoin = osutils.pathjoin
 
1047
        file_kind = self._kind
 
1048
 
 
1049
        # transport.base ends in a slash, we want the piece
 
1050
        # between the last two slashes
 
1051
        transport_base_dir = self.bzrdir.transport.base.rsplit('/', 2)[1]
 
1052
 
 
1053
        fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
 
1054
 
 
1055
        # directory file_id, relative path, absolute path, reverse sorted children
 
1056
        children = os.listdir(self.basedir)
 
1057
        children.sort()
 
1058
        # jam 20060527 The kernel sized tree seems equivalent whether we 
 
1059
        # use a deque and popleft to keep them sorted, or if we use a plain
 
1060
        # list and just reverse() them.
 
1061
        children = collections.deque(children)
 
1062
        stack = [(inv.root.file_id, u'', self.basedir, children)]
 
1063
        while stack:
 
1064
            from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
 
1065
 
 
1066
            while children:
 
1067
                f = children.popleft()
 
1068
                ## TODO: If we find a subdirectory with its own .bzr
 
1069
                ## directory, then that is a separate tree and we
 
1070
                ## should exclude it.
 
1071
 
 
1072
                # the bzrdir for this tree
 
1073
                if transport_base_dir == f:
 
1074
                    continue
 
1075
 
 
1076
                # we know that from_dir_relpath and from_dir_abspath never end in a slash
 
1077
                # and 'f' doesn't begin with one, we can do a string op, rather
 
1078
                # than the checks of pathjoin(), all relative paths will have an extra slash
 
1079
                # at the beginning
 
1080
                fp = from_dir_relpath + '/' + f
 
1081
 
 
1082
                # absolute path
 
1083
                fap = from_dir_abspath + '/' + f
 
1084
                
 
1085
                f_ie = inv.get_child(from_dir_id, f)
 
1086
                if f_ie:
 
1087
                    c = 'V'
 
1088
                elif self.is_ignored(fp[1:]):
 
1089
                    c = 'I'
 
1090
                else:
 
1091
                    # we may not have found this file, because of a unicode issue
 
1092
                    f_norm, can_access = osutils.normalized_filename(f)
 
1093
                    if f == f_norm or not can_access:
 
1094
                        # No change, so treat this file normally
 
1095
                        c = '?'
 
1096
                    else:
 
1097
                        # this file can be accessed by a normalized path
 
1098
                        # check again if it is versioned
 
1099
                        # these lines are repeated here for performance
 
1100
                        f = f_norm
 
1101
                        fp = from_dir_relpath + '/' + f
 
1102
                        fap = from_dir_abspath + '/' + f
 
1103
                        f_ie = inv.get_child(from_dir_id, f)
 
1104
                        if f_ie:
 
1105
                            c = 'V'
 
1106
                        elif self.is_ignored(fp[1:]):
 
1107
                            c = 'I'
 
1108
                        else:
 
1109
                            c = '?'
 
1110
 
 
1111
                fk = file_kind(fap)
 
1112
 
 
1113
                # make a last minute entry
 
1114
                if f_ie:
 
1115
                    yield fp[1:], c, fk, f_ie.file_id, f_ie
 
1116
                else:
 
1117
                    try:
 
1118
                        yield fp[1:], c, fk, None, fk_entries[fk]()
 
1119
                    except KeyError:
 
1120
                        yield fp[1:], c, fk, None, TreeEntry()
 
1121
                    continue
 
1122
                
 
1123
                if fk != 'directory':
 
1124
                    continue
 
1125
 
 
1126
                # But do this child first
 
1127
                new_children = os.listdir(fap)
 
1128
                new_children.sort()
 
1129
                new_children = collections.deque(new_children)
 
1130
                stack.append((f_ie.file_id, fp, fap, new_children))
 
1131
                # Break out of inner loop,
 
1132
                # so that we start outer loop with child
 
1133
                break
 
1134
            else:
 
1135
                # if we finished all children, pop it off the stack
 
1136
                stack.pop()
 
1137
 
 
1138
    @needs_tree_write_lock
 
1139
    def move(self, from_paths, to_dir=None, after=False, **kwargs):
 
1140
        """Rename files.
 
1141
 
 
1142
        to_dir must exist in the inventory.
 
1143
 
 
1144
        If to_dir exists and is a directory, the files are moved into
 
1145
        it, keeping their old names.  
 
1146
 
 
1147
        Note that to_dir is only the last component of the new name;
 
1148
        this doesn't change the directory.
 
1149
 
 
1150
        For each entry in from_paths the move mode will be determined
 
1151
        independently.
 
1152
 
 
1153
        The first mode moves the file in the filesystem and updates the
 
1154
        inventory. The second mode only updates the inventory without
 
1155
        touching the file on the filesystem. This is the new mode introduced
 
1156
        in version 0.15.
 
1157
 
 
1158
        move uses the second mode if 'after == True' and the target is not
 
1159
        versioned but present in the working tree.
 
1160
 
 
1161
        move uses the second mode if 'after == False' and the source is
 
1162
        versioned but no longer in the working tree, and the target is not
 
1163
        versioned but present in the working tree.
 
1164
 
 
1165
        move uses the first mode if 'after == False' and the source is
 
1166
        versioned and present in the working tree, and the target is not
 
1167
        versioned and not present in the working tree.
 
1168
 
 
1169
        Everything else results in an error.
 
1170
 
 
1171
        This returns a list of (from_path, to_path) pairs for each
 
1172
        entry that is moved.
 
1173
        """
 
1174
        rename_entries = []
 
1175
        rename_tuples = []
 
1176
 
 
1177
        # check for deprecated use of signature
 
1178
        if to_dir is None:
 
1179
            to_dir = kwargs.get('to_name', None)
 
1180
            if to_dir is None:
 
1181
                raise TypeError('You must supply a target directory')
 
1182
            else:
 
1183
                symbol_versioning.warn('The parameter to_name was deprecated'
 
1184
                                       ' in version 0.13. Use to_dir instead',
 
1185
                                       DeprecationWarning)
 
1186
 
 
1187
        # check destination directory
 
1188
        assert not isinstance(from_paths, basestring)
 
1189
        inv = self.inventory
 
1190
        to_abs = self.abspath(to_dir)
 
1191
        if not isdir(to_abs):
 
1192
            raise errors.BzrMoveFailedError('',to_dir,
 
1193
                errors.NotADirectory(to_abs))
 
1194
        if not self.has_filename(to_dir):
 
1195
            raise errors.BzrMoveFailedError('',to_dir,
 
1196
                errors.NotInWorkingDirectory(to_dir))
 
1197
        to_dir_id = inv.path2id(to_dir)
 
1198
        if to_dir_id is None:
 
1199
            raise errors.BzrMoveFailedError('',to_dir,
 
1200
                errors.NotVersionedError(path=str(to_dir)))
 
1201
 
 
1202
        to_dir_ie = inv[to_dir_id]
 
1203
        if to_dir_ie.kind != 'directory':
 
1204
            raise errors.BzrMoveFailedError('',to_dir,
 
1205
                errors.NotADirectory(to_abs))
 
1206
 
 
1207
        # create rename entries and tuples
 
1208
        for from_rel in from_paths:
 
1209
            from_tail = splitpath(from_rel)[-1]
 
1210
            from_id = inv.path2id(from_rel)
 
1211
            if from_id is None:
 
1212
                raise errors.BzrMoveFailedError(from_rel,to_dir,
 
1213
                    errors.NotVersionedError(path=str(from_rel)))
 
1214
 
 
1215
            from_entry = inv[from_id]
 
1216
            from_parent_id = from_entry.parent_id
 
1217
            to_rel = pathjoin(to_dir, from_tail)
 
1218
            rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
 
1219
                                         from_id=from_id,
 
1220
                                         from_tail=from_tail,
 
1221
                                         from_parent_id=from_parent_id,
 
1222
                                         to_rel=to_rel, to_tail=from_tail,
 
1223
                                         to_parent_id=to_dir_id)
 
1224
            rename_entries.append(rename_entry)
 
1225
            rename_tuples.append((from_rel, to_rel))
 
1226
 
 
1227
        # determine which move mode to use. checks also for movability
 
1228
        rename_entries = self._determine_mv_mode(rename_entries, after)
 
1229
 
 
1230
        original_modified = self._inventory_is_modified
 
1231
        try:
 
1232
            if len(from_paths):
 
1233
                self._inventory_is_modified = True
 
1234
            self._move(rename_entries)
 
1235
        except:
 
1236
            # restore the inventory on error
 
1237
            self._inventory_is_modified = original_modified
 
1238
            raise
 
1239
        self._write_inventory(inv)
 
1240
        return rename_tuples
 
1241
 
 
1242
    def _determine_mv_mode(self, rename_entries, after=False):
 
1243
        """Determines for each from-to pair if both inventory and working tree
 
1244
        or only the inventory has to be changed.
 
1245
 
 
1246
        Also does basic plausability tests.
 
1247
        """
 
1248
        inv = self.inventory
 
1249
 
 
1250
        for rename_entry in rename_entries:
 
1251
            # store to local variables for easier reference
 
1252
            from_rel = rename_entry.from_rel
 
1253
            from_id = rename_entry.from_id
 
1254
            to_rel = rename_entry.to_rel
 
1255
            to_id = inv.path2id(to_rel)
 
1256
            only_change_inv = False
 
1257
 
 
1258
            # check the inventory for source and destination
 
1259
            if from_id is None:
 
1260
                raise errors.BzrMoveFailedError(from_rel,to_rel,
 
1261
                    errors.NotVersionedError(path=str(from_rel)))
 
1262
            if to_id is not None:
 
1263
                raise errors.BzrMoveFailedError(from_rel,to_rel,
 
1264
                    errors.AlreadyVersionedError(path=str(to_rel)))
 
1265
 
 
1266
            # try to determine the mode for rename (only change inv or change
 
1267
            # inv and file system)
 
1268
            if after:
 
1269
                if not self.has_filename(to_rel):
 
1270
                    raise errors.BzrMoveFailedError(from_id,to_rel,
 
1271
                        errors.NoSuchFile(path=str(to_rel),
 
1272
                        extra="New file has not been created yet"))
 
1273
                only_change_inv = True
 
1274
            elif not self.has_filename(from_rel) and self.has_filename(to_rel):
 
1275
                only_change_inv = True
 
1276
            elif self.has_filename(from_rel) and not self.has_filename(to_rel):
 
1277
                only_change_inv = False
 
1278
            else:
 
1279
                # something is wrong, so lets determine what exactly
 
1280
                if not self.has_filename(from_rel) and \
 
1281
                   not self.has_filename(to_rel):
 
1282
                    raise errors.BzrRenameFailedError(from_rel,to_rel,
 
1283
                        errors.PathsDoNotExist(paths=(str(from_rel),
 
1284
                        str(to_rel))))
 
1285
                else:
 
1286
                    raise errors.RenameFailedFilesExist(from_rel, to_rel,
 
1287
                        extra="(Use --after to update the Bazaar id)")
 
1288
            rename_entry.only_change_inv = only_change_inv
 
1289
        return rename_entries
 
1290
 
 
1291
    def _move(self, rename_entries):
 
1292
        """Moves a list of files.
 
1293
 
 
1294
        Depending on the value of the flag 'only_change_inv', the
 
1295
        file will be moved on the file system or not.
 
1296
        """
 
1297
        inv = self.inventory
 
1298
        moved = []
 
1299
 
 
1300
        for entry in rename_entries:
 
1301
            try:
 
1302
                self._move_entry(entry)
 
1303
            except:
 
1304
                self._rollback_move(moved)
 
1305
                raise
 
1306
            moved.append(entry)
 
1307
 
 
1308
    def _rollback_move(self, moved):
 
1309
        """Try to rollback a previous move in case of an filesystem error."""
 
1310
        inv = self.inventory
 
1311
        for entry in moved:
 
1312
            try:
 
1313
                self._move_entry(_RenameEntry(entry.to_rel, entry.from_id,
 
1314
                    entry.to_tail, entry.to_parent_id, entry.from_rel,
 
1315
                    entry.from_tail, entry.from_parent_id,
 
1316
                    entry.only_change_inv))
 
1317
            except errors.BzrMoveFailedError, e:
 
1318
                raise errors.BzrMoveFailedError( '', '', "Rollback failed."
 
1319
                        " The working tree is in an inconsistent state."
 
1320
                        " Please consider doing a 'bzr revert'."
 
1321
                        " Error message is: %s" % e)
 
1322
 
 
1323
    def _move_entry(self, entry):
 
1324
        inv = self.inventory
 
1325
        from_rel_abs = self.abspath(entry.from_rel)
 
1326
        to_rel_abs = self.abspath(entry.to_rel)
 
1327
        if from_rel_abs == to_rel_abs:
 
1328
            raise errors.BzrMoveFailedError(entry.from_rel, entry.to_rel,
 
1329
                "Source and target are identical.")
 
1330
 
 
1331
        if not entry.only_change_inv:
 
1332
            try:
 
1333
                osutils.rename(from_rel_abs, to_rel_abs)
 
1334
            except OSError, e:
 
1335
                raise errors.BzrMoveFailedError(entry.from_rel,
 
1336
                    entry.to_rel, e[1])
 
1337
        inv.rename(entry.from_id, entry.to_parent_id, entry.to_tail)
 
1338
 
 
1339
    @needs_tree_write_lock
 
1340
    def rename_one(self, from_rel, to_rel, after=False):
 
1341
        """Rename one file.
 
1342
 
 
1343
        This can change the directory or the filename or both.
 
1344
 
 
1345
        rename_one has several 'modes' to work. First, it can rename a physical
 
1346
        file and change the file_id. That is the normal mode. Second, it can
 
1347
        only change the file_id without touching any physical file. This is
 
1348
        the new mode introduced in version 0.15.
 
1349
 
 
1350
        rename_one uses the second mode if 'after == True' and 'to_rel' is not
 
1351
        versioned but present in the working tree.
 
1352
 
 
1353
        rename_one uses the second mode if 'after == False' and 'from_rel' is
 
1354
        versioned but no longer in the working tree, and 'to_rel' is not
 
1355
        versioned but present in the working tree.
 
1356
 
 
1357
        rename_one uses the first mode if 'after == False' and 'from_rel' is
 
1358
        versioned and present in the working tree, and 'to_rel' is not
 
1359
        versioned and not present in the working tree.
 
1360
 
 
1361
        Everything else results in an error.
 
1362
        """
 
1363
        inv = self.inventory
 
1364
        rename_entries = []
 
1365
 
 
1366
        # create rename entries and tuples
 
1367
        from_tail = splitpath(from_rel)[-1]
 
1368
        from_id = inv.path2id(from_rel)
 
1369
        if from_id is None:
 
1370
            raise errors.BzrRenameFailedError(from_rel,to_rel,
 
1371
                errors.NotVersionedError(path=str(from_rel)))
 
1372
        from_entry = inv[from_id]
 
1373
        from_parent_id = from_entry.parent_id
 
1374
        to_dir, to_tail = os.path.split(to_rel)
 
1375
        to_dir_id = inv.path2id(to_dir)
 
1376
        rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
 
1377
                                     from_id=from_id,
 
1378
                                     from_tail=from_tail,
 
1379
                                     from_parent_id=from_parent_id,
 
1380
                                     to_rel=to_rel, to_tail=to_tail,
 
1381
                                     to_parent_id=to_dir_id)
 
1382
        rename_entries.append(rename_entry)
 
1383
 
 
1384
        # determine which move mode to use. checks also for movability
 
1385
        rename_entries = self._determine_mv_mode(rename_entries, after)
 
1386
 
 
1387
        # check if the target changed directory and if the target directory is
 
1388
        # versioned
 
1389
        if to_dir_id is None:
 
1390
            raise errors.BzrMoveFailedError(from_rel,to_rel,
 
1391
                errors.NotVersionedError(path=str(to_dir)))
 
1392
 
 
1393
        # all checks done. now we can continue with our actual work
 
1394
        mutter('rename_one:\n'
 
1395
               '  from_id   {%s}\n'
 
1396
               '  from_rel: %r\n'
 
1397
               '  to_rel:   %r\n'
 
1398
               '  to_dir    %r\n'
 
1399
               '  to_dir_id {%s}\n',
 
1400
               from_id, from_rel, to_rel, to_dir, to_dir_id)
 
1401
 
 
1402
        self._move(rename_entries)
 
1403
        self._write_inventory(inv)
 
1404
 
 
1405
    class _RenameEntry(object):
 
1406
        def __init__(self, from_rel, from_id, from_tail, from_parent_id,
 
1407
                     to_rel, to_tail, to_parent_id, only_change_inv=False):
 
1408
            self.from_rel = from_rel
 
1409
            self.from_id = from_id
 
1410
            self.from_tail = from_tail
 
1411
            self.from_parent_id = from_parent_id
 
1412
            self.to_rel = to_rel
 
1413
            self.to_tail = to_tail
 
1414
            self.to_parent_id = to_parent_id
 
1415
            self.only_change_inv = only_change_inv
 
1416
 
 
1417
    @needs_read_lock
 
1418
    def unknowns(self):
 
1419
        """Return all unknown files.
 
1420
 
 
1421
        These are files in the working directory that are not versioned or
 
1422
        control files or ignored.
 
1423
        """
 
1424
        # force the extras method to be fully executed before returning, to 
 
1425
        # prevent race conditions with the lock
 
1426
        return iter(
 
1427
            [subp for subp in self.extras() if not self.is_ignored(subp)])
 
1428
 
 
1429
    def _warn_deprecated_format(self):
 
1430
        ui.ui_factory.recommend_upgrade(
 
1431
            self._format.get_format_description(),
 
1432
            self.basedir)
 
1433
 
 
1434
    @needs_tree_write_lock
 
1435
    def unversion(self, file_ids):
 
1436
        """Remove the file ids in file_ids from the current versioned set.
 
1437
 
 
1438
        When a file_id is unversioned, all of its children are automatically
 
1439
        unversioned.
 
1440
 
 
1441
        :param file_ids: The file ids to stop versioning.
 
1442
        :raises: NoSuchId if any fileid is not currently versioned.
 
1443
        """
 
1444
        for file_id in file_ids:
 
1445
            file_id = osutils.safe_file_id(file_id)
 
1446
            if self._inventory.has_id(file_id):
 
1447
                self._inventory.remove_recursive_id(file_id)
 
1448
            else:
 
1449
                raise errors.NoSuchId(self, file_id)
 
1450
        if len(file_ids):
 
1451
            # in the future this should just set a dirty bit to wait for the 
 
1452
            # final unlock. However, until all methods of workingtree start
 
1453
            # with the current in -memory inventory rather than triggering 
 
1454
            # a read, it is more complex - we need to teach read_inventory
 
1455
            # to know when to read, and when to not read first... and possibly
 
1456
            # to save first when the in memory one may be corrupted.
 
1457
            # so for now, we just only write it if it is indeed dirty.
 
1458
            # - RBC 20060907
 
1459
            self._write_inventory(self._inventory)
 
1460
    
 
1461
    @deprecated_method(zero_eight)
 
1462
    def iter_conflicts(self):
 
1463
        """List all files in the tree that have text or content conflicts.
 
1464
        DEPRECATED.  Use conflicts instead."""
 
1465
        return self._iter_conflicts()
 
1466
 
 
1467
    def _iter_conflicts(self):
 
1468
        conflicted = set()
 
1469
        for info in self.list_files():
 
1470
            path = info[0]
 
1471
            stem = get_conflicted_stem(path)
 
1472
            if stem is None:
 
1473
                continue
 
1474
            if stem not in conflicted:
 
1475
                conflicted.add(stem)
 
1476
                yield stem
 
1477
 
 
1478
    @needs_write_lock
 
1479
    def pull(self, source, overwrite=False, stop_revision=None,
 
1480
             change_reporter=None):
 
1481
        top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1482
        source.lock_read()
 
1483
        try:
 
1484
            pp = ProgressPhase("Pull phase", 2, top_pb)
 
1485
            pp.next_phase()
 
1486
            old_revision_info = self.branch.last_revision_info()
 
1487
            basis_tree = self.basis_tree()
 
1488
            count = self.branch.pull(source, overwrite, stop_revision)
 
1489
            new_revision_info = self.branch.last_revision_info()
 
1490
            if new_revision_info != old_revision_info:
 
1491
                pp.next_phase()
 
1492
                repository = self.branch.repository
 
1493
                pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1494
                basis_tree.lock_read()
 
1495
                try:
 
1496
                    new_basis_tree = self.branch.basis_tree()
 
1497
                    merge.merge_inner(
 
1498
                                self.branch,
 
1499
                                new_basis_tree,
 
1500
                                basis_tree,
 
1501
                                this_tree=self,
 
1502
                                pb=pb,
 
1503
                                change_reporter=change_reporter)
 
1504
                    if (basis_tree.inventory.root is None and
 
1505
                        new_basis_tree.inventory.root is not None):
 
1506
                        self.set_root_id(new_basis_tree.inventory.root.file_id)
 
1507
                finally:
 
1508
                    pb.finished()
 
1509
                    basis_tree.unlock()
 
1510
                # TODO - dedup parents list with things merged by pull ?
 
1511
                # reuse the revisiontree we merged against to set the new
 
1512
                # tree data.
 
1513
                parent_trees = [(self.branch.last_revision(), new_basis_tree)]
 
1514
                # we have to pull the merge trees out again, because 
 
1515
                # merge_inner has set the ids. - this corner is not yet 
 
1516
                # layered well enough to prevent double handling.
 
1517
                # XXX TODO: Fix the double handling: telling the tree about
 
1518
                # the already known parent data is wasteful.
 
1519
                merges = self.get_parent_ids()[1:]
 
1520
                parent_trees.extend([
 
1521
                    (parent, repository.revision_tree(parent)) for
 
1522
                     parent in merges])
 
1523
                self.set_parent_trees(parent_trees)
 
1524
            return count
 
1525
        finally:
 
1526
            source.unlock()
 
1527
            top_pb.finished()
 
1528
 
 
1529
    @needs_write_lock
 
1530
    def put_file_bytes_non_atomic(self, file_id, bytes):
 
1531
        """See MutableTree.put_file_bytes_non_atomic."""
 
1532
        file_id = osutils.safe_file_id(file_id)
 
1533
        stream = file(self.id2abspath(file_id), 'wb')
 
1534
        try:
 
1535
            stream.write(bytes)
 
1536
        finally:
 
1537
            stream.close()
 
1538
        # TODO: update the hashcache here ?
 
1539
 
 
1540
    def extras(self):
 
1541
        """Yield all unversioned files in this WorkingTree.
 
1542
 
 
1543
        If there are any unversioned directories then only the directory is
 
1544
        returned, not all its children.  But if there are unversioned files
 
1545
        under a versioned subdirectory, they are returned.
 
1546
 
 
1547
        Currently returned depth-first, sorted by name within directories.
 
1548
        This is the same order used by 'osutils.walkdirs'.
 
1549
        """
 
1550
        ## TODO: Work from given directory downwards
 
1551
        for path, dir_entry in self.inventory.directories():
 
1552
            # mutter("search for unknowns in %r", path)
 
1553
            dirabs = self.abspath(path)
 
1554
            if not isdir(dirabs):
 
1555
                # e.g. directory deleted
 
1556
                continue
 
1557
 
 
1558
            fl = []
 
1559
            for subf in os.listdir(dirabs):
 
1560
                if subf == '.bzr':
 
1561
                    continue
 
1562
                if subf not in dir_entry.children:
 
1563
                    subf_norm, can_access = osutils.normalized_filename(subf)
 
1564
                    if subf_norm != subf and can_access:
 
1565
                        if subf_norm not in dir_entry.children:
 
1566
                            fl.append(subf_norm)
 
1567
                    else:
 
1568
                        fl.append(subf)
 
1569
            
 
1570
            fl.sort()
 
1571
            for subf in fl:
 
1572
                subp = pathjoin(path, subf)
 
1573
                yield subp
 
1574
 
 
1575
    def ignored_files(self):
 
1576
        """Yield list of PATH, IGNORE_PATTERN"""
 
1577
        for subp in self.extras():
 
1578
            pat = self.is_ignored(subp)
 
1579
            if pat is not None:
 
1580
                yield subp, pat
 
1581
 
 
1582
    def get_ignore_list(self):
 
1583
        """Return list of ignore patterns.
 
1584
 
 
1585
        Cached in the Tree object after the first call.
 
1586
        """
 
1587
        ignoreset = getattr(self, '_ignoreset', None)
 
1588
        if ignoreset is not None:
 
1589
            return ignoreset
 
1590
 
 
1591
        ignore_globs = set(bzrlib.DEFAULT_IGNORE)
 
1592
        ignore_globs.update(ignores.get_runtime_ignores())
 
1593
        ignore_globs.update(ignores.get_user_ignores())
 
1594
        if self.has_filename(bzrlib.IGNORE_FILENAME):
 
1595
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
 
1596
            try:
 
1597
                ignore_globs.update(ignores.parse_ignore_file(f))
 
1598
            finally:
 
1599
                f.close()
 
1600
        self._ignoreset = ignore_globs
 
1601
        return ignore_globs
 
1602
 
 
1603
    def _flush_ignore_list_cache(self):
 
1604
        """Resets the cached ignore list to force a cache rebuild."""
 
1605
        self._ignoreset = None
 
1606
        self._ignoreglobster = None
 
1607
 
 
1608
    def is_ignored(self, filename):
 
1609
        r"""Check whether the filename matches an ignore pattern.
 
1610
 
 
1611
        Patterns containing '/' or '\' need to match the whole path;
 
1612
        others match against only the last component.
 
1613
 
 
1614
        If the file is ignored, returns the pattern which caused it to
 
1615
        be ignored, otherwise None.  So this can simply be used as a
 
1616
        boolean if desired."""
 
1617
        if getattr(self, '_ignoreglobster', None) is None:
 
1618
            self._ignoreglobster = globbing.Globster(self.get_ignore_list())
 
1619
        return self._ignoreglobster.match(filename)
 
1620
 
 
1621
    def kind(self, file_id):
 
1622
        return file_kind(self.id2abspath(file_id))
 
1623
 
 
1624
    def _comparison_data(self, entry, path):
 
1625
        abspath = self.abspath(path)
 
1626
        try:
 
1627
            stat_value = os.lstat(abspath)
 
1628
        except OSError, e:
 
1629
            if getattr(e, 'errno', None) == errno.ENOENT:
 
1630
                stat_value = None
 
1631
                kind = None
 
1632
                executable = False
 
1633
            else:
 
1634
                raise
 
1635
        else:
 
1636
            mode = stat_value.st_mode
 
1637
            kind = osutils.file_kind_from_stat_mode(mode)
 
1638
            if not supports_executable():
 
1639
                executable = entry.executable
 
1640
            else:
 
1641
                executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
1642
        return kind, executable, stat_value
 
1643
 
 
1644
    def _file_size(self, entry, stat_value):
 
1645
        return stat_value.st_size
 
1646
 
 
1647
    def last_revision(self):
 
1648
        """Return the last revision of the branch for this tree.
 
1649
 
 
1650
        This format tree does not support a separate marker for last-revision
 
1651
        compared to the branch.
 
1652
 
 
1653
        See MutableTree.last_revision
 
1654
        """
 
1655
        return self._last_revision()
 
1656
 
 
1657
    @needs_read_lock
 
1658
    def _last_revision(self):
 
1659
        """helper for get_parent_ids."""
 
1660
        return self.branch.last_revision()
 
1661
 
 
1662
    def is_locked(self):
 
1663
        return self._control_files.is_locked()
 
1664
 
 
1665
    def _must_be_locked(self):
 
1666
        if not self.is_locked():
 
1667
            raise errors.ObjectNotLocked(self)
 
1668
 
 
1669
    def lock_read(self):
 
1670
        """See Branch.lock_read, and WorkingTree.unlock."""
 
1671
        if not self.is_locked():
 
1672
            self._reset_data()
 
1673
        self.branch.lock_read()
 
1674
        try:
 
1675
            return self._control_files.lock_read()
 
1676
        except:
 
1677
            self.branch.unlock()
 
1678
            raise
 
1679
 
 
1680
    def lock_tree_write(self):
 
1681
        """See MutableTree.lock_tree_write, and WorkingTree.unlock."""
 
1682
        if not self.is_locked():
 
1683
            self._reset_data()
 
1684
        self.branch.lock_read()
 
1685
        try:
 
1686
            return self._control_files.lock_write()
 
1687
        except:
 
1688
            self.branch.unlock()
 
1689
            raise
 
1690
 
 
1691
    def lock_write(self):
 
1692
        """See MutableTree.lock_write, and WorkingTree.unlock."""
 
1693
        if not self.is_locked():
 
1694
            self._reset_data()
 
1695
        self.branch.lock_write()
 
1696
        try:
 
1697
            return self._control_files.lock_write()
 
1698
        except:
 
1699
            self.branch.unlock()
 
1700
            raise
 
1701
 
 
1702
    def get_physical_lock_status(self):
 
1703
        return self._control_files.get_physical_lock_status()
 
1704
 
 
1705
    def _basis_inventory_name(self):
 
1706
        return 'basis-inventory-cache'
 
1707
 
 
1708
    def _reset_data(self):
 
1709
        """Reset transient data that cannot be revalidated."""
 
1710
        self._inventory_is_modified = False
 
1711
        result = self._deserialize(self._control_files.get('inventory'))
 
1712
        self._set_inventory(result, dirty=False)
 
1713
 
 
1714
    @needs_tree_write_lock
 
1715
    def set_last_revision(self, new_revision):
 
1716
        """Change the last revision in the working tree."""
 
1717
        new_revision = osutils.safe_revision_id(new_revision)
 
1718
        if self._change_last_revision(new_revision):
 
1719
            self._cache_basis_inventory(new_revision)
 
1720
 
 
1721
    def _change_last_revision(self, new_revision):
 
1722
        """Template method part of set_last_revision to perform the change.
 
1723
        
 
1724
        This is used to allow WorkingTree3 instances to not affect branch
 
1725
        when their last revision is set.
 
1726
        """
 
1727
        if new_revision is None:
 
1728
            self.branch.set_revision_history([])
 
1729
            return False
 
1730
        try:
 
1731
            self.branch.generate_revision_history(new_revision)
 
1732
        except errors.NoSuchRevision:
 
1733
            # not present in the repo - dont try to set it deeper than the tip
 
1734
            self.branch.set_revision_history([new_revision])
 
1735
        return True
 
1736
 
 
1737
    def _write_basis_inventory(self, xml):
 
1738
        """Write the basis inventory XML to the basis-inventory file"""
 
1739
        assert isinstance(xml, str), 'serialised xml must be bytestring.'
 
1740
        path = self._basis_inventory_name()
 
1741
        sio = StringIO(xml)
 
1742
        self._control_files.put(path, sio)
 
1743
 
 
1744
    def _create_basis_xml_from_inventory(self, revision_id, inventory):
 
1745
        """Create the text that will be saved in basis-inventory"""
 
1746
        # TODO: jam 20070209 This should be redundant, as the revision_id
 
1747
        #       as all callers should have already converted the revision_id to
 
1748
        #       utf8
 
1749
        inventory.revision_id = osutils.safe_revision_id(revision_id)
 
1750
        return xml7.serializer_v7.write_inventory_to_string(inventory)
 
1751
 
 
1752
    def _cache_basis_inventory(self, new_revision):
 
1753
        """Cache new_revision as the basis inventory."""
 
1754
        # TODO: this should allow the ready-to-use inventory to be passed in,
 
1755
        # as commit already has that ready-to-use [while the format is the
 
1756
        # same, that is].
 
1757
        try:
 
1758
            # this double handles the inventory - unpack and repack - 
 
1759
            # but is easier to understand. We can/should put a conditional
 
1760
            # in here based on whether the inventory is in the latest format
 
1761
            # - perhaps we should repack all inventories on a repository
 
1762
            # upgrade ?
 
1763
            # the fast path is to copy the raw xml from the repository. If the
 
1764
            # xml contains 'revision_id="', then we assume the right 
 
1765
            # revision_id is set. We must check for this full string, because a
 
1766
            # root node id can legitimately look like 'revision_id' but cannot
 
1767
            # contain a '"'.
 
1768
            xml = self.branch.repository.get_inventory_xml(new_revision)
 
1769
            firstline = xml.split('\n', 1)[0]
 
1770
            if (not 'revision_id="' in firstline or 
 
1771
                'format="7"' not in firstline):
 
1772
                inv = self.branch.repository.deserialise_inventory(
 
1773
                    new_revision, xml)
 
1774
                xml = self._create_basis_xml_from_inventory(new_revision, inv)
 
1775
            self._write_basis_inventory(xml)
 
1776
        except (errors.NoSuchRevision, errors.RevisionNotPresent):
 
1777
            pass
 
1778
 
 
1779
    def read_basis_inventory(self):
 
1780
        """Read the cached basis inventory."""
 
1781
        path = self._basis_inventory_name()
 
1782
        return self._control_files.get(path).read()
 
1783
        
 
1784
    @needs_read_lock
 
1785
    def read_working_inventory(self):
 
1786
        """Read the working inventory.
 
1787
        
 
1788
        :raises errors.InventoryModified: read_working_inventory will fail
 
1789
            when the current in memory inventory has been modified.
 
1790
        """
 
1791
        # conceptually this should be an implementation detail of the tree. 
 
1792
        # XXX: Deprecate this.
 
1793
        # ElementTree does its own conversion from UTF-8, so open in
 
1794
        # binary.
 
1795
        if self._inventory_is_modified:
 
1796
            raise errors.InventoryModified(self)
 
1797
        result = self._deserialize(self._control_files.get('inventory'))
 
1798
        self._set_inventory(result, dirty=False)
 
1799
        return result
 
1800
 
 
1801
    @needs_tree_write_lock
 
1802
    def remove(self, files, verbose=False, to_file=None):
 
1803
        """Remove nominated files from the working inventory..
 
1804
 
 
1805
        This does not remove their text.  This does not run on XXX on what? RBC
 
1806
 
 
1807
        TODO: Refuse to remove modified files unless --force is given?
 
1808
 
 
1809
        TODO: Do something useful with directories.
 
1810
 
 
1811
        TODO: Should this remove the text or not?  Tough call; not
 
1812
        removing may be useful and the user can just use use rm, and
 
1813
        is the opposite of add.  Removing it is consistent with most
 
1814
        other tools.  Maybe an option.
 
1815
        """
 
1816
        ## TODO: Normalize names
 
1817
        ## TODO: Remove nested loops; better scalability
 
1818
        if isinstance(files, basestring):
 
1819
            files = [files]
 
1820
 
 
1821
        inv = self.inventory
 
1822
 
 
1823
        # do this before any modifications
 
1824
        for f in files:
 
1825
            fid = inv.path2id(f)
 
1826
            if not fid:
 
1827
                note("%s is not versioned."%f)
 
1828
            else:
 
1829
                if verbose:
 
1830
                    # having remove it, it must be either ignored or unknown
 
1831
                    if self.is_ignored(f):
 
1832
                        new_status = 'I'
 
1833
                    else:
 
1834
                        new_status = '?'
 
1835
                    textui.show_status(new_status, inv[fid].kind, f,
 
1836
                                       to_file=to_file)
 
1837
                del inv[fid]
 
1838
 
 
1839
        self._write_inventory(inv)
 
1840
 
 
1841
    @needs_tree_write_lock
 
1842
    def revert(self, filenames, old_tree=None, backups=True, 
 
1843
               pb=DummyProgress(), report_changes=False):
 
1844
        from bzrlib.conflicts import resolve
 
1845
        if old_tree is None:
 
1846
            old_tree = self.basis_tree()
 
1847
        conflicts = transform.revert(self, old_tree, filenames, backups, pb,
 
1848
                                     report_changes)
 
1849
        if not len(filenames):
 
1850
            self.set_parent_ids(self.get_parent_ids()[:1])
 
1851
            resolve(self)
 
1852
        else:
 
1853
            resolve(self, filenames, ignore_misses=True)
 
1854
        return conflicts
 
1855
 
 
1856
    def revision_tree(self, revision_id):
 
1857
        """See Tree.revision_tree.
 
1858
 
 
1859
        WorkingTree can supply revision_trees for the basis revision only
 
1860
        because there is only one cached inventory in the bzr directory.
 
1861
        """
 
1862
        if revision_id == self.last_revision():
 
1863
            try:
 
1864
                xml = self.read_basis_inventory()
 
1865
            except errors.NoSuchFile:
 
1866
                pass
 
1867
            else:
 
1868
                try:
 
1869
                    inv = xml7.serializer_v7.read_inventory_from_string(xml)
 
1870
                    # dont use the repository revision_tree api because we want
 
1871
                    # to supply the inventory.
 
1872
                    if inv.revision_id == revision_id:
 
1873
                        return revisiontree.RevisionTree(self.branch.repository,
 
1874
                            inv, revision_id)
 
1875
                except errors.BadInventoryFormat:
 
1876
                    pass
 
1877
        # raise if there was no inventory, or if we read the wrong inventory.
 
1878
        raise errors.NoSuchRevisionInTree(self, revision_id)
 
1879
 
 
1880
    # XXX: This method should be deprecated in favour of taking in a proper
 
1881
    # new Inventory object.
 
1882
    @needs_tree_write_lock
 
1883
    def set_inventory(self, new_inventory_list):
 
1884
        from bzrlib.inventory import (Inventory,
 
1885
                                      InventoryDirectory,
 
1886
                                      InventoryEntry,
 
1887
                                      InventoryFile,
 
1888
                                      InventoryLink)
 
1889
        inv = Inventory(self.get_root_id())
 
1890
        for path, file_id, parent, kind in new_inventory_list:
 
1891
            name = os.path.basename(path)
 
1892
            if name == "":
 
1893
                continue
 
1894
            # fixme, there should be a factory function inv,add_?? 
 
1895
            if kind == 'directory':
 
1896
                inv.add(InventoryDirectory(file_id, name, parent))
 
1897
            elif kind == 'file':
 
1898
                inv.add(InventoryFile(file_id, name, parent))
 
1899
            elif kind == 'symlink':
 
1900
                inv.add(InventoryLink(file_id, name, parent))
 
1901
            else:
 
1902
                raise errors.BzrError("unknown kind %r" % kind)
 
1903
        self._write_inventory(inv)
 
1904
 
 
1905
    @needs_tree_write_lock
 
1906
    def set_root_id(self, file_id):
 
1907
        """Set the root id for this tree."""
 
1908
        # for compatability 
 
1909
        if file_id is None:
 
1910
            symbol_versioning.warn(symbol_versioning.zero_twelve
 
1911
                % 'WorkingTree.set_root_id with fileid=None',
 
1912
                DeprecationWarning,
 
1913
                stacklevel=3)
 
1914
            file_id = ROOT_ID
 
1915
        else:
 
1916
            file_id = osutils.safe_file_id(file_id)
 
1917
        self._set_root_id(file_id)
 
1918
 
 
1919
    def _set_root_id(self, file_id):
 
1920
        """Set the root id for this tree, in a format specific manner.
 
1921
 
 
1922
        :param file_id: The file id to assign to the root. It must not be 
 
1923
            present in the current inventory or an error will occur. It must
 
1924
            not be None, but rather a valid file id.
 
1925
        """
 
1926
        inv = self._inventory
 
1927
        orig_root_id = inv.root.file_id
 
1928
        # TODO: it might be nice to exit early if there was nothing
 
1929
        # to do, saving us from trigger a sync on unlock.
 
1930
        self._inventory_is_modified = True
 
1931
        # we preserve the root inventory entry object, but
 
1932
        # unlinkit from the byid index
 
1933
        del inv._byid[inv.root.file_id]
 
1934
        inv.root.file_id = file_id
 
1935
        # and link it into the index with the new changed id.
 
1936
        inv._byid[inv.root.file_id] = inv.root
 
1937
        # and finally update all children to reference the new id.
 
1938
        # XXX: this should be safe to just look at the root.children
 
1939
        # list, not the WHOLE INVENTORY.
 
1940
        for fid in inv:
 
1941
            entry = inv[fid]
 
1942
            if entry.parent_id == orig_root_id:
 
1943
                entry.parent_id = inv.root.file_id
 
1944
 
 
1945
    def unlock(self):
 
1946
        """See Branch.unlock.
 
1947
        
 
1948
        WorkingTree locking just uses the Branch locking facilities.
 
1949
        This is current because all working trees have an embedded branch
 
1950
        within them. IF in the future, we were to make branch data shareable
 
1951
        between multiple working trees, i.e. via shared storage, then we 
 
1952
        would probably want to lock both the local tree, and the branch.
 
1953
        """
 
1954
        raise NotImplementedError(self.unlock)
 
1955
 
 
1956
    def update(self):
 
1957
        """Update a working tree along its branch.
 
1958
 
 
1959
        This will update the branch if its bound too, which means we have
 
1960
        multiple trees involved:
 
1961
 
 
1962
        - The new basis tree of the master.
 
1963
        - The old basis tree of the branch.
 
1964
        - The old basis tree of the working tree.
 
1965
        - The current working tree state.
 
1966
 
 
1967
        Pathologically, all three may be different, and non-ancestors of each
 
1968
        other.  Conceptually we want to:
 
1969
 
 
1970
        - Preserve the wt.basis->wt.state changes
 
1971
        - Transform the wt.basis to the new master basis.
 
1972
        - Apply a merge of the old branch basis to get any 'local' changes from
 
1973
          it into the tree.
 
1974
        - Restore the wt.basis->wt.state changes.
 
1975
 
 
1976
        There isn't a single operation at the moment to do that, so we:
 
1977
        - Merge current state -> basis tree of the master w.r.t. the old tree
 
1978
          basis.
 
1979
        - Do a 'normal' merge of the old branch basis if it is relevant.
 
1980
        """
 
1981
        if self.branch.get_master_branch() is not None:
 
1982
            self.lock_write()
 
1983
            update_branch = True
 
1984
        else:
 
1985
            self.lock_tree_write()
 
1986
            update_branch = False
 
1987
        try:
 
1988
            if update_branch:
 
1989
                old_tip = self.branch.update()
 
1990
            else:
 
1991
                old_tip = None
 
1992
            return self._update_tree(old_tip)
 
1993
        finally:
 
1994
            self.unlock()
 
1995
 
 
1996
    @needs_tree_write_lock
 
1997
    def _update_tree(self, old_tip=None):
 
1998
        """Update a tree to the master branch.
 
1999
 
 
2000
        :param old_tip: if supplied, the previous tip revision the branch,
 
2001
            before it was changed to the master branch's tip.
 
2002
        """
 
2003
        # here if old_tip is not None, it is the old tip of the branch before
 
2004
        # it was updated from the master branch. This should become a pending
 
2005
        # merge in the working tree to preserve the user existing work.  we
 
2006
        # cant set that until we update the working trees last revision to be
 
2007
        # one from the new branch, because it will just get absorbed by the
 
2008
        # parent de-duplication logic.
 
2009
        # 
 
2010
        # We MUST save it even if an error occurs, because otherwise the users
 
2011
        # local work is unreferenced and will appear to have been lost.
 
2012
        # 
 
2013
        result = 0
 
2014
        try:
 
2015
            last_rev = self.get_parent_ids()[0]
 
2016
        except IndexError:
 
2017
            last_rev = None
 
2018
        if last_rev != self.branch.last_revision():
 
2019
            # merge tree state up to new branch tip.
 
2020
            basis = self.basis_tree()
 
2021
            basis.lock_read()
 
2022
            try:
 
2023
                to_tree = self.branch.basis_tree()
 
2024
                if basis.inventory.root is None:
 
2025
                    self.set_root_id(to_tree.inventory.root.file_id)
 
2026
                    self.flush()
 
2027
                result += merge.merge_inner(
 
2028
                                      self.branch,
 
2029
                                      to_tree,
 
2030
                                      basis,
 
2031
                                      this_tree=self)
 
2032
            finally:
 
2033
                basis.unlock()
 
2034
            # TODO - dedup parents list with things merged by pull ?
 
2035
            # reuse the tree we've updated to to set the basis:
 
2036
            parent_trees = [(self.branch.last_revision(), to_tree)]
 
2037
            merges = self.get_parent_ids()[1:]
 
2038
            # Ideally we ask the tree for the trees here, that way the working
 
2039
            # tree can decide whether to give us teh entire tree or give us a
 
2040
            # lazy initialised tree. dirstate for instance will have the trees
 
2041
            # in ram already, whereas a last-revision + basis-inventory tree
 
2042
            # will not, but also does not need them when setting parents.
 
2043
            for parent in merges:
 
2044
                parent_trees.append(
 
2045
                    (parent, self.branch.repository.revision_tree(parent)))
 
2046
            if old_tip is not None:
 
2047
                parent_trees.append(
 
2048
                    (old_tip, self.branch.repository.revision_tree(old_tip)))
 
2049
            self.set_parent_trees(parent_trees)
 
2050
            last_rev = parent_trees[0][0]
 
2051
        else:
 
2052
            # the working tree had the same last-revision as the master
 
2053
            # branch did. We may still have pivot local work from the local
 
2054
            # branch into old_tip:
 
2055
            if old_tip is not None:
 
2056
                self.add_parent_tree_id(old_tip)
 
2057
        if old_tip and old_tip != last_rev:
 
2058
            # our last revision was not the prior branch last revision
 
2059
            # and we have converted that last revision to a pending merge.
 
2060
            # base is somewhere between the branch tip now
 
2061
            # and the now pending merge
 
2062
 
 
2063
            # Since we just modified the working tree and inventory, flush out
 
2064
            # the current state, before we modify it again.
 
2065
            # TODO: jam 20070214 WorkingTree3 doesn't require this, dirstate
 
2066
            #       requires it only because TreeTransform directly munges the
 
2067
            #       inventory and calls tree._write_inventory(). Ultimately we
 
2068
            #       should be able to remove this extra flush.
 
2069
            self.flush()
 
2070
            from bzrlib.revision import common_ancestor
 
2071
            try:
 
2072
                base_rev_id = common_ancestor(self.branch.last_revision(),
 
2073
                                              old_tip,
 
2074
                                              self.branch.repository)
 
2075
            except errors.NoCommonAncestor:
 
2076
                base_rev_id = None
 
2077
            base_tree = self.branch.repository.revision_tree(base_rev_id)
 
2078
            other_tree = self.branch.repository.revision_tree(old_tip)
 
2079
            result += merge.merge_inner(
 
2080
                                  self.branch,
 
2081
                                  other_tree,
 
2082
                                  base_tree,
 
2083
                                  this_tree=self)
 
2084
        return result
 
2085
 
 
2086
    def _write_hashcache_if_dirty(self):
 
2087
        """Write out the hashcache if it is dirty."""
 
2088
        if self._hashcache.needs_write:
 
2089
            try:
 
2090
                self._hashcache.write()
 
2091
            except OSError, e:
 
2092
                if e.errno not in (errno.EPERM, errno.EACCES):
 
2093
                    raise
 
2094
                # TODO: jam 20061219 Should this be a warning? A single line
 
2095
                #       warning might be sufficient to let the user know what
 
2096
                #       is going on.
 
2097
                mutter('Could not write hashcache for %s\nError: %s',
 
2098
                       self._hashcache.cache_file_name(), e)
 
2099
 
 
2100
    @needs_tree_write_lock
 
2101
    def _write_inventory(self, inv):
 
2102
        """Write inventory as the current inventory."""
 
2103
        self._set_inventory(inv, dirty=True)
 
2104
        self.flush()
 
2105
 
 
2106
    def set_conflicts(self, arg):
 
2107
        raise errors.UnsupportedOperation(self.set_conflicts, self)
 
2108
 
 
2109
    def add_conflicts(self, arg):
 
2110
        raise errors.UnsupportedOperation(self.add_conflicts, self)
 
2111
 
 
2112
    @needs_read_lock
 
2113
    def conflicts(self):
 
2114
        conflicts = _mod_conflicts.ConflictList()
 
2115
        for conflicted in self._iter_conflicts():
 
2116
            text = True
 
2117
            try:
 
2118
                if file_kind(self.abspath(conflicted)) != "file":
 
2119
                    text = False
 
2120
            except errors.NoSuchFile:
 
2121
                text = False
 
2122
            if text is True:
 
2123
                for suffix in ('.THIS', '.OTHER'):
 
2124
                    try:
 
2125
                        kind = file_kind(self.abspath(conflicted+suffix))
 
2126
                        if kind != "file":
 
2127
                            text = False
 
2128
                    except errors.NoSuchFile:
 
2129
                        text = False
 
2130
                    if text == False:
 
2131
                        break
 
2132
            ctype = {True: 'text conflict', False: 'contents conflict'}[text]
 
2133
            conflicts.append(_mod_conflicts.Conflict.factory(ctype,
 
2134
                             path=conflicted,
 
2135
                             file_id=self.path2id(conflicted)))
 
2136
        return conflicts
 
2137
 
 
2138
    def walkdirs(self, prefix=""):
 
2139
        """Walk the directories of this tree.
 
2140
 
 
2141
        This API returns a generator, which is only valid during the current
 
2142
        tree transaction - within a single lock_read or lock_write duration.
 
2143
 
 
2144
        If the tree is not locked, it may cause an error to be raised, depending
 
2145
        on the tree implementation.
 
2146
        """
 
2147
        disk_top = self.abspath(prefix)
 
2148
        if disk_top.endswith('/'):
 
2149
            disk_top = disk_top[:-1]
 
2150
        top_strip_len = len(disk_top) + 1
 
2151
        inventory_iterator = self._walkdirs(prefix)
 
2152
        disk_iterator = osutils.walkdirs(disk_top, prefix)
 
2153
        try:
 
2154
            current_disk = disk_iterator.next()
 
2155
            disk_finished = False
 
2156
        except OSError, e:
 
2157
            if e.errno != errno.ENOENT:
 
2158
                raise
 
2159
            current_disk = None
 
2160
            disk_finished = True
 
2161
        try:
 
2162
            current_inv = inventory_iterator.next()
 
2163
            inv_finished = False
 
2164
        except StopIteration:
 
2165
            current_inv = None
 
2166
            inv_finished = True
 
2167
        while not inv_finished or not disk_finished:
 
2168
            if not disk_finished:
 
2169
                # strip out .bzr dirs
 
2170
                if current_disk[0][1][top_strip_len:] == '':
 
2171
                    # osutils.walkdirs can be made nicer - 
 
2172
                    # yield the path-from-prefix rather than the pathjoined
 
2173
                    # value.
 
2174
                    bzrdir_loc = bisect_left(current_disk[1], ('.bzr', '.bzr'))
 
2175
                    if current_disk[1][bzrdir_loc][0] == '.bzr':
 
2176
                        # we dont yield the contents of, or, .bzr itself.
 
2177
                        del current_disk[1][bzrdir_loc]
 
2178
            if inv_finished:
 
2179
                # everything is unknown
 
2180
                direction = 1
 
2181
            elif disk_finished:
 
2182
                # everything is missing
 
2183
                direction = -1
 
2184
            else:
 
2185
                direction = cmp(current_inv[0][0], current_disk[0][0])
 
2186
            if direction > 0:
 
2187
                # disk is before inventory - unknown
 
2188
                dirblock = [(relpath, basename, kind, stat, None, None) for
 
2189
                    relpath, basename, kind, stat, top_path in current_disk[1]]
 
2190
                yield (current_disk[0][0], None), dirblock
 
2191
                try:
 
2192
                    current_disk = disk_iterator.next()
 
2193
                except StopIteration:
 
2194
                    disk_finished = True
 
2195
            elif direction < 0:
 
2196
                # inventory is before disk - missing.
 
2197
                dirblock = [(relpath, basename, 'unknown', None, fileid, kind)
 
2198
                    for relpath, basename, dkind, stat, fileid, kind in 
 
2199
                    current_inv[1]]
 
2200
                yield (current_inv[0][0], current_inv[0][1]), dirblock
 
2201
                try:
 
2202
                    current_inv = inventory_iterator.next()
 
2203
                except StopIteration:
 
2204
                    inv_finished = True
 
2205
            else:
 
2206
                # versioned present directory
 
2207
                # merge the inventory and disk data together
 
2208
                dirblock = []
 
2209
                for relpath, subiterator in itertools.groupby(sorted(
 
2210
                    current_inv[1] + current_disk[1], key=operator.itemgetter(0)), operator.itemgetter(1)):
 
2211
                    path_elements = list(subiterator)
 
2212
                    if len(path_elements) == 2:
 
2213
                        inv_row, disk_row = path_elements
 
2214
                        # versioned, present file
 
2215
                        dirblock.append((inv_row[0],
 
2216
                            inv_row[1], disk_row[2],
 
2217
                            disk_row[3], inv_row[4],
 
2218
                            inv_row[5]))
 
2219
                    elif len(path_elements[0]) == 5:
 
2220
                        # unknown disk file
 
2221
                        dirblock.append((path_elements[0][0],
 
2222
                            path_elements[0][1], path_elements[0][2],
 
2223
                            path_elements[0][3], None, None))
 
2224
                    elif len(path_elements[0]) == 6:
 
2225
                        # versioned, absent file.
 
2226
                        dirblock.append((path_elements[0][0],
 
2227
                            path_elements[0][1], 'unknown', None,
 
2228
                            path_elements[0][4], path_elements[0][5]))
 
2229
                    else:
 
2230
                        raise NotImplementedError('unreachable code')
 
2231
                yield current_inv[0], dirblock
 
2232
                try:
 
2233
                    current_inv = inventory_iterator.next()
 
2234
                except StopIteration:
 
2235
                    inv_finished = True
 
2236
                try:
 
2237
                    current_disk = disk_iterator.next()
 
2238
                except StopIteration:
 
2239
                    disk_finished = True
 
2240
 
 
2241
    def _walkdirs(self, prefix=""):
 
2242
        _directory = 'directory'
 
2243
        # get the root in the inventory
 
2244
        inv = self.inventory
 
2245
        top_id = inv.path2id(prefix)
 
2246
        if top_id is None:
 
2247
            pending = []
 
2248
        else:
 
2249
            pending = [(prefix, '', _directory, None, top_id, None)]
 
2250
        while pending:
 
2251
            dirblock = []
 
2252
            currentdir = pending.pop()
 
2253
            # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-id, 5-kind
 
2254
            top_id = currentdir[4]
 
2255
            if currentdir[0]:
 
2256
                relroot = currentdir[0] + '/'
 
2257
            else:
 
2258
                relroot = ""
 
2259
            # FIXME: stash the node in pending
 
2260
            entry = inv[top_id]
 
2261
            for name, child in entry.sorted_children():
 
2262
                dirblock.append((relroot + name, name, child.kind, None,
 
2263
                    child.file_id, child.kind
 
2264
                    ))
 
2265
            yield (currentdir[0], entry.file_id), dirblock
 
2266
            # push the user specified dirs from dirblock
 
2267
            for dir in reversed(dirblock):
 
2268
                if dir[2] == _directory:
 
2269
                    pending.append(dir)
 
2270
 
 
2271
    @needs_tree_write_lock
 
2272
    def auto_resolve(self):
 
2273
        """Automatically resolve text conflicts according to contents.
 
2274
 
 
2275
        Only text conflicts are auto_resolvable. Files with no conflict markers
 
2276
        are considered 'resolved', because bzr always puts conflict markers
 
2277
        into files that have text conflicts.  The corresponding .THIS .BASE and
 
2278
        .OTHER files are deleted, as per 'resolve'.
 
2279
        :return: a tuple of ConflictLists: (un_resolved, resolved).
 
2280
        """
 
2281
        un_resolved = _mod_conflicts.ConflictList()
 
2282
        resolved = _mod_conflicts.ConflictList()
 
2283
        conflict_re = re.compile('^(<{7}|={7}|>{7})')
 
2284
        for conflict in self.conflicts():
 
2285
            if (conflict.typestring != 'text conflict' or
 
2286
                self.kind(conflict.file_id) != 'file'):
 
2287
                un_resolved.append(conflict)
 
2288
                continue
 
2289
            my_file = open(self.id2abspath(conflict.file_id), 'rb')
 
2290
            try:
 
2291
                for line in my_file:
 
2292
                    if conflict_re.search(line):
 
2293
                        un_resolved.append(conflict)
 
2294
                        break
 
2295
                else:
 
2296
                    resolved.append(conflict)
 
2297
            finally:
 
2298
                my_file.close()
 
2299
        resolved.remove_files(self)
 
2300
        self.set_conflicts(un_resolved)
 
2301
        return un_resolved, resolved
 
2302
 
 
2303
 
 
2304
class WorkingTree2(WorkingTree):
 
2305
    """This is the Format 2 working tree.
 
2306
 
 
2307
    This was the first weave based working tree. 
 
2308
     - uses os locks for locking.
 
2309
     - uses the branch last-revision.
 
2310
    """
 
2311
 
 
2312
    def lock_tree_write(self):
 
2313
        """See WorkingTree.lock_tree_write().
 
2314
 
 
2315
        In Format2 WorkingTrees we have a single lock for the branch and tree
 
2316
        so lock_tree_write() degrades to lock_write().
 
2317
        """
 
2318
        self.branch.lock_write()
 
2319
        try:
 
2320
            return self._control_files.lock_write()
 
2321
        except:
 
2322
            self.branch.unlock()
 
2323
            raise
 
2324
 
 
2325
    def unlock(self):
 
2326
        # we share control files:
 
2327
        if self._control_files._lock_count == 3:
 
2328
            # _inventory_is_modified is always False during a read lock.
 
2329
            if self._inventory_is_modified:
 
2330
                self.flush()
 
2331
            self._write_hashcache_if_dirty()
 
2332
                    
 
2333
        # reverse order of locking.
 
2334
        try:
 
2335
            return self._control_files.unlock()
 
2336
        finally:
 
2337
            self.branch.unlock()
 
2338
 
 
2339
 
 
2340
class WorkingTree3(WorkingTree):
 
2341
    """This is the Format 3 working tree.
 
2342
 
 
2343
    This differs from the base WorkingTree by:
 
2344
     - having its own file lock
 
2345
     - having its own last-revision property.
 
2346
 
 
2347
    This is new in bzr 0.8
 
2348
    """
 
2349
 
 
2350
    @needs_read_lock
 
2351
    def _last_revision(self):
 
2352
        """See Mutable.last_revision."""
 
2353
        try:
 
2354
            return osutils.safe_revision_id(
 
2355
                        self._control_files.get('last-revision').read())
 
2356
        except errors.NoSuchFile:
 
2357
            return None
 
2358
 
 
2359
    def _change_last_revision(self, revision_id):
 
2360
        """See WorkingTree._change_last_revision."""
 
2361
        if revision_id is None or revision_id == NULL_REVISION:
 
2362
            try:
 
2363
                self._control_files._transport.delete('last-revision')
 
2364
            except errors.NoSuchFile:
 
2365
                pass
 
2366
            return False
 
2367
        else:
 
2368
            self._control_files.put_bytes('last-revision', revision_id)
 
2369
            return True
 
2370
 
 
2371
    @needs_tree_write_lock
 
2372
    def set_conflicts(self, conflicts):
 
2373
        self._put_rio('conflicts', conflicts.to_stanzas(), 
 
2374
                      CONFLICT_HEADER_1)
 
2375
 
 
2376
    @needs_tree_write_lock
 
2377
    def add_conflicts(self, new_conflicts):
 
2378
        conflict_set = set(self.conflicts())
 
2379
        conflict_set.update(set(list(new_conflicts)))
 
2380
        self.set_conflicts(_mod_conflicts.ConflictList(sorted(conflict_set,
 
2381
                                       key=_mod_conflicts.Conflict.sort_key)))
 
2382
 
 
2383
    @needs_read_lock
 
2384
    def conflicts(self):
 
2385
        try:
 
2386
            confile = self._control_files.get('conflicts')
 
2387
        except errors.NoSuchFile:
 
2388
            return _mod_conflicts.ConflictList()
 
2389
        try:
 
2390
            if confile.next() != CONFLICT_HEADER_1 + '\n':
 
2391
                raise errors.ConflictFormatError()
 
2392
        except StopIteration:
 
2393
            raise errors.ConflictFormatError()
 
2394
        return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
 
2395
 
 
2396
    def unlock(self):
 
2397
        if self._control_files._lock_count == 1:
 
2398
            # _inventory_is_modified is always False during a read lock.
 
2399
            if self._inventory_is_modified:
 
2400
                self.flush()
 
2401
            self._write_hashcache_if_dirty()
 
2402
        # reverse order of locking.
 
2403
        try:
 
2404
            return self._control_files.unlock()
 
2405
        finally:
 
2406
            self.branch.unlock()
 
2407
 
 
2408
 
 
2409
def get_conflicted_stem(path):
 
2410
    for suffix in _mod_conflicts.CONFLICT_SUFFIXES:
 
2411
        if path.endswith(suffix):
 
2412
            return path[:-len(suffix)]
 
2413
 
 
2414
 
 
2415
@deprecated_function(zero_eight)
 
2416
def is_control_file(filename):
 
2417
    """See WorkingTree.is_control_filename(filename)."""
 
2418
    ## FIXME: better check
 
2419
    filename = normpath(filename)
 
2420
    while filename != '':
 
2421
        head, tail = os.path.split(filename)
 
2422
        ## mutter('check %r for control file' % ((head, tail),))
 
2423
        if tail == '.bzr':
 
2424
            return True
 
2425
        if filename == head:
 
2426
            break
 
2427
        filename = head
 
2428
    return False
 
2429
 
 
2430
 
 
2431
class WorkingTreeFormat(object):
 
2432
    """An encapsulation of the initialization and open routines for a format.
 
2433
 
 
2434
    Formats provide three things:
 
2435
     * An initialization routine,
 
2436
     * a format string,
 
2437
     * an open routine.
 
2438
 
 
2439
    Formats are placed in an dict by their format string for reference 
 
2440
    during workingtree opening. Its not required that these be instances, they
 
2441
    can be classes themselves with class methods - it simply depends on 
 
2442
    whether state is needed for a given format or not.
 
2443
 
 
2444
    Once a format is deprecated, just deprecate the initialize and open
 
2445
    methods on the format class. Do not deprecate the object, as the 
 
2446
    object will be created every time regardless.
 
2447
    """
 
2448
 
 
2449
    _default_format = None
 
2450
    """The default format used for new trees."""
 
2451
 
 
2452
    _formats = {}
 
2453
    """The known formats."""
 
2454
 
 
2455
    requires_rich_root = False
 
2456
 
 
2457
    @classmethod
 
2458
    def find_format(klass, a_bzrdir):
 
2459
        """Return the format for the working tree object in a_bzrdir."""
 
2460
        try:
 
2461
            transport = a_bzrdir.get_workingtree_transport(None)
 
2462
            format_string = transport.get("format").read()
 
2463
            return klass._formats[format_string]
 
2464
        except errors.NoSuchFile:
 
2465
            raise errors.NoWorkingTree(base=transport.base)
 
2466
        except KeyError:
 
2467
            raise errors.UnknownFormatError(format=format_string)
 
2468
 
 
2469
    def __eq__(self, other):
 
2470
        return self.__class__ is other.__class__
 
2471
 
 
2472
    def __ne__(self, other):
 
2473
        return not (self == other)
 
2474
 
 
2475
    @classmethod
 
2476
    def get_default_format(klass):
 
2477
        """Return the current default format."""
 
2478
        return klass._default_format
 
2479
 
 
2480
    def get_format_string(self):
 
2481
        """Return the ASCII format string that identifies this format."""
 
2482
        raise NotImplementedError(self.get_format_string)
 
2483
 
 
2484
    def get_format_description(self):
 
2485
        """Return the short description for this format."""
 
2486
        raise NotImplementedError(self.get_format_description)
 
2487
 
 
2488
    def is_supported(self):
 
2489
        """Is this format supported?
 
2490
 
 
2491
        Supported formats can be initialized and opened.
 
2492
        Unsupported formats may not support initialization or committing or 
 
2493
        some other features depending on the reason for not being supported.
 
2494
        """
 
2495
        return True
 
2496
 
 
2497
    @classmethod
 
2498
    def register_format(klass, format):
 
2499
        klass._formats[format.get_format_string()] = format
 
2500
 
 
2501
    @classmethod
 
2502
    def set_default_format(klass, format):
 
2503
        klass._default_format = format
 
2504
 
 
2505
    @classmethod
 
2506
    def unregister_format(klass, format):
 
2507
        assert klass._formats[format.get_format_string()] is format
 
2508
        del klass._formats[format.get_format_string()]
 
2509
 
 
2510
 
 
2511
 
 
2512
class WorkingTreeFormat2(WorkingTreeFormat):
 
2513
    """The second working tree format. 
 
2514
 
 
2515
    This format modified the hash cache from the format 1 hash cache.
 
2516
    """
 
2517
 
 
2518
    def get_format_description(self):
 
2519
        """See WorkingTreeFormat.get_format_description()."""
 
2520
        return "Working tree format 2"
 
2521
 
 
2522
    def stub_initialize_remote(self, control_files):
 
2523
        """As a special workaround create critical control files for a remote working tree
 
2524
        
 
2525
        This ensures that it can later be updated and dealt with locally,
 
2526
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with 
 
2527
        no working tree.  (See bug #43064).
 
2528
        """
 
2529
        sio = StringIO()
 
2530
        inv = Inventory()
 
2531
        xml5.serializer_v5.write_inventory(inv, sio)
 
2532
        sio.seek(0)
 
2533
        control_files.put('inventory', sio)
 
2534
 
 
2535
        control_files.put_bytes('pending-merges', '')
 
2536
        
 
2537
 
 
2538
    def initialize(self, a_bzrdir, revision_id=None):
 
2539
        """See WorkingTreeFormat.initialize()."""
 
2540
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
2541
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
2542
        branch = a_bzrdir.open_branch()
 
2543
        if revision_id is not None:
 
2544
            revision_id = osutils.safe_revision_id(revision_id)
 
2545
            branch.lock_write()
 
2546
            try:
 
2547
                revision_history = branch.revision_history()
 
2548
                try:
 
2549
                    position = revision_history.index(revision_id)
 
2550
                except ValueError:
 
2551
                    raise errors.NoSuchRevision(branch, revision_id)
 
2552
                branch.set_revision_history(revision_history[:position + 1])
 
2553
            finally:
 
2554
                branch.unlock()
 
2555
        revision = branch.last_revision()
 
2556
        inv = Inventory()
 
2557
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
 
2558
                         branch,
 
2559
                         inv,
 
2560
                         _internal=True,
 
2561
                         _format=self,
 
2562
                         _bzrdir=a_bzrdir)
 
2563
        basis_tree = branch.repository.revision_tree(revision)
 
2564
        if basis_tree.inventory.root is not None:
 
2565
            wt.set_root_id(basis_tree.inventory.root.file_id)
 
2566
        # set the parent list and cache the basis tree.
 
2567
        wt.set_parent_trees([(revision, basis_tree)])
 
2568
        transform.build_tree(basis_tree, wt)
 
2569
        return wt
 
2570
 
 
2571
    def __init__(self):
 
2572
        super(WorkingTreeFormat2, self).__init__()
 
2573
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
2574
 
 
2575
    def open(self, a_bzrdir, _found=False):
 
2576
        """Return the WorkingTree object for a_bzrdir
 
2577
 
 
2578
        _found is a private parameter, do not use it. It is used to indicate
 
2579
               if format probing has already been done.
 
2580
        """
 
2581
        if not _found:
 
2582
            # we are being called directly and must probe.
 
2583
            raise NotImplementedError
 
2584
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
2585
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
2586
        return WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
 
2587
                           _internal=True,
 
2588
                           _format=self,
 
2589
                           _bzrdir=a_bzrdir)
 
2590
 
 
2591
 
 
2592
class WorkingTreeFormat3(WorkingTreeFormat):
 
2593
    """The second working tree format updated to record a format marker.
 
2594
 
 
2595
    This format:
 
2596
        - exists within a metadir controlling .bzr
 
2597
        - includes an explicit version marker for the workingtree control
 
2598
          files, separate from the BzrDir format
 
2599
        - modifies the hash cache format
 
2600
        - is new in bzr 0.8
 
2601
        - uses a LockDir to guard access for writes.
 
2602
    """
 
2603
 
 
2604
    def get_format_string(self):
 
2605
        """See WorkingTreeFormat.get_format_string()."""
 
2606
        return "Bazaar-NG Working Tree format 3"
 
2607
 
 
2608
    def get_format_description(self):
 
2609
        """See WorkingTreeFormat.get_format_description()."""
 
2610
        return "Working tree format 3"
 
2611
 
 
2612
    _lock_file_name = 'lock'
 
2613
    _lock_class = LockDir
 
2614
 
 
2615
    _tree_class = WorkingTree3
 
2616
 
 
2617
    def __get_matchingbzrdir(self):
 
2618
        return bzrdir.BzrDirMetaFormat1()
 
2619
 
 
2620
    _matchingbzrdir = property(__get_matchingbzrdir)
 
2621
 
 
2622
    def _open_control_files(self, a_bzrdir):
 
2623
        transport = a_bzrdir.get_workingtree_transport(None)
 
2624
        return LockableFiles(transport, self._lock_file_name, 
 
2625
                             self._lock_class)
 
2626
 
 
2627
    def initialize(self, a_bzrdir, revision_id=None):
 
2628
        """See WorkingTreeFormat.initialize().
 
2629
        
 
2630
        revision_id allows creating a working tree at a different
 
2631
        revision than the branch is at.
 
2632
        """
 
2633
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
2634
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
2635
        transport = a_bzrdir.get_workingtree_transport(self)
 
2636
        control_files = self._open_control_files(a_bzrdir)
 
2637
        control_files.create_lock()
 
2638
        control_files.lock_write()
 
2639
        control_files.put_utf8('format', self.get_format_string())
 
2640
        branch = a_bzrdir.open_branch()
 
2641
        if revision_id is None:
 
2642
            revision_id = branch.last_revision()
 
2643
        else:
 
2644
            revision_id = osutils.safe_revision_id(revision_id)
 
2645
        # WorkingTree3 can handle an inventory which has a unique root id.
 
2646
        # as of bzr 0.12. However, bzr 0.11 and earlier fail to handle
 
2647
        # those trees. And because there isn't a format bump inbetween, we
 
2648
        # are maintaining compatibility with older clients.
 
2649
        # inv = Inventory(root_id=gen_root_id())
 
2650
        inv = self._initial_inventory()
 
2651
        wt = self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
 
2652
                         branch,
 
2653
                         inv,
 
2654
                         _internal=True,
 
2655
                         _format=self,
 
2656
                         _bzrdir=a_bzrdir,
 
2657
                         _control_files=control_files)
 
2658
        wt.lock_tree_write()
 
2659
        try:
 
2660
            basis_tree = branch.repository.revision_tree(revision_id)
 
2661
            # only set an explicit root id if there is one to set.
 
2662
            if basis_tree.inventory.root is not None:
 
2663
                wt.set_root_id(basis_tree.inventory.root.file_id)
 
2664
            if revision_id == NULL_REVISION:
 
2665
                wt.set_parent_trees([])
 
2666
            else:
 
2667
                wt.set_parent_trees([(revision_id, basis_tree)])
 
2668
            transform.build_tree(basis_tree, wt)
 
2669
        finally:
 
2670
            # Unlock in this order so that the unlock-triggers-flush in
 
2671
            # WorkingTree is given a chance to fire.
 
2672
            control_files.unlock()
 
2673
            wt.unlock()
 
2674
        return wt
 
2675
 
 
2676
    def _initial_inventory(self):
 
2677
        return Inventory()
 
2678
 
 
2679
    def __init__(self):
 
2680
        super(WorkingTreeFormat3, self).__init__()
 
2681
 
 
2682
    def open(self, a_bzrdir, _found=False):
 
2683
        """Return the WorkingTree object for a_bzrdir
 
2684
 
 
2685
        _found is a private parameter, do not use it. It is used to indicate
 
2686
               if format probing has already been done.
 
2687
        """
 
2688
        if not _found:
 
2689
            # we are being called directly and must probe.
 
2690
            raise NotImplementedError
 
2691
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
2692
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
2693
        return self._open(a_bzrdir, self._open_control_files(a_bzrdir))
 
2694
 
 
2695
    def _open(self, a_bzrdir, control_files):
 
2696
        """Open the tree itself.
 
2697
        
 
2698
        :param a_bzrdir: the dir for the tree.
 
2699
        :param control_files: the control files for the tree.
 
2700
        """
 
2701
        return self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
 
2702
                                _internal=True,
 
2703
                                _format=self,
 
2704
                                _bzrdir=a_bzrdir,
 
2705
                                _control_files=control_files)
 
2706
 
 
2707
    def __str__(self):
 
2708
        return self.get_format_string()
 
2709
 
 
2710
 
 
2711
__default_format = WorkingTreeFormat4()
 
2712
WorkingTreeFormat.register_format(__default_format)
 
2713
WorkingTreeFormat.register_format(WorkingTreeFormat3())
 
2714
WorkingTreeFormat.set_default_format(__default_format)
 
2715
# formats which have no format string are not discoverable
 
2716
# and not independently creatable, so are not registered.
 
2717
_legacy_formats = [WorkingTreeFormat2(),
 
2718
                   ]
 
2719
 
 
2720
 
 
2721
class WorkingTreeTestProviderAdapter(object):
 
2722
    """A tool to generate a suite testing multiple workingtree formats at once.
 
2723
 
 
2724
    This is done by copying the test once for each transport and injecting
 
2725
    the transport_server, transport_readonly_server, and workingtree_format
 
2726
    classes into each copy. Each copy is also given a new id() to make it
 
2727
    easy to identify.
 
2728
    """
 
2729
 
 
2730
    def __init__(self, transport_server, transport_readonly_server, formats):
 
2731
        self._transport_server = transport_server
 
2732
        self._transport_readonly_server = transport_readonly_server
 
2733
        self._formats = formats
 
2734
    
 
2735
    def _clone_test(self, test, bzrdir_format, workingtree_format, variation):
 
2736
        """Clone test for adaption."""
 
2737
        new_test = deepcopy(test)
 
2738
        new_test.transport_server = self._transport_server
 
2739
        new_test.transport_readonly_server = self._transport_readonly_server
 
2740
        new_test.bzrdir_format = bzrdir_format
 
2741
        new_test.workingtree_format = workingtree_format
 
2742
        def make_new_test_id():
 
2743
            new_id = "%s(%s)" % (test.id(), variation)
 
2744
            return lambda: new_id
 
2745
        new_test.id = make_new_test_id()
 
2746
        return new_test
 
2747
    
 
2748
    def adapt(self, test):
 
2749
        from bzrlib.tests import TestSuite
 
2750
        result = TestSuite()
 
2751
        for workingtree_format, bzrdir_format in self._formats:
 
2752
            new_test = self._clone_test(
 
2753
                test,
 
2754
                bzrdir_format,
 
2755
                workingtree_format, workingtree_format.__class__.__name__)
 
2756
            result.addTest(new_test)
 
2757
        return result