/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/workingtree.py

  • Committer: Robey Pointer
  • Date: 2006-09-08 18:46:29 UTC
  • mto: This revision was merged to the branch mainline in revision 1996.
  • Revision ID: robey@lag.net-20060908184629-e3fc4c61ca21508c
pychecker is on crack; go back to using 'is None'.

Show diffs side-by-side

added added

removed removed

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