~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/workingtree.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-03-16 14:01:20 UTC
  • mfrom: (3280.2.5 integration)
  • Revision ID: pqm@pqm.ubuntu.com-20080316140120-i3yq8yr1l66m11h7
Start 1.4 development

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""WorkingTree object and friends.
18
18
 
19
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
 
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
23
new revision based on the workingtree and its inventory.
24
24
 
25
25
At the moment every WorkingTree has its own branch.  Remote
29
29
WorkingTree.open(dir).
30
30
"""
31
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)
32
38
 
33
39
from cStringIO import StringIO
34
40
import os
42
48
import itertools
43
49
import operator
44
50
import stat
 
51
from time import time
 
52
import warnings
45
53
import re
46
54
 
47
55
import bzrlib
49
57
    branch,
50
58
    bzrdir,
51
59
    conflicts as _mod_conflicts,
52
 
    controldir,
 
60
    dirstate,
53
61
    errors,
54
62
    generate_ids,
55
63
    globbing,
56
 
    graph as _mod_graph,
57
64
    hashcache,
58
65
    ignores,
59
 
    inventory,
60
66
    merge,
61
67
    revision as _mod_revision,
62
68
    revisiontree,
 
69
    repository,
 
70
    textui,
63
71
    trace,
64
72
    transform,
65
 
    transport,
66
73
    ui,
67
 
    views,
 
74
    urlutils,
68
75
    xml5,
 
76
    xml6,
69
77
    xml7,
70
78
    )
71
 
from bzrlib.workingtree_4 import (
72
 
    WorkingTreeFormat4,
73
 
    WorkingTreeFormat5,
74
 
    WorkingTreeFormat6,
75
 
    )
 
79
import bzrlib.branch
 
80
from bzrlib.transport import get_transport
 
81
import bzrlib.ui
 
82
from bzrlib.workingtree_4 import WorkingTreeFormat4
76
83
""")
77
84
 
78
85
from bzrlib import symbol_versioning
79
86
from bzrlib.decorators import needs_read_lock, needs_write_lock
80
 
from bzrlib.lock import LogicalLockResult
81
 
from bzrlib.lockable_files import LockableFiles
 
87
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, TreeReference
 
88
from bzrlib.lockable_files import LockableFiles, TransportLock
82
89
from bzrlib.lockdir import LockDir
83
90
import bzrlib.mutabletree
84
91
from bzrlib.mutabletree import needs_tree_write_lock
85
92
from bzrlib import osutils
86
93
from bzrlib.osutils import (
 
94
    compact_date,
87
95
    file_kind,
88
96
    isdir,
89
97
    normpath,
90
98
    pathjoin,
 
99
    rand_chars,
91
100
    realpath,
92
101
    safe_unicode,
93
102
    splitpath,
94
103
    supports_executable,
95
104
    )
96
 
from bzrlib.filters import filtered_input_file
97
105
from bzrlib.trace import mutter, note
98
106
from bzrlib.transport.local import LocalTransport
99
 
from bzrlib.revision import CURRENT_REVISION
 
107
from bzrlib.progress import DummyProgress, ProgressPhase
 
108
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
100
109
from bzrlib.rio import RioReader, rio_file, Stanza
101
 
from bzrlib.symbol_versioning import (
102
 
    deprecated_passed,
103
 
    DEPRECATED_PARAMETER,
104
 
    )
 
110
from bzrlib.symbol_versioning import (deprecated_passed,
 
111
        deprecated_method,
 
112
        deprecated_function,
 
113
        DEPRECATED_PARAMETER,
 
114
        zero_eight,
 
115
        zero_eleven,
 
116
        zero_thirteen,
 
117
        )
105
118
 
106
119
 
107
120
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
108
 
# TODO: Modifying the conflict objects or their type is currently nearly
109
 
# impossible as there is no clear relationship between the working tree format
110
 
# and the conflict list file format.
111
121
CONFLICT_HEADER_1 = "BZR conflict list format 1"
112
122
 
113
123
ERROR_PATH_NOT_FOUND = 3    # WindowsError errno code, equivalent to ENOENT
114
124
 
115
125
 
 
126
@deprecated_function(zero_thirteen)
 
127
def gen_file_id(name):
 
128
    """Return new file id for the basename 'name'.
 
129
 
 
130
    Use bzrlib.generate_ids.gen_file_id() instead
 
131
    """
 
132
    return generate_ids.gen_file_id(name)
 
133
 
 
134
 
 
135
@deprecated_function(zero_thirteen)
 
136
def gen_root_id():
 
137
    """Return a new tree-root file id.
 
138
 
 
139
    This has been deprecated in favor of bzrlib.generate_ids.gen_root_id()
 
140
    """
 
141
    return generate_ids.gen_root_id()
 
142
 
 
143
 
116
144
class TreeEntry(object):
117
145
    """An entry that implements the minimum interface used by commands.
118
146
 
119
 
    This needs further inspection, it may be better to have
 
147
    This needs further inspection, it may be better to have 
120
148
    InventoryEntries without ids - though that seems wrong. For now,
121
149
    this is a parallel hierarchy to InventoryEntry, and needs to become
122
150
    one of several things: decorates to that hierarchy, children of, or
125
153
    no InventoryEntry available - i.e. for unversioned objects.
126
154
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
127
155
    """
128
 
 
 
156
 
129
157
    def __eq__(self, other):
130
158
        # yes, this us ugly, TODO: best practice __eq__ style.
131
159
        return (isinstance(other, TreeEntry)
132
160
                and other.__class__ == self.__class__)
133
 
 
 
161
 
134
162
    def kind_character(self):
135
163
        return "???"
136
164
 
168
196
        return ''
169
197
 
170
198
 
171
 
class WorkingTree(bzrlib.mutabletree.MutableTree,
172
 
    controldir.ControlComponent):
 
199
class WorkingTree(bzrlib.mutabletree.MutableTree):
173
200
    """Working copy tree.
174
201
 
175
202
    The inventory is held in the `Branch` working-inventory, and the
177
204
 
178
205
    It is possible for a `WorkingTree` to have a filename which is
179
206
    not listed in the Inventory and vice versa.
180
 
 
181
 
    :ivar basedir: The root of the tree on disk. This is a unicode path object
182
 
        (as opposed to a URL).
183
207
    """
184
208
 
185
 
    # override this to set the strategy for storing views
186
 
    def _make_views(self):
187
 
        return views.DisabledViews(self)
188
 
 
189
209
    def __init__(self, basedir='.',
190
210
                 branch=DEPRECATED_PARAMETER,
191
211
                 _inventory=None,
202
222
        if not _internal:
203
223
            raise errors.BzrError("Please use bzrdir.open_workingtree or "
204
224
                "WorkingTree.open() to obtain a WorkingTree.")
 
225
        assert isinstance(basedir, basestring), \
 
226
            "base directory %r is not a string" % basedir
205
227
        basedir = safe_unicode(basedir)
206
228
        mutter("opening working tree %r", basedir)
207
229
        if deprecated_passed(branch):
215
237
            self._control_files = self.branch.control_files
216
238
        else:
217
239
            # assume all other formats have their own control files.
 
240
            assert isinstance(_control_files, LockableFiles), \
 
241
                    "_control_files must be a LockableFiles, not %r" \
 
242
                    % _control_files
218
243
            self._control_files = _control_files
219
 
        self._transport = self._control_files._transport
220
244
        # update the whole cache up front and write to disk if anything changed;
221
245
        # in the future we might want to do this more selectively
222
246
        # two possible ways offer themselves : in self._unlock, write the cache
226
250
        wt_trans = self.bzrdir.get_workingtree_transport(None)
227
251
        cache_filename = wt_trans.local_abspath('stat-cache')
228
252
        self._hashcache = hashcache.HashCache(basedir, cache_filename,
229
 
            self.bzrdir._get_file_mode(),
230
 
            self._content_filter_stack_provider())
 
253
                                              self._control_files._file_mode)
231
254
        hc = self._hashcache
232
255
        hc.read()
233
256
        # is this scan needed ? it makes things kinda slow.
248
271
            # permitted to do this.
249
272
            self._set_inventory(_inventory, dirty=False)
250
273
        self._detect_case_handling()
251
 
        self._rules_searcher = None
252
 
        self.views = self._make_views()
253
 
 
254
 
    @property
255
 
    def user_transport(self):
256
 
        return self.bzrdir.user_transport
257
 
 
258
 
    @property
259
 
    def control_transport(self):
260
 
        return self._transport
261
274
 
262
275
    def _detect_case_handling(self):
263
276
        wt_trans = self.bzrdir.get_workingtree_transport(None)
289
302
        self._control_files.break_lock()
290
303
        self.branch.break_lock()
291
304
 
292
 
    def _get_check_refs(self):
293
 
        """Return the references needed to perform a check of this tree.
294
 
        
295
 
        The default implementation returns no refs, and is only suitable for
296
 
        trees that have no local caching and can commit on ghosts at any time.
297
 
 
298
 
        :seealso: bzrlib.check for details about check_refs.
299
 
        """
300
 
        return []
301
 
 
302
305
    def requires_rich_root(self):
303
306
        return self._format.requires_rich_root
304
307
 
305
308
    def supports_tree_reference(self):
306
309
        return False
307
310
 
308
 
    def supports_content_filtering(self):
309
 
        return self._format.supports_content_filtering()
310
 
 
311
 
    def supports_views(self):
312
 
        return self.views.supports_views()
313
 
 
314
311
    def _set_inventory(self, inv, dirty):
315
312
        """Set the internal cached inventory.
316
313
 
321
318
            False then the inventory is the same as that on disk and any
322
319
            serialisation would be unneeded overhead.
323
320
        """
 
321
        assert inv.root is not None
324
322
        self._inventory = inv
325
323
        self._inventory_is_modified = dirty
326
324
 
330
328
 
331
329
        """
332
330
        if path is None:
333
 
            path = osutils.getcwd()
 
331
            path = os.path.getcwdu()
334
332
        control = bzrdir.BzrDir.open(path, _unsupported)
335
333
        return control.open_workingtree(_unsupported)
336
 
 
 
334
        
337
335
    @staticmethod
338
336
    def open_containing(path=None):
339
337
        """Open an existing working tree which has its root about path.
340
 
 
 
338
        
341
339
        This probes for a working tree at path and searches upwards from there.
342
340
 
343
341
        Basically we keep looking up until we find the control directory or
350
348
        if path is None:
351
349
            path = osutils.getcwd()
352
350
        control, relpath = bzrdir.BzrDir.open_containing(path)
 
351
 
353
352
        return control.open_workingtree(), relpath
354
353
 
355
354
    @staticmethod
356
 
    def open_containing_paths(file_list, default_directory='.',
357
 
        canonicalize=True, apply_view=True):
358
 
        """Open the WorkingTree that contains a set of paths.
359
 
 
360
 
        Fail if the paths given are not all in a single tree.
361
 
 
362
 
        This is used for the many command-line interfaces that take a list of
363
 
        any number of files and that require they all be in the same tree.
364
 
        """
365
 
        # recommended replacement for builtins.internal_tree_files
366
 
        if file_list is None or len(file_list) == 0:
367
 
            tree = WorkingTree.open_containing(default_directory)[0]
368
 
            # XXX: doesn't really belong here, and seems to have the strange
369
 
            # side effect of making it return a bunch of files, not the whole
370
 
            # tree -- mbp 20100716
371
 
            if tree.supports_views() and apply_view:
372
 
                view_files = tree.views.lookup_view()
373
 
                if view_files:
374
 
                    file_list = view_files
375
 
                    view_str = views.view_display_str(view_files)
376
 
                    note("Ignoring files outside view. View is %s" % view_str)
377
 
            return tree, file_list
378
 
        tree = WorkingTree.open_containing(file_list[0])[0]
379
 
        return tree, tree.safe_relpath_files(file_list, canonicalize,
380
 
            apply_view=apply_view)
381
 
 
382
 
    def safe_relpath_files(self, file_list, canonicalize=True, apply_view=True):
383
 
        """Convert file_list into a list of relpaths in tree.
384
 
 
385
 
        :param self: A tree to operate on.
386
 
        :param file_list: A list of user provided paths or None.
387
 
        :param apply_view: if True and a view is set, apply it or check that
388
 
            specified files are within it
389
 
        :return: A list of relative paths.
390
 
        :raises errors.PathNotChild: When a provided path is in a different self
391
 
            than self.
392
 
        """
393
 
        if file_list is None:
394
 
            return None
395
 
        if self.supports_views() and apply_view:
396
 
            view_files = self.views.lookup_view()
397
 
        else:
398
 
            view_files = []
399
 
        new_list = []
400
 
        # self.relpath exists as a "thunk" to osutils, but canonical_relpath
401
 
        # doesn't - fix that up here before we enter the loop.
402
 
        if canonicalize:
403
 
            fixer = lambda p: osutils.canonical_relpath(self.basedir, p)
404
 
        else:
405
 
            fixer = self.relpath
406
 
        for filename in file_list:
407
 
            relpath = fixer(osutils.dereference_path(filename))
408
 
            if view_files and not osutils.is_inside_any(view_files, relpath):
409
 
                raise errors.FileOutsideView(filename, view_files)
410
 
            new_list.append(relpath)
411
 
        return new_list
412
 
 
413
 
    @staticmethod
414
355
    def open_downlevel(path=None):
415
356
        """Open an unsupported working tree.
416
357
 
429
370
                return True, None
430
371
            else:
431
372
                return True, tree
432
 
        t = transport.get_transport(location)
433
 
        iterator = bzrdir.BzrDir.find_bzrdirs(t, evaluate=evaluate,
 
373
        transport = get_transport(location)
 
374
        iterator = bzrdir.BzrDir.find_bzrdirs(transport, evaluate=evaluate,
434
375
                                              list_current=list_current)
435
 
        return [tr for tr in iterator if tr is not None]
 
376
        return [t for t in iterator if t is not None]
436
377
 
437
378
    # should be deprecated - this is slow and in any case treating them as a
438
379
    # container is (we now know) bad style -- mbp 20070302
461
402
 
462
403
    def basis_tree(self):
463
404
        """Return RevisionTree for the current last revision.
464
 
 
 
405
        
465
406
        If the left most parent is a ghost then the returned tree will be an
466
 
        empty tree - one obtained by calling
467
 
        repository.revision_tree(NULL_REVISION).
 
407
        empty tree - one obtained by calling repository.revision_tree(None).
468
408
        """
469
409
        try:
470
410
            revision_id = self.get_parent_ids()[0]
472
412
            # no parents, return an empty revision tree.
473
413
            # in the future this should return the tree for
474
414
            # 'empty:' - the implicit root empty tree.
475
 
            return self.branch.repository.revision_tree(
476
 
                       _mod_revision.NULL_REVISION)
 
415
            return self.branch.repository.revision_tree(None)
477
416
        try:
478
417
            return self.revision_tree(revision_id)
479
418
        except errors.NoSuchRevision:
483
422
        # at this point ?
484
423
        try:
485
424
            return self.branch.repository.revision_tree(revision_id)
486
 
        except (errors.RevisionNotPresent, errors.NoSuchRevision):
 
425
        except errors.RevisionNotPresent:
487
426
            # the basis tree *may* be a ghost or a low level error may have
488
 
            # occurred. If the revision is present, its a problem, if its not
 
427
            # occured. If the revision is present, its a problem, if its not
489
428
            # its a ghost.
490
429
            if self.branch.repository.has_revision(revision_id):
491
430
                raise
492
431
            # the basis tree is a ghost so return an empty tree.
493
 
            return self.branch.repository.revision_tree(
494
 
                       _mod_revision.NULL_REVISION)
 
432
            return self.branch.repository.revision_tree(None)
495
433
 
496
434
    def _cleanup(self):
497
435
        self._flush_ignore_list_cache()
498
436
 
 
437
    @staticmethod
 
438
    @deprecated_method(zero_eight)
 
439
    def create(branch, directory):
 
440
        """Create a workingtree for branch at directory.
 
441
 
 
442
        If existing_directory already exists it must have a .bzr directory.
 
443
        If it does not exist, it will be created.
 
444
 
 
445
        This returns a new WorkingTree object for the new checkout.
 
446
 
 
447
        TODO FIXME RBC 20060124 when we have checkout formats in place this
 
448
        should accept an optional revisionid to checkout [and reject this if
 
449
        checking out into the same dir as a pre-checkout-aware branch format.]
 
450
 
 
451
        XXX: When BzrDir is present, these should be created through that 
 
452
        interface instead.
 
453
        """
 
454
        warnings.warn('delete WorkingTree.create', stacklevel=3)
 
455
        transport = get_transport(directory)
 
456
        if branch.bzrdir.root_transport.base == transport.base:
 
457
            # same dir 
 
458
            return branch.bzrdir.create_workingtree()
 
459
        # different directory, 
 
460
        # create a branch reference
 
461
        # and now a working tree.
 
462
        raise NotImplementedError
 
463
 
 
464
    @staticmethod
 
465
    @deprecated_method(zero_eight)
 
466
    def create_standalone(directory):
 
467
        """Create a checkout and a branch and a repo at directory.
 
468
 
 
469
        Directory must exist and be empty.
 
470
 
 
471
        please use BzrDir.create_standalone_workingtree
 
472
        """
 
473
        return bzrdir.BzrDir.create_standalone_workingtree(directory)
 
474
 
499
475
    def relpath(self, path):
500
476
        """Return the local path portion from a given path.
501
 
 
502
 
        The path may be absolute or relative. If its a relative path it is
 
477
        
 
478
        The path may be absolute or relative. If its a relative path it is 
503
479
        interpreted relative to the python current working directory.
504
480
        """
505
481
        return osutils.relpath(self.basedir, path)
507
483
    def has_filename(self, filename):
508
484
        return osutils.lexists(self.abspath(filename))
509
485
 
510
 
    def get_file(self, file_id, path=None, filtered=True):
511
 
        return self.get_file_with_stat(file_id, path, filtered=filtered)[0]
512
 
 
513
 
    def get_file_with_stat(self, file_id, path=None, filtered=True,
514
 
        _fstat=os.fstat):
515
 
        """See Tree.get_file_with_stat."""
 
486
    def get_file(self, file_id, path=None):
516
487
        if path is None:
517
488
            path = self.id2path(file_id)
518
 
        file_obj = self.get_file_byname(path, filtered=False)
519
 
        stat_value = _fstat(file_obj.fileno())
520
 
        if filtered and self.supports_content_filtering():
521
 
            filters = self._content_filter_stack(path)
522
 
            file_obj = filtered_input_file(file_obj, filters)
523
 
        return (file_obj, stat_value)
524
 
 
525
 
    def get_file_text(self, file_id, path=None, filtered=True):
526
 
        my_file = self.get_file(file_id, path=path, filtered=filtered)
527
 
        try:
528
 
            return my_file.read()
529
 
        finally:
530
 
            my_file.close()
531
 
 
532
 
    def get_file_byname(self, filename, filtered=True):
533
 
        path = self.abspath(filename)
534
 
        f = file(path, 'rb')
535
 
        if filtered and self.supports_content_filtering():
536
 
            filters = self._content_filter_stack(filename)
537
 
            return filtered_input_file(f, filters)
538
 
        else:
539
 
            return f
540
 
 
541
 
    def get_file_lines(self, file_id, path=None, filtered=True):
542
 
        """See Tree.get_file_lines()"""
543
 
        file = self.get_file(file_id, path, filtered=filtered)
544
 
        try:
545
 
            return file.readlines()
546
 
        finally:
547
 
            file.close()
 
489
        return self.get_file_byname(path)
 
490
 
 
491
    def get_file_text(self, file_id):
 
492
        return self.get_file(file_id).read()
 
493
 
 
494
    def get_file_byname(self, filename):
 
495
        return file(self.abspath(filename), 'rb')
548
496
 
549
497
    @needs_read_lock
550
498
    def annotate_iter(self, file_id, default_revision=CURRENT_REVISION):
557
505
        incorrectly attributed to CURRENT_REVISION (but after committing, the
558
506
        attribution will be correct).
559
507
        """
560
 
        maybe_file_parent_keys = []
561
 
        for parent_id in self.get_parent_ids():
562
 
            try:
563
 
                parent_tree = self.revision_tree(parent_id)
564
 
            except errors.NoSuchRevisionInTree:
565
 
                parent_tree = self.branch.repository.revision_tree(parent_id)
566
 
            parent_tree.lock_read()
567
 
            try:
568
 
                if file_id not in parent_tree:
569
 
                    continue
570
 
                ie = parent_tree.inventory[file_id]
571
 
                if ie.kind != 'file':
572
 
                    # Note: this is slightly unnecessary, because symlinks and
573
 
                    # directories have a "text" which is the empty text, and we
574
 
                    # know that won't mess up annotations. But it seems cleaner
575
 
                    continue
576
 
                parent_text_key = (file_id, ie.revision)
577
 
                if parent_text_key not in maybe_file_parent_keys:
578
 
                    maybe_file_parent_keys.append(parent_text_key)
579
 
            finally:
580
 
                parent_tree.unlock()
581
 
        graph = _mod_graph.Graph(self.branch.repository.texts)
582
 
        heads = graph.heads(maybe_file_parent_keys)
583
 
        file_parent_keys = []
584
 
        for key in maybe_file_parent_keys:
585
 
            if key in heads:
586
 
                file_parent_keys.append(key)
587
 
 
588
 
        # Now we have the parents of this content
589
 
        annotator = self.branch.repository.texts.get_annotator()
590
 
        text = self.get_file_text(file_id)
591
 
        this_key =(file_id, default_revision)
592
 
        annotator.add_special_text(this_key, file_parent_keys, text)
593
 
        annotations = [(key[-1], line)
594
 
                       for key, line in annotator.annotate_flat(this_key)]
595
 
        return annotations
 
508
        basis = self.basis_tree()
 
509
        basis.lock_read()
 
510
        try:
 
511
            changes = self.iter_changes(basis, True, [self.id2path(file_id)],
 
512
                require_versioned=True).next()
 
513
            changed_content, kind = changes[2], changes[6]
 
514
            if not changed_content:
 
515
                return basis.annotate_iter(file_id)
 
516
            if kind[1] is None:
 
517
                return None
 
518
            import annotate
 
519
            if kind[0] != 'file':
 
520
                old_lines = []
 
521
            else:
 
522
                old_lines = list(basis.annotate_iter(file_id))
 
523
            old = [old_lines]
 
524
            for tree in self.branch.repository.revision_trees(
 
525
                self.get_parent_ids()[1:]):
 
526
                if file_id not in tree:
 
527
                    continue
 
528
                old.append(list(tree.annotate_iter(file_id)))
 
529
            return annotate.reannotate(old, self.get_file(file_id).readlines(),
 
530
                                       default_revision)
 
531
        finally:
 
532
            basis.unlock()
596
533
 
597
534
    def _get_ancestors(self, default_revision):
598
535
        ancestors = set([default_revision])
603
540
 
604
541
    def get_parent_ids(self):
605
542
        """See Tree.get_parent_ids.
606
 
 
 
543
        
607
544
        This implementation reads the pending merges list and last_revision
608
545
        value and uses that to decide what the parents list should be.
609
546
        """
613
550
        else:
614
551
            parents = [last_rev]
615
552
        try:
616
 
            merges_bytes = self._transport.get_bytes('pending-merges')
 
553
            merges_file = self._control_files.get('pending-merges')
617
554
        except errors.NoSuchFile:
618
555
            pass
619
556
        else:
620
 
            for l in osutils.split_lines(merges_bytes):
 
557
            for l in merges_file.readlines():
621
558
                revision_id = l.rstrip('\n')
622
559
                parents.append(revision_id)
623
560
        return parents
626
563
    def get_root_id(self):
627
564
        """Return the id of this trees root"""
628
565
        return self._inventory.root.file_id
629
 
 
 
566
        
630
567
    def _get_store_filename(self, file_id):
631
568
        ## XXX: badly named; this is not in the store at all
632
569
        return self.abspath(self.id2path(file_id))
634
571
    @needs_read_lock
635
572
    def clone(self, to_bzrdir, revision_id=None):
636
573
        """Duplicate this working tree into to_bzr, including all state.
637
 
 
 
574
        
638
575
        Specifically modified files are kept as modified, but
639
576
        ignored and unknown files are discarded.
640
577
 
641
578
        If you want to make a new line of development, see bzrdir.sprout()
642
579
 
643
580
        revision
644
 
            If not None, the cloned tree will have its last revision set to
645
 
            revision, and difference between the source trees last revision
 
581
            If not None, the cloned tree will have its last revision set to 
 
582
            revision, and and difference between the source trees last revision
646
583
            and this one merged in.
647
584
        """
648
585
        # assumes the target bzr dir format is compatible.
649
 
        result = to_bzrdir.create_workingtree()
 
586
        result = self._format.initialize(to_bzrdir)
650
587
        self.copy_content_into(result, revision_id)
651
588
        return result
652
589
 
681
618
    __contains__ = has_id
682
619
 
683
620
    def get_file_size(self, file_id):
684
 
        """See Tree.get_file_size"""
685
 
        # XXX: this returns the on-disk size; it should probably return the
686
 
        # canonical size
687
 
        try:
688
 
            return os.path.getsize(self.id2abspath(file_id))
689
 
        except OSError, e:
690
 
            if e.errno != errno.ENOENT:
691
 
                raise
692
 
            else:
693
 
                return None
 
621
        return os.path.getsize(self.id2abspath(file_id))
694
622
 
695
623
    @needs_read_lock
696
624
    def get_file_sha1(self, file_id, path=None, stat_value=None):
705
633
 
706
634
    def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
707
635
        file_id = self.path2id(path)
708
 
        if file_id is None:
709
 
            # For unversioned files on win32, we just assume they are not
710
 
            # executable
711
 
            return False
712
636
        return self._inventory[file_id].executable
713
637
 
714
638
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
736
660
        """See MutableTree._add."""
737
661
        # TODO: Re-adding a file that is removed in the working copy
738
662
        # should probably put it back with the previous ID.
739
 
        # the read and write working inventory should not occur in this
 
663
        # the read and write working inventory should not occur in this 
740
664
        # function - they should be part of lock_write and unlock.
741
665
        inv = self.inventory
742
666
        for f, file_id, kind in zip(files, ids, kinds):
 
667
            assert kind is not None
743
668
            if file_id is None:
744
669
                inv.add_path(f, kind=kind)
745
670
            else:
824
749
            raise
825
750
        kind = _mapper(stat_result.st_mode)
826
751
        if kind == 'file':
827
 
            return self._file_content_summary(path, stat_result)
 
752
            size = stat_result.st_size
 
753
            # try for a stat cache lookup
 
754
            executable = self._is_executable_from_path_and_stat(path, stat_result)
 
755
            return (kind, size, executable, self._sha_from_stat(
 
756
                path, stat_result))
828
757
        elif kind == 'directory':
829
758
            # perhaps it looks like a plain directory, but it's really a
830
759
            # reference.
832
761
                kind = 'tree-reference'
833
762
            return kind, None, None, None
834
763
        elif kind == 'symlink':
835
 
            target = osutils.readlink(abspath)
836
 
            return ('symlink', None, None, target)
 
764
            return ('symlink', None, None, os.readlink(abspath))
837
765
        else:
838
766
            return (kind, None, None, None)
839
767
 
840
 
    def _file_content_summary(self, path, stat_result):
841
 
        size = stat_result.st_size
842
 
        executable = self._is_executable_from_path_and_stat(path, stat_result)
843
 
        # try for a stat cache lookup
844
 
        return ('file', size, executable, self._sha_from_stat(
845
 
            path, stat_result))
 
768
    @deprecated_method(zero_eleven)
 
769
    @needs_read_lock
 
770
    def pending_merges(self):
 
771
        """Return a list of pending merges.
 
772
 
 
773
        These are revisions that have been merged into the working
 
774
        directory but not yet committed.
 
775
 
 
776
        As of 0.11 this is deprecated. Please see WorkingTree.get_parent_ids()
 
777
        instead - which is available on all tree objects.
 
778
        """
 
779
        return self.get_parent_ids()[1:]
846
780
 
847
781
    def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
848
782
        """Common ghost checking functionality from set_parent_*.
858
792
 
859
793
    def _set_merges_from_parent_ids(self, parent_ids):
860
794
        merges = parent_ids[1:]
861
 
        self._transport.put_bytes('pending-merges', '\n'.join(merges),
862
 
            mode=self.bzrdir._get_file_mode())
863
 
 
864
 
    def _filter_parent_ids_by_ancestry(self, revision_ids):
865
 
        """Check that all merged revisions are proper 'heads'.
866
 
 
867
 
        This will always return the first revision_id, and any merged revisions
868
 
        which are
869
 
        """
870
 
        if len(revision_ids) == 0:
871
 
            return revision_ids
872
 
        graph = self.branch.repository.get_graph()
873
 
        heads = graph.heads(revision_ids)
874
 
        new_revision_ids = revision_ids[:1]
875
 
        for revision_id in revision_ids[1:]:
876
 
            if revision_id in heads and revision_id not in new_revision_ids:
877
 
                new_revision_ids.append(revision_id)
878
 
        if new_revision_ids != revision_ids:
879
 
            trace.mutter('requested to set revision_ids = %s,'
880
 
                         ' but filtered to %s', revision_ids, new_revision_ids)
881
 
        return new_revision_ids
 
795
        self._control_files.put_bytes('pending-merges', '\n'.join(merges))
882
796
 
883
797
    @needs_tree_write_lock
884
798
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
885
799
        """Set the parent ids to revision_ids.
886
 
 
 
800
        
887
801
        See also set_parent_trees. This api will try to retrieve the tree data
888
802
        for each element of revision_ids from the trees repository. If you have
889
803
        tree data already available, it is more efficient to use
898
812
        for revision_id in revision_ids:
899
813
            _mod_revision.check_not_reserved_id(revision_id)
900
814
 
901
 
        revision_ids = self._filter_parent_ids_by_ancestry(revision_ids)
902
 
 
903
815
        if len(revision_ids) > 0:
904
816
            self.set_last_revision(revision_ids[0])
905
817
        else:
917
829
        self._check_parents_for_ghosts(parent_ids,
918
830
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
919
831
 
920
 
        parent_ids = self._filter_parent_ids_by_ancestry(parent_ids)
921
 
 
922
832
        if len(parent_ids) == 0:
923
833
            leftmost_parent_id = _mod_revision.NULL_REVISION
924
834
            leftmost_parent_tree = None
964
874
    def _put_rio(self, filename, stanzas, header):
965
875
        self._must_be_locked()
966
876
        my_file = rio_file(stanzas, header)
967
 
        self._transport.put_file(filename, my_file,
968
 
            mode=self.bzrdir._get_file_mode())
 
877
        self._control_files.put(filename, my_file)
969
878
 
970
879
    @needs_write_lock # because merge pulls data into the branch.
971
880
    def merge_from_branch(self, branch, to_revision=None, from_revision=None,
972
 
                          merge_type=None, force=False):
 
881
        merge_type=None):
973
882
        """Merge from a branch into this working tree.
974
883
 
975
884
        :param branch: The branch to merge from.
979
888
            branch.last_revision().
980
889
        """
981
890
        from bzrlib.merge import Merger, Merge3Merger
982
 
        merger = Merger(self.branch, this_tree=self)
983
 
        # check that there are no local alterations
984
 
        if not force and self.has_changes():
985
 
            raise errors.UncommittedChanges(self)
986
 
        if to_revision is None:
987
 
            to_revision = _mod_revision.ensure_null(branch.last_revision())
988
 
        merger.other_rev_id = to_revision
989
 
        if _mod_revision.is_null(merger.other_rev_id):
990
 
            raise errors.NoCommits(branch)
991
 
        self.branch.fetch(branch, last_revision=merger.other_rev_id)
992
 
        merger.other_basis = merger.other_rev_id
993
 
        merger.other_tree = self.branch.repository.revision_tree(
994
 
            merger.other_rev_id)
995
 
        merger.other_branch = branch
996
 
        if from_revision is None:
997
 
            merger.find_base()
998
 
        else:
999
 
            merger.set_base_revision(from_revision, branch)
1000
 
        if merger.base_rev_id == merger.other_rev_id:
1001
 
            raise errors.PointlessMerge
1002
 
        merger.backup_files = False
1003
 
        if merge_type is None:
1004
 
            merger.merge_type = Merge3Merger
1005
 
        else:
1006
 
            merger.merge_type = merge_type
1007
 
        merger.set_interesting_files(None)
1008
 
        merger.show_base = False
1009
 
        merger.reprocess = False
1010
 
        conflicts = merger.do_merge()
1011
 
        merger.set_pending()
 
891
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
892
        try:
 
893
            merger = Merger(self.branch, this_tree=self, pb=pb)
 
894
            merger.pp = ProgressPhase("Merge phase", 5, pb)
 
895
            merger.pp.next_phase()
 
896
            # check that there are no
 
897
            # local alterations
 
898
            merger.check_basis(check_clean=True, require_commits=False)
 
899
            if to_revision is None:
 
900
                to_revision = _mod_revision.ensure_null(branch.last_revision())
 
901
            merger.other_rev_id = to_revision
 
902
            if _mod_revision.is_null(merger.other_rev_id):
 
903
                raise errors.NoCommits(branch)
 
904
            self.branch.fetch(branch, last_revision=merger.other_rev_id)
 
905
            merger.other_basis = merger.other_rev_id
 
906
            merger.other_tree = self.branch.repository.revision_tree(
 
907
                merger.other_rev_id)
 
908
            merger.other_branch = branch
 
909
            merger.pp.next_phase()
 
910
            if from_revision is None:
 
911
                merger.find_base()
 
912
            else:
 
913
                merger.set_base_revision(from_revision, branch)
 
914
            if merger.base_rev_id == merger.other_rev_id:
 
915
                raise errors.PointlessMerge
 
916
            merger.backup_files = False
 
917
            if merge_type is None:
 
918
                merger.merge_type = Merge3Merger
 
919
            else:
 
920
                merger.merge_type = merge_type
 
921
            merger.set_interesting_files(None)
 
922
            merger.show_base = False
 
923
            merger.reprocess = False
 
924
            conflicts = merger.do_merge()
 
925
            merger.set_pending()
 
926
        finally:
 
927
            pb.finished()
1012
928
        return conflicts
1013
929
 
1014
930
    @needs_read_lock
1015
931
    def merge_modified(self):
1016
932
        """Return a dictionary of files modified by a merge.
1017
933
 
1018
 
        The list is initialized by WorkingTree.set_merge_modified, which is
 
934
        The list is initialized by WorkingTree.set_merge_modified, which is 
1019
935
        typically called after we make some automatic updates to the tree
1020
936
        because of a merge.
1021
937
 
1023
939
        still in the working inventory and have that text hash.
1024
940
        """
1025
941
        try:
1026
 
            hashfile = self._transport.get('merge-hashes')
 
942
            hashfile = self._control_files.get('merge-hashes')
1027
943
        except errors.NoSuchFile:
1028
944
            return {}
 
945
        merge_hashes = {}
1029
946
        try:
1030
 
            merge_hashes = {}
1031
 
            try:
1032
 
                if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
1033
 
                    raise errors.MergeModifiedFormatError()
1034
 
            except StopIteration:
 
947
            if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
1035
948
                raise errors.MergeModifiedFormatError()
1036
 
            for s in RioReader(hashfile):
1037
 
                # RioReader reads in Unicode, so convert file_ids back to utf8
1038
 
                file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
1039
 
                if file_id not in self.inventory:
1040
 
                    continue
1041
 
                text_hash = s.get("hash")
1042
 
                if text_hash == self.get_file_sha1(file_id):
1043
 
                    merge_hashes[file_id] = text_hash
1044
 
            return merge_hashes
1045
 
        finally:
1046
 
            hashfile.close()
 
949
        except StopIteration:
 
950
            raise errors.MergeModifiedFormatError()
 
951
        for s in RioReader(hashfile):
 
952
            # RioReader reads in Unicode, so convert file_ids back to utf8
 
953
            file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
 
954
            if file_id not in self.inventory:
 
955
                continue
 
956
            text_hash = s.get("hash")
 
957
            if text_hash == self.get_file_sha1(file_id):
 
958
                merge_hashes[file_id] = text_hash
 
959
        return merge_hashes
1047
960
 
1048
961
    @needs_write_lock
1049
962
    def mkdir(self, path, file_id=None):
1055
968
        return file_id
1056
969
 
1057
970
    def get_symlink_target(self, file_id):
1058
 
        abspath = self.id2abspath(file_id)
1059
 
        target = osutils.readlink(abspath)
1060
 
        return target
 
971
        return os.readlink(self.id2abspath(file_id))
1061
972
 
1062
973
    @needs_write_lock
1063
974
    def subsume(self, other_tree):
1113
1024
        return False
1114
1025
 
1115
1026
    def _directory_may_be_tree_reference(self, relpath):
1116
 
        # as a special case, if a directory contains control files then
 
1027
        # as a special case, if a directory contains control files then 
1117
1028
        # it's a tree reference, except that the root of the tree is not
1118
1029
        return relpath and osutils.isdir(self.abspath(relpath) + u"/.bzr")
1119
1030
        # TODO: We could ask all the control formats whether they
1130
1041
    @needs_tree_write_lock
1131
1042
    def extract(self, file_id, format=None):
1132
1043
        """Extract a subtree from this tree.
1133
 
 
 
1044
        
1134
1045
        A new branch will be created, relative to the path for this tree.
1135
1046
        """
1136
1047
        self.flush()
1141
1052
                transport = transport.clone(name)
1142
1053
                transport.ensure_base()
1143
1054
            return transport
1144
 
 
 
1055
            
1145
1056
        sub_path = self.id2path(file_id)
1146
1057
        branch_transport = mkdirs(sub_path)
1147
1058
        if format is None:
1161
1072
        tree_transport = self.bzrdir.root_transport.clone(sub_path)
1162
1073
        if tree_transport.base != branch_transport.base:
1163
1074
            tree_bzrdir = format.initialize_on_transport(tree_transport)
1164
 
            branch.BranchReferenceFormat().initialize(tree_bzrdir,
1165
 
                target_branch=new_branch)
 
1075
            branch.BranchReferenceFormat().initialize(tree_bzrdir, new_branch)
1166
1076
        else:
1167
1077
            tree_bzrdir = branch_bzrdir
1168
 
        wt = tree_bzrdir.create_workingtree(_mod_revision.NULL_REVISION)
 
1078
        wt = tree_bzrdir.create_workingtree(NULL_REVISION)
1169
1079
        wt.set_parent_ids(self.get_parent_ids())
1170
1080
        my_inv = self.inventory
1171
 
        child_inv = inventory.Inventory(root_id=None)
 
1081
        child_inv = Inventory(root_id=None)
1172
1082
        new_root = my_inv[file_id]
1173
1083
        my_inv.remove_recursive_id(file_id)
1174
1084
        new_root.parent_id = None
1192
1102
        sio = StringIO()
1193
1103
        self._serialize(self._inventory, sio)
1194
1104
        sio.seek(0)
1195
 
        self._transport.put_file('inventory', sio,
1196
 
            mode=self.bzrdir._get_file_mode())
 
1105
        self._control_files.put('inventory', sio)
1197
1106
        self._inventory_is_modified = False
1198
1107
 
1199
1108
    def _kind(self, relpath):
1200
1109
        return osutils.file_kind(self.abspath(relpath))
1201
1110
 
1202
 
    def list_files(self, include_root=False, from_dir=None, recursive=True):
1203
 
        """List all files as (path, class, kind, id, entry).
 
1111
    def list_files(self, include_root=False):
 
1112
        """Recursively list all files as (path, class, kind, id, entry).
1204
1113
 
1205
1114
        Lists, but does not descend into unversioned directories.
 
1115
 
1206
1116
        This does not include files that have been deleted in this
1207
 
        tree. Skips the control directory.
 
1117
        tree.
1208
1118
 
1209
 
        :param include_root: if True, return an entry for the root
1210
 
        :param from_dir: start from this directory or None for the root
1211
 
        :param recursive: whether to recurse into subdirectories or not
 
1119
        Skips the control directory.
1212
1120
        """
1213
1121
        # list_files is an iterator, so @needs_read_lock doesn't work properly
1214
1122
        # with it. So callers should be careful to always read_lock the tree.
1216
1124
            raise errors.ObjectNotLocked(self)
1217
1125
 
1218
1126
        inv = self.inventory
1219
 
        if from_dir is None and include_root is True:
 
1127
        if include_root is True:
1220
1128
            yield ('', 'V', 'directory', inv.root.file_id, inv.root)
1221
1129
        # Convert these into local objects to save lookup times
1222
1130
        pathjoin = osutils.pathjoin
1229
1137
        fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
1230
1138
 
1231
1139
        # directory file_id, relative path, absolute path, reverse sorted children
1232
 
        if from_dir is not None:
1233
 
            from_dir_id = inv.path2id(from_dir)
1234
 
            if from_dir_id is None:
1235
 
                # Directory not versioned
1236
 
                return
1237
 
            from_dir_abspath = pathjoin(self.basedir, from_dir)
1238
 
        else:
1239
 
            from_dir_id = inv.root.file_id
1240
 
            from_dir_abspath = self.basedir
1241
 
        children = os.listdir(from_dir_abspath)
 
1140
        children = os.listdir(self.basedir)
1242
1141
        children.sort()
1243
 
        # jam 20060527 The kernel sized tree seems equivalent whether we
 
1142
        # jam 20060527 The kernel sized tree seems equivalent whether we 
1244
1143
        # use a deque and popleft to keep them sorted, or if we use a plain
1245
1144
        # list and just reverse() them.
1246
1145
        children = collections.deque(children)
1247
 
        stack = [(from_dir_id, u'', from_dir_abspath, children)]
 
1146
        stack = [(inv.root.file_id, u'', self.basedir, children)]
1248
1147
        while stack:
1249
1148
            from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
1250
1149
 
1266
1165
 
1267
1166
                # absolute path
1268
1167
                fap = from_dir_abspath + '/' + f
1269
 
 
1270
 
                dir_ie = inv[from_dir_id]
1271
 
                if dir_ie.kind == 'directory':
1272
 
                    f_ie = dir_ie.children.get(f)
1273
 
                else:
1274
 
                    f_ie = None
 
1168
                
 
1169
                f_ie = inv.get_child(from_dir_id, f)
1275
1170
                if f_ie:
1276
1171
                    c = 'V'
1277
1172
                elif self.is_ignored(fp[1:]):
1278
1173
                    c = 'I'
1279
1174
                else:
1280
 
                    # we may not have found this file, because of a unicode
1281
 
                    # issue, or because the directory was actually a symlink.
 
1175
                    # we may not have found this file, because of a unicode issue
1282
1176
                    f_norm, can_access = osutils.normalized_filename(f)
1283
1177
                    if f == f_norm or not can_access:
1284
1178
                        # No change, so treat this file normally
1309
1203
                    except KeyError:
1310
1204
                        yield fp[1:], c, fk, None, TreeEntry()
1311
1205
                    continue
1312
 
 
 
1206
                
1313
1207
                if fk != 'directory':
1314
1208
                    continue
1315
1209
 
1316
 
                # But do this child first if recursing down
1317
 
                if recursive:
1318
 
                    new_children = os.listdir(fap)
1319
 
                    new_children.sort()
1320
 
                    new_children = collections.deque(new_children)
1321
 
                    stack.append((f_ie.file_id, fp, fap, new_children))
1322
 
                    # Break out of inner loop,
1323
 
                    # so that we start outer loop with child
1324
 
                    break
 
1210
                # But do this child first
 
1211
                new_children = os.listdir(fap)
 
1212
                new_children.sort()
 
1213
                new_children = collections.deque(new_children)
 
1214
                stack.append((f_ie.file_id, fp, fap, new_children))
 
1215
                # Break out of inner loop,
 
1216
                # so that we start outer loop with child
 
1217
                break
1325
1218
            else:
1326
1219
                # if we finished all children, pop it off the stack
1327
1220
                stack.pop()
1328
1221
 
1329
1222
    @needs_tree_write_lock
1330
 
    def move(self, from_paths, to_dir=None, after=False):
 
1223
    def move(self, from_paths, to_dir=None, after=False, **kwargs):
1331
1224
        """Rename files.
1332
1225
 
1333
1226
        to_dir must exist in the inventory.
1334
1227
 
1335
1228
        If to_dir exists and is a directory, the files are moved into
1336
 
        it, keeping their old names.
 
1229
        it, keeping their old names.  
1337
1230
 
1338
1231
        Note that to_dir is only the last component of the new name;
1339
1232
        this doesn't change the directory.
1367
1260
 
1368
1261
        # check for deprecated use of signature
1369
1262
        if to_dir is None:
1370
 
            raise TypeError('You must supply a target directory')
 
1263
            to_dir = kwargs.get('to_name', None)
 
1264
            if to_dir is None:
 
1265
                raise TypeError('You must supply a target directory')
 
1266
            else:
 
1267
                symbol_versioning.warn('The parameter to_name was deprecated'
 
1268
                                       ' in version 0.13. Use to_dir instead',
 
1269
                                       DeprecationWarning)
 
1270
 
1371
1271
        # check destination directory
1372
 
        if isinstance(from_paths, basestring):
1373
 
            raise ValueError()
 
1272
        assert not isinstance(from_paths, basestring)
1374
1273
        inv = self.inventory
1375
1274
        to_abs = self.abspath(to_dir)
1376
1275
        if not isdir(to_abs):
1460
1359
                only_change_inv = True
1461
1360
            elif self.has_filename(from_rel) and not self.has_filename(to_rel):
1462
1361
                only_change_inv = False
1463
 
            elif (not self.case_sensitive
1464
 
                  and from_rel.lower() == to_rel.lower()
1465
 
                  and self.has_filename(from_rel)):
 
1362
            elif (sys.platform == 'win32'
 
1363
                and from_rel.lower() == to_rel.lower()
 
1364
                and self.has_filename(from_rel)):
1466
1365
                only_change_inv = False
1467
1366
            else:
1468
1367
                # something is wrong, so lets determine what exactly
1498
1397
        inv = self.inventory
1499
1398
        for entry in moved:
1500
1399
            try:
1501
 
                self._move_entry(WorkingTree._RenameEntry(
1502
 
                    entry.to_rel, entry.from_id,
 
1400
                self._move_entry(_RenameEntry(entry.to_rel, entry.from_id,
1503
1401
                    entry.to_tail, entry.to_parent_id, entry.from_rel,
1504
1402
                    entry.from_tail, entry.from_parent_id,
1505
1403
                    entry.only_change_inv))
1556
1454
        from_tail = splitpath(from_rel)[-1]
1557
1455
        from_id = inv.path2id(from_rel)
1558
1456
        if from_id is None:
1559
 
            # if file is missing in the inventory maybe it's in the basis_tree
1560
 
            basis_tree = self.branch.basis_tree()
1561
 
            from_id = basis_tree.path2id(from_rel)
1562
 
            if from_id is None:
1563
 
                raise errors.BzrRenameFailedError(from_rel,to_rel,
1564
 
                    errors.NotVersionedError(path=str(from_rel)))
1565
 
            # put entry back in the inventory so we can rename it
1566
 
            from_entry = basis_tree.inventory[from_id].copy()
1567
 
            inv.add(from_entry)
1568
 
        else:
1569
 
            from_entry = inv[from_id]
 
1457
            raise errors.BzrRenameFailedError(from_rel,to_rel,
 
1458
                errors.NotVersionedError(path=str(from_rel)))
 
1459
        from_entry = inv[from_id]
1570
1460
        from_parent_id = from_entry.parent_id
1571
1461
        to_dir, to_tail = os.path.split(to_rel)
1572
1462
        to_dir_id = inv.path2id(to_dir)
1618
1508
        These are files in the working directory that are not versioned or
1619
1509
        control files or ignored.
1620
1510
        """
1621
 
        # force the extras method to be fully executed before returning, to
 
1511
        # force the extras method to be fully executed before returning, to 
1622
1512
        # prevent race conditions with the lock
1623
1513
        return iter(
1624
1514
            [subp for subp in self.extras() if not self.is_ignored(subp)])
1634
1524
        :raises: NoSuchId if any fileid is not currently versioned.
1635
1525
        """
1636
1526
        for file_id in file_ids:
1637
 
            if file_id not in self._inventory:
1638
 
                raise errors.NoSuchId(self, file_id)
1639
 
        for file_id in file_ids:
1640
1527
            if self._inventory.has_id(file_id):
1641
1528
                self._inventory.remove_recursive_id(file_id)
 
1529
            else:
 
1530
                raise errors.NoSuchId(self, file_id)
1642
1531
        if len(file_ids):
1643
 
            # in the future this should just set a dirty bit to wait for the
 
1532
            # in the future this should just set a dirty bit to wait for the 
1644
1533
            # final unlock. However, until all methods of workingtree start
1645
 
            # with the current in -memory inventory rather than triggering
 
1534
            # with the current in -memory inventory rather than triggering 
1646
1535
            # a read, it is more complex - we need to teach read_inventory
1647
1536
            # to know when to read, and when to not read first... and possibly
1648
1537
            # to save first when the in memory one may be corrupted.
1649
1538
            # so for now, we just only write it if it is indeed dirty.
1650
1539
            # - RBC 20060907
1651
1540
            self._write_inventory(self._inventory)
 
1541
    
 
1542
    @deprecated_method(zero_eight)
 
1543
    def iter_conflicts(self):
 
1544
        """List all files in the tree that have text or content conflicts.
 
1545
        DEPRECATED.  Use conflicts instead."""
 
1546
        return self._iter_conflicts()
1652
1547
 
1653
1548
    def _iter_conflicts(self):
1654
1549
        conflicted = set()
1663
1558
 
1664
1559
    @needs_write_lock
1665
1560
    def pull(self, source, overwrite=False, stop_revision=None,
1666
 
             change_reporter=None, possible_transports=None, local=False):
 
1561
             change_reporter=None, possible_transports=None):
 
1562
        top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1667
1563
        source.lock_read()
1668
1564
        try:
 
1565
            pp = ProgressPhase("Pull phase", 2, top_pb)
 
1566
            pp.next_phase()
1669
1567
            old_revision_info = self.branch.last_revision_info()
1670
1568
            basis_tree = self.basis_tree()
1671
1569
            count = self.branch.pull(source, overwrite, stop_revision,
1672
 
                                     possible_transports=possible_transports,
1673
 
                                     local=local)
 
1570
                                     possible_transports=possible_transports)
1674
1571
            new_revision_info = self.branch.last_revision_info()
1675
1572
            if new_revision_info != old_revision_info:
 
1573
                pp.next_phase()
1676
1574
                repository = self.branch.repository
 
1575
                pb = bzrlib.ui.ui_factory.nested_progress_bar()
1677
1576
                basis_tree.lock_read()
1678
1577
                try:
1679
1578
                    new_basis_tree = self.branch.basis_tree()
1682
1581
                                new_basis_tree,
1683
1582
                                basis_tree,
1684
1583
                                this_tree=self,
1685
 
                                pb=None,
 
1584
                                pb=pb,
1686
1585
                                change_reporter=change_reporter)
1687
 
                    basis_root_id = basis_tree.get_root_id()
1688
 
                    new_root_id = new_basis_tree.get_root_id()
1689
 
                    if basis_root_id != new_root_id:
1690
 
                        self.set_root_id(new_root_id)
 
1586
                    if (basis_tree.inventory.root is None and
 
1587
                        new_basis_tree.inventory.root is not None):
 
1588
                        self.set_root_id(new_basis_tree.get_root_id())
1691
1589
                finally:
 
1590
                    pb.finished()
1692
1591
                    basis_tree.unlock()
1693
1592
                # TODO - dedup parents list with things merged by pull ?
1694
1593
                # reuse the revisiontree we merged against to set the new
1695
1594
                # tree data.
1696
1595
                parent_trees = [(self.branch.last_revision(), new_basis_tree)]
1697
 
                # we have to pull the merge trees out again, because
1698
 
                # merge_inner has set the ids. - this corner is not yet
 
1596
                # we have to pull the merge trees out again, because 
 
1597
                # merge_inner has set the ids. - this corner is not yet 
1699
1598
                # layered well enough to prevent double handling.
1700
1599
                # XXX TODO: Fix the double handling: telling the tree about
1701
1600
                # the already known parent data is wasteful.
1707
1606
            return count
1708
1607
        finally:
1709
1608
            source.unlock()
 
1609
            top_pb.finished()
1710
1610
 
1711
1611
    @needs_write_lock
1712
1612
    def put_file_bytes_non_atomic(self, file_id, bytes):
1738
1638
 
1739
1639
            fl = []
1740
1640
            for subf in os.listdir(dirabs):
1741
 
                if self.bzrdir.is_control_filename(subf):
 
1641
                if subf == '.bzr':
1742
1642
                    continue
1743
1643
                if subf not in dir_entry.children:
1744
 
                    try:
1745
 
                        (subf_norm,
1746
 
                         can_access) = osutils.normalized_filename(subf)
1747
 
                    except UnicodeDecodeError:
1748
 
                        path_os_enc = path.encode(osutils._fs_enc)
1749
 
                        relpath = path_os_enc + '/' + subf
1750
 
                        raise errors.BadFilenameEncoding(relpath,
1751
 
                                                         osutils._fs_enc)
 
1644
                    subf_norm, can_access = osutils.normalized_filename(subf)
1752
1645
                    if subf_norm != subf and can_access:
1753
1646
                        if subf_norm not in dir_entry.children:
1754
1647
                            fl.append(subf_norm)
1755
1648
                    else:
1756
1649
                        fl.append(subf)
1757
 
 
 
1650
            
1758
1651
            fl.sort()
1759
1652
            for subf in fl:
1760
1653
                subp = pathjoin(path, subf)
1797
1690
        r"""Check whether the filename matches an ignore pattern.
1798
1691
 
1799
1692
        Patterns containing '/' or '\' need to match the whole path;
1800
 
        others match against only the last component.  Patterns starting
1801
 
        with '!' are ignore exceptions.  Exceptions take precedence
1802
 
        over regular patterns and cause the filename to not be ignored.
 
1693
        others match against only the last component.
1803
1694
 
1804
1695
        If the file is ignored, returns the pattern which caused it to
1805
1696
        be ignored, otherwise None.  So this can simply be used as a
1806
1697
        boolean if desired."""
1807
1698
        if getattr(self, '_ignoreglobster', None) is None:
1808
 
            self._ignoreglobster = globbing.ExceptionGlobster(self.get_ignore_list())
 
1699
            self._ignoreglobster = globbing.Globster(self.get_ignore_list())
1809
1700
        return self._ignoreglobster.match(filename)
1810
1701
 
1811
1702
    def kind(self, file_id):
1861
1752
            raise errors.ObjectNotLocked(self)
1862
1753
 
1863
1754
    def lock_read(self):
1864
 
        """Lock the tree for reading.
1865
 
 
1866
 
        This also locks the branch, and can be unlocked via self.unlock().
1867
 
 
1868
 
        :return: A bzrlib.lock.LogicalLockResult.
1869
 
        """
 
1755
        """See Branch.lock_read, and WorkingTree.unlock."""
1870
1756
        if not self.is_locked():
1871
1757
            self._reset_data()
1872
1758
        self.branch.lock_read()
1873
1759
        try:
1874
 
            self._control_files.lock_read()
1875
 
            return LogicalLockResult(self.unlock)
 
1760
            return self._control_files.lock_read()
1876
1761
        except:
1877
1762
            self.branch.unlock()
1878
1763
            raise
1879
1764
 
1880
1765
    def lock_tree_write(self):
1881
 
        """See MutableTree.lock_tree_write, and WorkingTree.unlock.
1882
 
 
1883
 
        :return: A bzrlib.lock.LogicalLockResult.
1884
 
        """
 
1766
        """See MutableTree.lock_tree_write, and WorkingTree.unlock."""
1885
1767
        if not self.is_locked():
1886
1768
            self._reset_data()
1887
1769
        self.branch.lock_read()
1888
1770
        try:
1889
 
            self._control_files.lock_write()
1890
 
            return LogicalLockResult(self.unlock)
 
1771
            return self._control_files.lock_write()
1891
1772
        except:
1892
1773
            self.branch.unlock()
1893
1774
            raise
1894
1775
 
1895
1776
    def lock_write(self):
1896
 
        """See MutableTree.lock_write, and WorkingTree.unlock.
1897
 
 
1898
 
        :return: A bzrlib.lock.LogicalLockResult.
1899
 
        """
 
1777
        """See MutableTree.lock_write, and WorkingTree.unlock."""
1900
1778
        if not self.is_locked():
1901
1779
            self._reset_data()
1902
1780
        self.branch.lock_write()
1903
1781
        try:
1904
 
            self._control_files.lock_write()
1905
 
            return LogicalLockResult(self.unlock)
 
1782
            return self._control_files.lock_write()
1906
1783
        except:
1907
1784
            self.branch.unlock()
1908
1785
            raise
1916
1793
    def _reset_data(self):
1917
1794
        """Reset transient data that cannot be revalidated."""
1918
1795
        self._inventory_is_modified = False
1919
 
        f = self._transport.get('inventory')
1920
 
        try:
1921
 
            result = self._deserialize(f)
1922
 
        finally:
1923
 
            f.close()
 
1796
        result = self._deserialize(self._control_files.get('inventory'))
1924
1797
        self._set_inventory(result, dirty=False)
1925
1798
 
1926
1799
    @needs_tree_write_lock
1931
1804
 
1932
1805
    def _change_last_revision(self, new_revision):
1933
1806
        """Template method part of set_last_revision to perform the change.
1934
 
 
 
1807
        
1935
1808
        This is used to allow WorkingTree3 instances to not affect branch
1936
1809
        when their last revision is set.
1937
1810
        """
1947
1820
 
1948
1821
    def _write_basis_inventory(self, xml):
1949
1822
        """Write the basis inventory XML to the basis-inventory file"""
 
1823
        assert isinstance(xml, str), 'serialised xml must be bytestring.'
1950
1824
        path = self._basis_inventory_name()
1951
1825
        sio = StringIO(xml)
1952
 
        self._transport.put_file(path, sio,
1953
 
            mode=self.bzrdir._get_file_mode())
 
1826
        self._control_files.put(path, sio)
1954
1827
 
1955
1828
    def _create_basis_xml_from_inventory(self, revision_id, inventory):
1956
1829
        """Create the text that will be saved in basis-inventory"""
1963
1836
        # as commit already has that ready-to-use [while the format is the
1964
1837
        # same, that is].
1965
1838
        try:
1966
 
            # this double handles the inventory - unpack and repack -
 
1839
            # this double handles the inventory - unpack and repack - 
1967
1840
            # but is easier to understand. We can/should put a conditional
1968
1841
            # in here based on whether the inventory is in the latest format
1969
1842
            # - perhaps we should repack all inventories on a repository
1970
1843
            # upgrade ?
1971
1844
            # the fast path is to copy the raw xml from the repository. If the
1972
 
            # xml contains 'revision_id="', then we assume the right
 
1845
            # xml contains 'revision_id="', then we assume the right 
1973
1846
            # revision_id is set. We must check for this full string, because a
1974
1847
            # root node id can legitimately look like 'revision_id' but cannot
1975
1848
            # contain a '"'.
1976
 
            xml = self.branch.repository._get_inventory_xml(new_revision)
 
1849
            xml = self.branch.repository.get_inventory_xml(new_revision)
1977
1850
            firstline = xml.split('\n', 1)[0]
1978
 
            if (not 'revision_id="' in firstline or
 
1851
            if (not 'revision_id="' in firstline or 
1979
1852
                'format="7"' not in firstline):
1980
 
                inv = self.branch.repository._serializer.read_inventory_from_string(
1981
 
                    xml, new_revision)
 
1853
                inv = self.branch.repository.deserialise_inventory(
 
1854
                    new_revision, xml)
1982
1855
                xml = self._create_basis_xml_from_inventory(new_revision, inv)
1983
1856
            self._write_basis_inventory(xml)
1984
1857
        except (errors.NoSuchRevision, errors.RevisionNotPresent):
1987
1860
    def read_basis_inventory(self):
1988
1861
        """Read the cached basis inventory."""
1989
1862
        path = self._basis_inventory_name()
1990
 
        return self._transport.get_bytes(path)
1991
 
 
 
1863
        return self._control_files.get(path).read()
 
1864
        
1992
1865
    @needs_read_lock
1993
1866
    def read_working_inventory(self):
1994
1867
        """Read the working inventory.
1995
 
 
 
1868
        
1996
1869
        :raises errors.InventoryModified: read_working_inventory will fail
1997
1870
            when the current in memory inventory has been modified.
1998
1871
        """
1999
 
        # conceptually this should be an implementation detail of the tree.
 
1872
        # conceptually this should be an implementation detail of the tree. 
2000
1873
        # XXX: Deprecate this.
2001
1874
        # ElementTree does its own conversion from UTF-8, so open in
2002
1875
        # binary.
2003
1876
        if self._inventory_is_modified:
2004
1877
            raise errors.InventoryModified(self)
2005
 
        f = self._transport.get('inventory')
2006
 
        try:
2007
 
            result = self._deserialize(f)
2008
 
        finally:
2009
 
            f.close()
 
1878
        result = self._deserialize(self._control_files.get('inventory'))
2010
1879
        self._set_inventory(result, dirty=False)
2011
1880
        return result
2012
1881
 
2025
1894
 
2026
1895
        inv_delta = []
2027
1896
 
2028
 
        all_files = set() # specified and nested files 
 
1897
        new_files=set()
2029
1898
        unknown_nested_files=set()
2030
 
        if to_file is None:
2031
 
            to_file = sys.stdout
2032
 
 
2033
 
        files_to_backup = []
2034
1899
 
2035
1900
        def recurse_directory_to_add_files(directory):
2036
1901
            # Recurse directory and add all files
2037
1902
            # so we can check if they have changed.
2038
 
            for parent_info, file_infos in self.walkdirs(directory):
2039
 
                for relpath, basename, kind, lstat, fileid, kind in file_infos:
 
1903
            for parent_info, file_infos in\
 
1904
                osutils.walkdirs(self.abspath(directory),
 
1905
                    directory):
 
1906
                for relpath, basename, kind, lstat, abspath in file_infos:
2040
1907
                    # Is it versioned or ignored?
2041
 
                    if self.path2id(relpath):
 
1908
                    if self.path2id(relpath) or self.is_ignored(relpath):
2042
1909
                        # Add nested content for deletion.
2043
 
                        all_files.add(relpath)
 
1910
                        new_files.add(relpath)
2044
1911
                    else:
2045
 
                        # Files which are not versioned
 
1912
                        # Files which are not versioned and not ignored
2046
1913
                        # should be treated as unknown.
2047
 
                        files_to_backup.append(relpath)
 
1914
                        unknown_nested_files.add((relpath, None, kind))
2048
1915
 
2049
1916
        for filename in files:
2050
1917
            # Get file name into canonical form.
2051
1918
            abspath = self.abspath(filename)
2052
1919
            filename = self.relpath(abspath)
2053
1920
            if len(filename) > 0:
2054
 
                all_files.add(filename)
2055
 
                recurse_directory_to_add_files(filename)
 
1921
                new_files.add(filename)
 
1922
                if osutils.isdir(abspath):
 
1923
                    recurse_directory_to_add_files(filename)
2056
1924
 
2057
 
        files = list(all_files)
 
1925
        files = list(new_files)
2058
1926
 
2059
1927
        if len(files) == 0:
2060
1928
            return # nothing to do
2064
1932
 
2065
1933
        # Bail out if we are going to delete files we shouldn't
2066
1934
        if not keep_files and not force:
2067
 
            for (file_id, path, content_change, versioned, parent_id, name,
2068
 
                 kind, executable) in self.iter_changes(self.basis_tree(),
2069
 
                     include_unchanged=True, require_versioned=False,
2070
 
                     want_unversioned=True, specific_files=files):
2071
 
                if versioned[0] == False:
2072
 
                    # The record is unknown or newly added
2073
 
                    files_to_backup.append(path[1])
2074
 
                elif (content_change and (kind[1] is not None) and
2075
 
                        osutils.is_inside_any(files, path[1])):
2076
 
                    # Versioned and changed, but not deleted, and still
2077
 
                    # in one of the dirs to be deleted.
2078
 
                    files_to_backup.append(path[1])
2079
 
 
2080
 
        def backup(file_to_backup):
2081
 
            backup_name = self.bzrdir.generate_backup_name(file_to_backup)
2082
 
            osutils.rename(abs_path, self.abspath(backup_name))
2083
 
            return "removed %s (but kept a copy: %s)" % (file_to_backup, backup_name)
2084
 
 
2085
 
        # Build inv_delta and delete files where applicable,
 
1935
            has_changed_files = len(unknown_nested_files) > 0
 
1936
            if not has_changed_files:
 
1937
                for (file_id, path, content_change, versioned, parent_id, name,
 
1938
                     kind, executable) in self.iter_changes(self.basis_tree(),
 
1939
                         include_unchanged=True, require_versioned=False,
 
1940
                         want_unversioned=True, specific_files=files):
 
1941
                    if versioned == (False, False):
 
1942
                        # The record is unknown ...
 
1943
                        if not self.is_ignored(path[1]):
 
1944
                            # ... but not ignored
 
1945
                            has_changed_files = True
 
1946
                            break
 
1947
                    elif content_change and (kind[1] != None):
 
1948
                        # Versioned and changed, but not deleted
 
1949
                        has_changed_files = True
 
1950
                        break
 
1951
 
 
1952
            if has_changed_files:
 
1953
                # Make delta show ALL applicable changes in error message.
 
1954
                tree_delta = self.changes_from(self.basis_tree(),
 
1955
                    require_versioned=False, want_unversioned=True,
 
1956
                    specific_files=files)
 
1957
                for unknown_file in unknown_nested_files:
 
1958
                    if unknown_file not in tree_delta.unversioned:
 
1959
                        tree_delta.unversioned.extend((unknown_file,))
 
1960
                raise errors.BzrRemoveChangedFilesError(tree_delta)
 
1961
 
 
1962
        # Build inv_delta and delete files where applicaple,
2086
1963
        # do this before any modifications to inventory.
2087
1964
        for f in files:
2088
1965
            fid = self.path2id(f)
2096
1973
                        new_status = 'I'
2097
1974
                    else:
2098
1975
                        new_status = '?'
2099
 
                    # XXX: Really should be a more abstract reporter interface
2100
 
                    kind_ch = osutils.kind_marker(self.kind(fid))
2101
 
                    to_file.write(new_status + '       ' + f + kind_ch + '\n')
 
1976
                    textui.show_status(new_status, self.kind(fid), f,
 
1977
                                       to_file=to_file)
2102
1978
                # Unversion file
2103
1979
                inv_delta.append((f, None, fid, None))
2104
1980
                message = "removed %s" % (f,)
2110
1986
                        len(os.listdir(abs_path)) > 0):
2111
1987
                        if force:
2112
1988
                            osutils.rmtree(abs_path)
2113
 
                            message = "deleted %s" % (f,)
2114
1989
                        else:
2115
 
                            message = backup(f)
 
1990
                            message = "%s is not an empty directory "\
 
1991
                                "and won't be deleted." % (f,)
2116
1992
                    else:
2117
 
                        if f in files_to_backup:
2118
 
                            message = backup(f)
2119
 
                        else:
2120
 
                            osutils.delete_any(abs_path)
2121
 
                            message = "deleted %s" % (f,)
 
1993
                        osutils.delete_any(abs_path)
 
1994
                        message = "deleted %s" % (f,)
2122
1995
                elif message is not None:
2123
1996
                    # Only care if we haven't done anything yet.
2124
1997
                    message = "%s does not exist." % (f,)
2130
2003
 
2131
2004
    @needs_tree_write_lock
2132
2005
    def revert(self, filenames=None, old_tree=None, backups=True,
2133
 
               pb=None, report_changes=False):
 
2006
               pb=DummyProgress(), report_changes=False):
2134
2007
        from bzrlib.conflicts import resolve
2135
2008
        if filenames == []:
2136
2009
            filenames = None
2149
2022
            if filenames is None and len(self.get_parent_ids()) > 1:
2150
2023
                parent_trees = []
2151
2024
                last_revision = self.last_revision()
2152
 
                if last_revision != _mod_revision.NULL_REVISION:
 
2025
                if last_revision != NULL_REVISION:
2153
2026
                    if basis_tree is None:
2154
2027
                        basis_tree = self.basis_tree()
2155
2028
                        basis_tree.lock_read()
2193
2066
    def set_inventory(self, new_inventory_list):
2194
2067
        from bzrlib.inventory import (Inventory,
2195
2068
                                      InventoryDirectory,
 
2069
                                      InventoryEntry,
2196
2070
                                      InventoryFile,
2197
2071
                                      InventoryLink)
2198
2072
        inv = Inventory(self.get_root_id())
2200
2074
            name = os.path.basename(path)
2201
2075
            if name == "":
2202
2076
                continue
2203
 
            # fixme, there should be a factory function inv,add_??
 
2077
            # fixme, there should be a factory function inv,add_?? 
2204
2078
            if kind == 'directory':
2205
2079
                inv.add(InventoryDirectory(file_id, name, parent))
2206
2080
            elif kind == 'file':
2214
2088
    @needs_tree_write_lock
2215
2089
    def set_root_id(self, file_id):
2216
2090
        """Set the root id for this tree."""
2217
 
        # for compatability
 
2091
        # for compatability 
2218
2092
        if file_id is None:
2219
 
            raise ValueError(
2220
 
                'WorkingTree.set_root_id with fileid=None')
2221
 
        file_id = osutils.safe_file_id(file_id)
 
2093
            symbol_versioning.warn(symbol_versioning.zero_twelve
 
2094
                % 'WorkingTree.set_root_id with fileid=None',
 
2095
                DeprecationWarning,
 
2096
                stacklevel=3)
 
2097
            file_id = ROOT_ID
 
2098
        else:
 
2099
            file_id = osutils.safe_file_id(file_id)
2222
2100
        self._set_root_id(file_id)
2223
2101
 
2224
2102
    def _set_root_id(self, file_id):
2225
2103
        """Set the root id for this tree, in a format specific manner.
2226
2104
 
2227
 
        :param file_id: The file id to assign to the root. It must not be
 
2105
        :param file_id: The file id to assign to the root. It must not be 
2228
2106
            present in the current inventory or an error will occur. It must
2229
2107
            not be None, but rather a valid file id.
2230
2108
        """
2249
2127
 
2250
2128
    def unlock(self):
2251
2129
        """See Branch.unlock.
2252
 
 
 
2130
        
2253
2131
        WorkingTree locking just uses the Branch locking facilities.
2254
2132
        This is current because all working trees have an embedded branch
2255
2133
        within them. IF in the future, we were to make branch data shareable
2256
 
        between multiple working trees, i.e. via shared storage, then we
 
2134
        between multiple working trees, i.e. via shared storage, then we 
2257
2135
        would probably want to lock both the local tree, and the branch.
2258
2136
        """
2259
2137
        raise NotImplementedError(self.unlock)
2260
2138
 
2261
 
    _marker = object()
2262
 
 
2263
 
    def update(self, change_reporter=None, possible_transports=None,
2264
 
               revision=None, old_tip=_marker):
 
2139
    def update(self, change_reporter=None, possible_transports=None):
2265
2140
        """Update a working tree along its branch.
2266
2141
 
2267
2142
        This will update the branch if its bound too, which means we have
2285
2160
        - Merge current state -> basis tree of the master w.r.t. the old tree
2286
2161
          basis.
2287
2162
        - Do a 'normal' merge of the old branch basis if it is relevant.
2288
 
 
2289
 
        :param revision: The target revision to update to. Must be in the
2290
 
            revision history.
2291
 
        :param old_tip: If branch.update() has already been run, the value it
2292
 
            returned (old tip of the branch or None). _marker is used
2293
 
            otherwise.
2294
2163
        """
2295
 
        if self.branch.get_bound_location() is not None:
 
2164
        if self.branch.get_master_branch(possible_transports) is not None:
2296
2165
            self.lock_write()
2297
 
            update_branch = (old_tip is self._marker)
 
2166
            update_branch = True
2298
2167
        else:
2299
2168
            self.lock_tree_write()
2300
2169
            update_branch = False
2302
2171
            if update_branch:
2303
2172
                old_tip = self.branch.update(possible_transports)
2304
2173
            else:
2305
 
                if old_tip is self._marker:
2306
 
                    old_tip = None
2307
 
            return self._update_tree(old_tip, change_reporter, revision)
 
2174
                old_tip = None
 
2175
            return self._update_tree(old_tip, change_reporter)
2308
2176
        finally:
2309
2177
            self.unlock()
2310
2178
 
2311
2179
    @needs_tree_write_lock
2312
 
    def _update_tree(self, old_tip=None, change_reporter=None, revision=None):
 
2180
    def _update_tree(self, old_tip=None, change_reporter=None):
2313
2181
        """Update a tree to the master branch.
2314
2182
 
2315
2183
        :param old_tip: if supplied, the previous tip revision the branch,
2321
2189
        # cant set that until we update the working trees last revision to be
2322
2190
        # one from the new branch, because it will just get absorbed by the
2323
2191
        # parent de-duplication logic.
2324
 
        #
 
2192
        # 
2325
2193
        # We MUST save it even if an error occurs, because otherwise the users
2326
2194
        # local work is unreferenced and will appear to have been lost.
2327
 
        #
2328
 
        nb_conflicts = 0
 
2195
        # 
 
2196
        result = 0
2329
2197
        try:
2330
2198
            last_rev = self.get_parent_ids()[0]
2331
2199
        except IndexError:
2332
2200
            last_rev = _mod_revision.NULL_REVISION
2333
 
        if revision is None:
2334
 
            revision = self.branch.last_revision()
2335
 
 
2336
 
        old_tip = old_tip or _mod_revision.NULL_REVISION
2337
 
 
2338
 
        if not _mod_revision.is_null(old_tip) and old_tip != last_rev:
2339
 
            # the branch we are bound to was updated
2340
 
            # merge those changes in first
2341
 
            base_tree  = self.basis_tree()
2342
 
            other_tree = self.branch.repository.revision_tree(old_tip)
2343
 
            nb_conflicts = merge.merge_inner(self.branch, other_tree,
2344
 
                                             base_tree, this_tree=self,
2345
 
                                             change_reporter=change_reporter)
2346
 
            if nb_conflicts:
2347
 
                self.add_parent_tree((old_tip, other_tree))
2348
 
                trace.note('Rerun update after fixing the conflicts.')
2349
 
                return nb_conflicts
2350
 
 
2351
 
        if last_rev != _mod_revision.ensure_null(revision):
2352
 
            # the working tree is up to date with the branch
2353
 
            # we can merge the specified revision from master
2354
 
            to_tree = self.branch.repository.revision_tree(revision)
2355
 
            to_root_id = to_tree.get_root_id()
2356
 
 
 
2201
        if last_rev != _mod_revision.ensure_null(self.branch.last_revision()):
 
2202
            # merge tree state up to new branch tip.
2357
2203
            basis = self.basis_tree()
2358
2204
            basis.lock_read()
2359
2205
            try:
2360
 
                if (basis.inventory.root is None
2361
 
                    or basis.inventory.root.file_id != to_root_id):
2362
 
                    self.set_root_id(to_root_id)
 
2206
                to_tree = self.branch.basis_tree()
 
2207
                if basis.inventory.root is None:
 
2208
                    self.set_root_id(to_tree.get_root_id())
2363
2209
                    self.flush()
 
2210
                result += merge.merge_inner(
 
2211
                                      self.branch,
 
2212
                                      to_tree,
 
2213
                                      basis,
 
2214
                                      this_tree=self,
 
2215
                                      change_reporter=change_reporter)
2364
2216
            finally:
2365
2217
                basis.unlock()
2366
 
 
2367
 
            # determine the branch point
2368
 
            graph = self.branch.repository.get_graph()
2369
 
            base_rev_id = graph.find_unique_lca(self.branch.last_revision(),
2370
 
                                                last_rev)
2371
 
            base_tree = self.branch.repository.revision_tree(base_rev_id)
2372
 
 
2373
 
            nb_conflicts = merge.merge_inner(self.branch, to_tree, base_tree,
2374
 
                                             this_tree=self,
2375
 
                                             change_reporter=change_reporter)
2376
 
            self.set_last_revision(revision)
2377
2218
            # TODO - dedup parents list with things merged by pull ?
2378
2219
            # reuse the tree we've updated to to set the basis:
2379
 
            parent_trees = [(revision, to_tree)]
 
2220
            parent_trees = [(self.branch.last_revision(), to_tree)]
2380
2221
            merges = self.get_parent_ids()[1:]
2381
2222
            # Ideally we ask the tree for the trees here, that way the working
2382
 
            # tree can decide whether to give us the entire tree or give us a
 
2223
            # tree can decide whether to give us teh entire tree or give us a
2383
2224
            # lazy initialised tree. dirstate for instance will have the trees
2384
2225
            # in ram already, whereas a last-revision + basis-inventory tree
2385
2226
            # will not, but also does not need them when setting parents.
2386
2227
            for parent in merges:
2387
2228
                parent_trees.append(
2388
2229
                    (parent, self.branch.repository.revision_tree(parent)))
2389
 
            if not _mod_revision.is_null(old_tip):
 
2230
            if (old_tip is not None and not _mod_revision.is_null(old_tip)):
2390
2231
                parent_trees.append(
2391
2232
                    (old_tip, self.branch.repository.revision_tree(old_tip)))
2392
2233
            self.set_parent_trees(parent_trees)
2393
2234
            last_rev = parent_trees[0][0]
2394
 
        return nb_conflicts
 
2235
        else:
 
2236
            # the working tree had the same last-revision as the master
 
2237
            # branch did. We may still have pivot local work from the local
 
2238
            # branch into old_tip:
 
2239
            if (old_tip is not None and not _mod_revision.is_null(old_tip)):
 
2240
                self.add_parent_tree_id(old_tip)
 
2241
        if (old_tip is not None and not _mod_revision.is_null(old_tip)
 
2242
            and old_tip != last_rev):
 
2243
            # our last revision was not the prior branch last revision
 
2244
            # and we have converted that last revision to a pending merge.
 
2245
            # base is somewhere between the branch tip now
 
2246
            # and the now pending merge
 
2247
 
 
2248
            # Since we just modified the working tree and inventory, flush out
 
2249
            # the current state, before we modify it again.
 
2250
            # TODO: jam 20070214 WorkingTree3 doesn't require this, dirstate
 
2251
            #       requires it only because TreeTransform directly munges the
 
2252
            #       inventory and calls tree._write_inventory(). Ultimately we
 
2253
            #       should be able to remove this extra flush.
 
2254
            self.flush()
 
2255
            graph = self.branch.repository.get_graph()
 
2256
            base_rev_id = graph.find_unique_lca(self.branch.last_revision(),
 
2257
                                                old_tip)
 
2258
            base_tree = self.branch.repository.revision_tree(base_rev_id)
 
2259
            other_tree = self.branch.repository.revision_tree(old_tip)
 
2260
            result += merge.merge_inner(
 
2261
                                  self.branch,
 
2262
                                  other_tree,
 
2263
                                  base_tree,
 
2264
                                  this_tree=self,
 
2265
                                  change_reporter=change_reporter)
 
2266
        return result
2395
2267
 
2396
2268
    def _write_hashcache_if_dirty(self):
2397
2269
        """Write out the hashcache if it is dirty."""
2496
2368
                    # value.
2497
2369
                    bzrdir_loc = bisect_left(cur_disk_dir_content,
2498
2370
                        ('.bzr', '.bzr'))
2499
 
                    if (bzrdir_loc < len(cur_disk_dir_content)
2500
 
                        and self.bzrdir.is_control_filename(
2501
 
                            cur_disk_dir_content[bzrdir_loc][0])):
 
2371
                    if cur_disk_dir_content[bzrdir_loc][0] == '.bzr':
2502
2372
                        # we dont yield the contents of, or, .bzr itself.
2503
2373
                        del cur_disk_dir_content[bzrdir_loc]
2504
2374
            if inv_finished:
2594
2464
                relroot = ""
2595
2465
            # FIXME: stash the node in pending
2596
2466
            entry = inv[top_id]
2597
 
            if entry.kind == 'directory':
2598
 
                for name, child in entry.sorted_children():
2599
 
                    dirblock.append((relroot + name, name, child.kind, None,
2600
 
                        child.file_id, child.kind
2601
 
                        ))
 
2467
            for name, child in entry.sorted_children():
 
2468
                dirblock.append((relroot + name, name, child.kind, None,
 
2469
                    child.file_id, child.kind
 
2470
                    ))
2602
2471
            yield (currentdir[0], entry.file_id), dirblock
2603
2472
            # push the user specified dirs from dirblock
2604
2473
            for dir in reversed(dirblock):
2637
2506
        self.set_conflicts(un_resolved)
2638
2507
        return un_resolved, resolved
2639
2508
 
2640
 
    @needs_read_lock
2641
 
    def _check(self, references):
2642
 
        """Check the tree for consistency.
2643
 
 
2644
 
        :param references: A dict with keys matching the items returned by
2645
 
            self._get_check_refs(), and values from looking those keys up in
2646
 
            the repository.
2647
 
        """
2648
 
        tree_basis = self.basis_tree()
2649
 
        tree_basis.lock_read()
2650
 
        try:
2651
 
            repo_basis = references[('trees', self.last_revision())]
2652
 
            if len(list(repo_basis.iter_changes(tree_basis))) > 0:
2653
 
                raise errors.BzrCheckError(
2654
 
                    "Mismatched basis inventory content.")
2655
 
            self._validate()
2656
 
        finally:
2657
 
            tree_basis.unlock()
2658
 
 
2659
2509
    def _validate(self):
2660
2510
        """Validate internal structures.
2661
2511
 
2667
2517
        """
2668
2518
        return
2669
2519
 
2670
 
    def _get_rules_searcher(self, default_searcher):
2671
 
        """See Tree._get_rules_searcher."""
2672
 
        if self._rules_searcher is None:
2673
 
            self._rules_searcher = super(WorkingTree,
2674
 
                self)._get_rules_searcher(default_searcher)
2675
 
        return self._rules_searcher
2676
 
 
2677
 
    def get_shelf_manager(self):
2678
 
        """Return the ShelfManager for this WorkingTree."""
2679
 
        from bzrlib.shelf import ShelfManager
2680
 
        return ShelfManager(self, self._transport)
2681
 
 
2682
2520
 
2683
2521
class WorkingTree2(WorkingTree):
2684
2522
    """This is the Format 2 working tree.
2685
2523
 
2686
 
    This was the first weave based working tree.
 
2524
    This was the first weave based working tree. 
2687
2525
     - uses os locks for locking.
2688
2526
     - uses the branch last-revision.
2689
2527
    """
2699
2537
        if self._inventory is None:
2700
2538
            self.read_working_inventory()
2701
2539
 
2702
 
    def _get_check_refs(self):
2703
 
        """Return the references needed to perform a check of this tree."""
2704
 
        return [('trees', self.last_revision())]
2705
 
 
2706
2540
    def lock_tree_write(self):
2707
2541
        """See WorkingTree.lock_tree_write().
2708
2542
 
2709
2543
        In Format2 WorkingTrees we have a single lock for the branch and tree
2710
2544
        so lock_tree_write() degrades to lock_write().
2711
 
 
2712
 
        :return: An object with an unlock method which will release the lock
2713
 
            obtained.
2714
2545
        """
2715
2546
        self.branch.lock_write()
2716
2547
        try:
2717
 
            self._control_files.lock_write()
2718
 
            return self
 
2548
            return self._control_files.lock_write()
2719
2549
        except:
2720
2550
            self.branch.unlock()
2721
2551
            raise
2730
2560
            if self._inventory_is_modified:
2731
2561
                self.flush()
2732
2562
            self._write_hashcache_if_dirty()
2733
 
 
 
2563
                    
2734
2564
        # reverse order of locking.
2735
2565
        try:
2736
2566
            return self._control_files.unlock()
2752
2582
    def _last_revision(self):
2753
2583
        """See Mutable.last_revision."""
2754
2584
        try:
2755
 
            return self._transport.get_bytes('last-revision')
 
2585
            return self._control_files.get('last-revision').read()
2756
2586
        except errors.NoSuchFile:
2757
2587
            return _mod_revision.NULL_REVISION
2758
2588
 
2759
2589
    def _change_last_revision(self, revision_id):
2760
2590
        """See WorkingTree._change_last_revision."""
2761
 
        if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
 
2591
        if revision_id is None or revision_id == NULL_REVISION:
2762
2592
            try:
2763
 
                self._transport.delete('last-revision')
 
2593
                self._control_files._transport.delete('last-revision')
2764
2594
            except errors.NoSuchFile:
2765
2595
                pass
2766
2596
            return False
2767
2597
        else:
2768
 
            self._transport.put_bytes('last-revision', revision_id,
2769
 
                mode=self.bzrdir._get_file_mode())
 
2598
            self._control_files.put_bytes('last-revision', revision_id)
2770
2599
            return True
2771
2600
 
2772
 
    def _get_check_refs(self):
2773
 
        """Return the references needed to perform a check of this tree."""
2774
 
        return [('trees', self.last_revision())]
2775
 
 
2776
2601
    @needs_tree_write_lock
2777
2602
    def set_conflicts(self, conflicts):
2778
 
        self._put_rio('conflicts', conflicts.to_stanzas(),
 
2603
        self._put_rio('conflicts', conflicts.to_stanzas(), 
2779
2604
                      CONFLICT_HEADER_1)
2780
2605
 
2781
2606
    @needs_tree_write_lock
2788
2613
    @needs_read_lock
2789
2614
    def conflicts(self):
2790
2615
        try:
2791
 
            confile = self._transport.get('conflicts')
 
2616
            confile = self._control_files.get('conflicts')
2792
2617
        except errors.NoSuchFile:
2793
2618
            return _mod_conflicts.ConflictList()
2794
2619
        try:
2795
 
            try:
2796
 
                if confile.next() != CONFLICT_HEADER_1 + '\n':
2797
 
                    raise errors.ConflictFormatError()
2798
 
            except StopIteration:
 
2620
            if confile.next() != CONFLICT_HEADER_1 + '\n':
2799
2621
                raise errors.ConflictFormatError()
2800
 
            return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
2801
 
        finally:
2802
 
            confile.close()
 
2622
        except StopIteration:
 
2623
            raise errors.ConflictFormatError()
 
2624
        return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
2803
2625
 
2804
2626
    def unlock(self):
2805
2627
        # do non-implementation specific cleanup
2822
2644
            return path[:-len(suffix)]
2823
2645
 
2824
2646
 
 
2647
@deprecated_function(zero_eight)
 
2648
def is_control_file(filename):
 
2649
    """See WorkingTree.is_control_filename(filename)."""
 
2650
    ## FIXME: better check
 
2651
    filename = normpath(filename)
 
2652
    while filename != '':
 
2653
        head, tail = os.path.split(filename)
 
2654
        ## mutter('check %r for control file' % ((head, tail),))
 
2655
        if tail == '.bzr':
 
2656
            return True
 
2657
        if filename == head:
 
2658
            break
 
2659
        filename = head
 
2660
    return False
 
2661
 
 
2662
 
2825
2663
class WorkingTreeFormat(object):
2826
2664
    """An encapsulation of the initialization and open routines for a format.
2827
2665
 
2830
2668
     * a format string,
2831
2669
     * an open routine.
2832
2670
 
2833
 
    Formats are placed in an dict by their format string for reference
 
2671
    Formats are placed in an dict by their format string for reference 
2834
2672
    during workingtree opening. Its not required that these be instances, they
2835
 
    can be classes themselves with class methods - it simply depends on
 
2673
    can be classes themselves with class methods - it simply depends on 
2836
2674
    whether state is needed for a given format or not.
2837
2675
 
2838
2676
    Once a format is deprecated, just deprecate the initialize and open
2839
 
    methods on the format class. Do not deprecate the object, as the
 
2677
    methods on the format class. Do not deprecate the object, as the 
2840
2678
    object will be created every time regardless.
2841
2679
    """
2842
2680
 
2855
2693
        """Return the format for the working tree object in a_bzrdir."""
2856
2694
        try:
2857
2695
            transport = a_bzrdir.get_workingtree_transport(None)
2858
 
            format_string = transport.get_bytes("format")
 
2696
            format_string = transport.get("format").read()
2859
2697
            return klass._formats[format_string]
2860
2698
        except errors.NoSuchFile:
2861
2699
            raise errors.NoWorkingTree(base=transport.base)
2886
2724
        """Is this format supported?
2887
2725
 
2888
2726
        Supported formats can be initialized and opened.
2889
 
        Unsupported formats may not support initialization or committing or
 
2727
        Unsupported formats may not support initialization or committing or 
2890
2728
        some other features depending on the reason for not being supported.
2891
2729
        """
2892
2730
        return True
2893
2731
 
2894
 
    def supports_content_filtering(self):
2895
 
        """True if this format supports content filtering."""
2896
 
        return False
2897
 
 
2898
 
    def supports_views(self):
2899
 
        """True if this format supports stored views."""
2900
 
        return False
2901
 
 
2902
2732
    @classmethod
2903
2733
    def register_format(klass, format):
2904
2734
        klass._formats[format.get_format_string()] = format
2909
2739
 
2910
2740
    @classmethod
2911
2741
    def unregister_format(klass, format):
 
2742
        assert klass._formats[format.get_format_string()] is format
2912
2743
        del klass._formats[format.get_format_string()]
2913
2744
 
2914
2745
 
2915
2746
class WorkingTreeFormat2(WorkingTreeFormat):
2916
 
    """The second working tree format.
 
2747
    """The second working tree format. 
2917
2748
 
2918
2749
    This format modified the hash cache from the format 1 hash cache.
2919
2750
    """
2924
2755
        """See WorkingTreeFormat.get_format_description()."""
2925
2756
        return "Working tree format 2"
2926
2757
 
2927
 
    def _stub_initialize_on_transport(self, transport, file_mode):
2928
 
        """Workaround: create control files for a remote working tree.
2929
 
 
 
2758
    def stub_initialize_remote(self, control_files):
 
2759
        """As a special workaround create critical control files for a remote working tree
 
2760
        
2930
2761
        This ensures that it can later be updated and dealt with locally,
2931
 
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with
 
2762
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with 
2932
2763
        no working tree.  (See bug #43064).
2933
2764
        """
2934
2765
        sio = StringIO()
2935
 
        inv = inventory.Inventory()
 
2766
        inv = Inventory()
2936
2767
        xml5.serializer_v5.write_inventory(inv, sio, working=True)
2937
2768
        sio.seek(0)
2938
 
        transport.put_file('inventory', sio, file_mode)
2939
 
        transport.put_bytes('pending-merges', '', file_mode)
 
2769
        control_files.put('inventory', sio)
 
2770
 
 
2771
        control_files.put_bytes('pending-merges', '')
 
2772
        
2940
2773
 
2941
2774
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
2942
2775
                   accelerator_tree=None, hardlink=False):
2954
2787
            branch.generate_revision_history(revision_id)
2955
2788
        finally:
2956
2789
            branch.unlock()
2957
 
        inv = inventory.Inventory()
 
2790
        inv = Inventory()
2958
2791
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
2959
2792
                         branch,
2960
2793
                         inv,
3005
2838
        - is new in bzr 0.8
3006
2839
        - uses a LockDir to guard access for writes.
3007
2840
    """
3008
 
 
 
2841
    
3009
2842
    upgrade_recommended = True
3010
2843
 
3011
2844
    def get_format_string(self):
3028
2861
 
3029
2862
    def _open_control_files(self, a_bzrdir):
3030
2863
        transport = a_bzrdir.get_workingtree_transport(None)
3031
 
        return LockableFiles(transport, self._lock_file_name,
 
2864
        return LockableFiles(transport, self._lock_file_name, 
3032
2865
                             self._lock_class)
3033
2866
 
3034
2867
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
3035
2868
                   accelerator_tree=None, hardlink=False):
3036
2869
        """See WorkingTreeFormat.initialize().
3037
 
 
 
2870
        
3038
2871
        :param revision_id: if supplied, create a working tree at a different
3039
2872
            revision than the branch is at.
3040
2873
        :param accelerator_tree: A tree which can be used for retrieving file
3050
2883
        control_files = self._open_control_files(a_bzrdir)
3051
2884
        control_files.create_lock()
3052
2885
        control_files.lock_write()
3053
 
        transport.put_bytes('format', self.get_format_string(),
3054
 
            mode=a_bzrdir._get_file_mode())
 
2886
        control_files.put_utf8('format', self.get_format_string())
3055
2887
        if from_branch is not None:
3056
2888
            branch = from_branch
3057
2889
        else:
3077
2909
            # only set an explicit root id if there is one to set.
3078
2910
            if basis_tree.inventory.root is not None:
3079
2911
                wt.set_root_id(basis_tree.get_root_id())
3080
 
            if revision_id == _mod_revision.NULL_REVISION:
 
2912
            if revision_id == NULL_REVISION:
3081
2913
                wt.set_parent_trees([])
3082
2914
            else:
3083
2915
                wt.set_parent_trees([(revision_id, basis_tree)])
3090
2922
        return wt
3091
2923
 
3092
2924
    def _initial_inventory(self):
3093
 
        return inventory.Inventory()
 
2925
        return Inventory()
3094
2926
 
3095
2927
    def __init__(self):
3096
2928
        super(WorkingTreeFormat3, self).__init__()
3111
2943
 
3112
2944
    def _open(self, a_bzrdir, control_files):
3113
2945
        """Open the tree itself.
3114
 
 
 
2946
        
3115
2947
        :param a_bzrdir: the dir for the tree.
3116
2948
        :param control_files: the control files for the tree.
3117
2949
        """
3125
2957
        return self.get_format_string()
3126
2958
 
3127
2959
 
3128
 
__default_format = WorkingTreeFormat6()
 
2960
__default_format = WorkingTreeFormat4()
3129
2961
WorkingTreeFormat.register_format(__default_format)
3130
 
WorkingTreeFormat.register_format(WorkingTreeFormat5())
3131
 
WorkingTreeFormat.register_format(WorkingTreeFormat4())
3132
2962
WorkingTreeFormat.register_format(WorkingTreeFormat3())
3133
2963
WorkingTreeFormat.set_default_format(__default_format)
3134
2964
# formats which have no format string are not discoverable