/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

Review comments for gen_file_id changes.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
 
2
 
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
 
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
 
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""WorkingTree object and friends.
 
18
 
 
19
A WorkingTree represents the editable working copy of a branch.
 
20
Operations which represent the WorkingTree are also done here, 
 
21
such as renaming or adding files.  The WorkingTree has an inventory 
 
22
which is updated by these operations.  A commit produces a 
 
23
new revision based on the workingtree and its inventory.
 
24
 
 
25
At the moment every WorkingTree has its own branch.  Remote
 
26
WorkingTrees aren't supported.
 
27
 
 
28
To get a WorkingTree, call bzrdir.open_workingtree() or
 
29
WorkingTree.open(dir).
 
30
"""
 
31
 
 
32
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
from copy import deepcopy
 
44
from cStringIO import StringIO
 
45
import errno
 
46
import fnmatch
 
47
import os
 
48
import re
 
49
import stat
 
50
from time import time
 
51
 
 
52
from bzrlib.atomicfile import AtomicFile
 
53
from bzrlib.branch import (Branch,
 
54
                           quotefn)
 
55
from bzrlib.conflicts import Conflict, ConflictList, CONFLICT_SUFFIXES
 
56
import bzrlib.bzrdir as bzrdir
 
57
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
58
import bzrlib.errors as errors
 
59
from bzrlib.errors import (BzrCheckError,
 
60
                           BzrError,
 
61
                           ConflictFormatError,
 
62
                           DivergedBranches,
 
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
 
72
from bzrlib.lockdir import LockDir
 
73
from bzrlib.merge import merge_inner, transform_tree
 
74
from bzrlib.osutils import (
 
75
                            abspath,
 
76
                            appendpath,
 
77
                            compact_date,
 
78
                            file_kind,
 
79
                            isdir,
 
80
                            getcwd,
 
81
                            pathjoin,
 
82
                            pumpfile,
 
83
                            safe_unicode,
 
84
                            splitpath,
 
85
                            rand_chars,
 
86
                            normpath,
 
87
                            realpath,
 
88
                            relpath,
 
89
                            rename,
 
90
                            supports_executable,
 
91
                            )
 
92
from bzrlib.progress import DummyProgress, ProgressPhase
 
93
from bzrlib.revision import NULL_REVISION
 
94
from bzrlib.rio import RioReader, rio_file, Stanza
 
95
from bzrlib.symbol_versioning import *
 
96
from bzrlib.textui import show_status
 
97
import bzrlib.tree
 
98
from bzrlib.transform import build_tree
 
99
from bzrlib.trace import mutter, note
 
100
from bzrlib.transport import get_transport
 
101
from bzrlib.transport.local import LocalTransport
 
102
import bzrlib.ui
 
103
import bzrlib.xml5
 
104
 
 
105
 
 
106
# the regex here does the following:
 
107
# 1) remove any weird characters; we don't escape them but rather
 
108
# just pull them out
 
109
 # 2) match leading '.'s to make it not hidden
 
110
_gen_file_id_re = re.compile(r'[^\w.]|(^\.*)')
 
111
_gen_id_suffix = None
 
112
_gen_id_serial = 0
 
113
 
 
114
 
 
115
def _next_id_suffix():
 
116
    """Create a new file id suffix that is reasonably unique.
 
117
    
 
118
    On the first call we combine the current time with 64 bits of randomness
 
119
    to give a highly probably globally unique number. Then each call in the same
 
120
    process adds 1 to a serial number we append to that unique value.
 
121
    """
 
122
    # XXX TODO: change bzrlib.add.smart_add to call workingtree.add() rather 
 
123
    # than having to move the id randomness out of the inner loop like this.
 
124
    # XXX TODO: for the global randomness this uses we should add the thread-id
 
125
    # before the serial #.
 
126
    global _gen_id_suffix, _gen_id_serial
 
127
    if _gen_id_suffix is None:
 
128
        _gen_id_suffix = "-%s-%s-" % (compact_date(time()), rand_chars(16))
 
129
    _gen_id_serial += 1
 
130
    return _gen_id_suffix + str(_gen_id_serial)
 
131
 
 
132
 
 
133
def gen_file_id(name):
 
134
    """Return new file id for the basename 'name'.
 
135
 
 
136
    The uniqueness is supplied from _next_id_suffix.
 
137
    """
 
138
    # XXX TODO: squash the filename to lowercase.
 
139
    # XXX TODO: truncate the filename to something like 20 or 30 chars.
 
140
    # XXX TODO: consider what to do with ids that look like illegal filepaths
 
141
    # on platforms we support.
 
142
    return _gen_file_id_re.sub('', name) + _next_id_suffix()
 
143
 
 
144
 
 
145
def gen_root_id():
 
146
    """Return a new tree-root file id."""
 
147
    return gen_file_id('TREE_ROOT')
 
148
 
 
149
 
 
150
class TreeEntry(object):
 
151
    """An entry that implements the minium interface used by commands.
 
152
 
 
153
    This needs further inspection, it may be better to have 
 
154
    InventoryEntries without ids - though that seems wrong. For now,
 
155
    this is a parallel hierarchy to InventoryEntry, and needs to become
 
156
    one of several things: decorates to that hierarchy, children of, or
 
157
    parents of it.
 
158
    Another note is that these objects are currently only used when there is
 
159
    no InventoryEntry available - i.e. for unversioned objects.
 
160
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
 
161
    """
 
162
 
 
163
    def __eq__(self, other):
 
164
        # yes, this us ugly, TODO: best practice __eq__ style.
 
165
        return (isinstance(other, TreeEntry)
 
166
                and other.__class__ == self.__class__)
 
167
 
 
168
    def kind_character(self):
 
169
        return "???"
 
170
 
 
171
 
 
172
class TreeDirectory(TreeEntry):
 
173
    """See TreeEntry. This is a directory in a working tree."""
 
174
 
 
175
    def __eq__(self, other):
 
176
        return (isinstance(other, TreeDirectory)
 
177
                and other.__class__ == self.__class__)
 
178
 
 
179
    def kind_character(self):
 
180
        return "/"
 
181
 
 
182
 
 
183
class TreeFile(TreeEntry):
 
184
    """See TreeEntry. This is a regular file in a working tree."""
 
185
 
 
186
    def __eq__(self, other):
 
187
        return (isinstance(other, TreeFile)
 
188
                and other.__class__ == self.__class__)
 
189
 
 
190
    def kind_character(self):
 
191
        return ''
 
192
 
 
193
 
 
194
class TreeLink(TreeEntry):
 
195
    """See TreeEntry. This is a symlink in a working tree."""
 
196
 
 
197
    def __eq__(self, other):
 
198
        return (isinstance(other, TreeLink)
 
199
                and other.__class__ == self.__class__)
 
200
 
 
201
    def kind_character(self):
 
202
        return ''
 
203
 
 
204
 
 
205
class WorkingTree(bzrlib.tree.Tree):
 
206
    """Working copy tree.
 
207
 
 
208
    The inventory is held in the `Branch` working-inventory, and the
 
209
    files are in a directory on disk.
 
210
 
 
211
    It is possible for a `WorkingTree` to have a filename which is
 
212
    not listed in the Inventory and vice versa.
 
213
    """
 
214
 
 
215
    def __init__(self, basedir='.',
 
216
                 branch=DEPRECATED_PARAMETER,
 
217
                 _inventory=None,
 
218
                 _control_files=None,
 
219
                 _internal=False,
 
220
                 _format=None,
 
221
                 _bzrdir=None):
 
222
        """Construct a WorkingTree for basedir.
 
223
 
 
224
        If the branch is not supplied, it is opened automatically.
 
225
        If the branch is supplied, it must be the branch for this basedir.
 
226
        (branch.base is not cross checked, because for remote branches that
 
227
        would be meaningless).
 
228
        """
 
229
        self._format = _format
 
230
        self.bzrdir = _bzrdir
 
231
        if not _internal:
 
232
            # not created via open etc.
 
233
            warn("WorkingTree() is deprecated as of bzr version 0.8. "
 
234
                 "Please use bzrdir.open_workingtree or WorkingTree.open().",
 
235
                 DeprecationWarning,
 
236
                 stacklevel=2)
 
237
            wt = WorkingTree.open(basedir)
 
238
            self._branch = wt.branch
 
239
            self.basedir = wt.basedir
 
240
            self._control_files = wt._control_files
 
241
            self._hashcache = wt._hashcache
 
242
            self._set_inventory(wt._inventory)
 
243
            self._format = wt._format
 
244
            self.bzrdir = wt.bzrdir
 
245
        from bzrlib.hashcache import HashCache
 
246
        from bzrlib.trace import note, mutter
 
247
        assert isinstance(basedir, basestring), \
 
248
            "base directory %r is not a string" % basedir
 
249
        basedir = safe_unicode(basedir)
 
250
        mutter("opening working tree %r", basedir)
 
251
        if deprecated_passed(branch):
 
252
            if not _internal:
 
253
                warn("WorkingTree(..., branch=XXX) is deprecated as of bzr 0.8."
 
254
                     " Please use bzrdir.open_workingtree() or"
 
255
                     " WorkingTree.open().",
 
256
                     DeprecationWarning,
 
257
                     stacklevel=2
 
258
                     )
 
259
            self._branch = branch
 
260
        else:
 
261
            self._branch = self.bzrdir.open_branch()
 
262
        assert isinstance(self.branch, Branch), \
 
263
            "branch %r is not a Branch" % self.branch
 
264
        self.basedir = realpath(basedir)
 
265
        # if branch is at our basedir and is a format 6 or less
 
266
        if isinstance(self._format, WorkingTreeFormat2):
 
267
            # share control object
 
268
            self._control_files = self.branch.control_files
 
269
        else:
 
270
            # only ready for format 3
 
271
            assert isinstance(self._format, WorkingTreeFormat3)
 
272
            assert isinstance(_control_files, LockableFiles), \
 
273
                    "_control_files must be a LockableFiles, not %r" \
 
274
                    % _control_files
 
275
            self._control_files = _control_files
 
276
        # update the whole cache up front and write to disk if anything changed;
 
277
        # in the future we might want to do this more selectively
 
278
        # two possible ways offer themselves : in self._unlock, write the cache
 
279
        # if needed, or, when the cache sees a change, append it to the hash
 
280
        # cache file, and have the parser take the most recent entry for a
 
281
        # given path only.
 
282
        cache_filename = self.bzrdir.get_workingtree_transport(None).abspath('stat-cache')
 
283
        hc = self._hashcache = HashCache(basedir, cache_filename, self._control_files._file_mode)
 
284
        hc.read()
 
285
        # is this scan needed ? it makes things kinda slow.
 
286
        hc.scan()
 
287
 
 
288
        if hc.needs_write:
 
289
            mutter("write hc")
 
290
            hc.write()
 
291
 
 
292
        if _inventory is None:
 
293
            self._set_inventory(self.read_working_inventory())
 
294
        else:
 
295
            self._set_inventory(_inventory)
 
296
 
 
297
    branch = property(
 
298
        fget=lambda self: self._branch,
 
299
        doc="""The branch this WorkingTree is connected to.
 
300
 
 
301
            This cannot be set - it is reflective of the actual disk structure
 
302
            the working tree has been constructed from.
 
303
            """)
 
304
 
 
305
    def break_lock(self):
 
306
        """Break a lock if one is present from another instance.
 
307
 
 
308
        Uses the ui factory to ask for confirmation if the lock may be from
 
309
        an active process.
 
310
 
 
311
        This will probe the repository for its lock as well.
 
312
        """
 
313
        self._control_files.break_lock()
 
314
        self.branch.break_lock()
 
315
 
 
316
    def _set_inventory(self, inv):
 
317
        self._inventory = inv
 
318
        self.path2id = self._inventory.path2id
 
319
 
 
320
    def is_control_filename(self, filename):
 
321
        """True if filename is the name of a control file in this tree.
 
322
        
 
323
        This is true IF and ONLY IF the filename is part of the meta data
 
324
        that bzr controls in this tree. I.E. a random .bzr directory placed
 
325
        on disk will not be a control file for this tree.
 
326
        """
 
327
        try:
 
328
            self.bzrdir.transport.relpath(self.abspath(filename))
 
329
            return True
 
330
        except errors.PathNotChild:
 
331
            return False
 
332
 
 
333
    @staticmethod
 
334
    def open(path=None, _unsupported=False):
 
335
        """Open an existing working tree at path.
 
336
 
 
337
        """
 
338
        if path is None:
 
339
            path = os.path.getcwdu()
 
340
        control = bzrdir.BzrDir.open(path, _unsupported)
 
341
        return control.open_workingtree(_unsupported)
 
342
        
 
343
    @staticmethod
 
344
    def open_containing(path=None):
 
345
        """Open an existing working tree which has its root about path.
 
346
        
 
347
        This probes for a working tree at path and searches upwards from there.
 
348
 
 
349
        Basically we keep looking up until we find the control directory or
 
350
        run into /.  If there isn't one, raises NotBranchError.
 
351
        TODO: give this a new exception.
 
352
        If there is one, it is returned, along with the unused portion of path.
 
353
        """
 
354
        if path is None:
 
355
            path = os.getcwdu()
 
356
        control, relpath = bzrdir.BzrDir.open_containing(path)
 
357
        return control.open_workingtree(), relpath
 
358
 
 
359
    @staticmethod
 
360
    def open_downlevel(path=None):
 
361
        """Open an unsupported working tree.
 
362
 
 
363
        Only intended for advanced situations like upgrading part of a bzrdir.
 
364
        """
 
365
        return WorkingTree.open(path, _unsupported=True)
 
366
 
 
367
    def __iter__(self):
 
368
        """Iterate through file_ids for this tree.
 
369
 
 
370
        file_ids are in a WorkingTree if they are in the working inventory
 
371
        and the working file exists.
 
372
        """
 
373
        inv = self._inventory
 
374
        for path, ie in inv.iter_entries():
 
375
            if bzrlib.osutils.lexists(self.abspath(path)):
 
376
                yield ie.file_id
 
377
 
 
378
    def __repr__(self):
 
379
        return "<%s of %s>" % (self.__class__.__name__,
 
380
                               getattr(self, 'basedir', None))
 
381
 
 
382
    def abspath(self, filename):
 
383
        return pathjoin(self.basedir, filename)
 
384
    
 
385
    def basis_tree(self):
 
386
        """Return RevisionTree for the current last revision."""
 
387
        revision_id = self.last_revision()
 
388
        if revision_id is not None:
 
389
            try:
 
390
                xml = self.read_basis_inventory()
 
391
                inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
 
392
            except NoSuchFile:
 
393
                inv = None
 
394
            if inv is not None and inv.revision_id == revision_id:
 
395
                return bzrlib.tree.RevisionTree(self.branch.repository, inv,
 
396
                                                revision_id)
 
397
        # FIXME? RBC 20060403 should we cache the inventory here ?
 
398
        return self.branch.repository.revision_tree(revision_id)
 
399
 
 
400
    @staticmethod
 
401
    @deprecated_method(zero_eight)
 
402
    def create(branch, directory):
 
403
        """Create a workingtree for branch at directory.
 
404
 
 
405
        If existing_directory already exists it must have a .bzr directory.
 
406
        If it does not exist, it will be created.
 
407
 
 
408
        This returns a new WorkingTree object for the new checkout.
 
409
 
 
410
        TODO FIXME RBC 20060124 when we have checkout formats in place this
 
411
        should accept an optional revisionid to checkout [and reject this if
 
412
        checking out into the same dir as a pre-checkout-aware branch format.]
 
413
 
 
414
        XXX: When BzrDir is present, these should be created through that 
 
415
        interface instead.
 
416
        """
 
417
        warn('delete WorkingTree.create', stacklevel=3)
 
418
        transport = get_transport(directory)
 
419
        if branch.bzrdir.root_transport.base == transport.base:
 
420
            # same dir 
 
421
            return branch.bzrdir.create_workingtree()
 
422
        # different directory, 
 
423
        # create a branch reference
 
424
        # and now a working tree.
 
425
        raise NotImplementedError
 
426
 
 
427
    @staticmethod
 
428
    @deprecated_method(zero_eight)
 
429
    def create_standalone(directory):
 
430
        """Create a checkout and a branch and a repo at directory.
 
431
 
 
432
        Directory must exist and be empty.
 
433
 
 
434
        please use BzrDir.create_standalone_workingtree
 
435
        """
 
436
        return bzrdir.BzrDir.create_standalone_workingtree(directory)
 
437
 
 
438
    def relpath(self, abs):
 
439
        """Return the local path portion from a given absolute path."""
 
440
        return relpath(self.basedir, abs)
 
441
 
 
442
    def has_filename(self, filename):
 
443
        return bzrlib.osutils.lexists(self.abspath(filename))
 
444
 
 
445
    def get_file(self, file_id):
 
446
        return self.get_file_byname(self.id2path(file_id))
 
447
 
 
448
    def get_file_byname(self, filename):
 
449
        return file(self.abspath(filename), 'rb')
 
450
 
 
451
    def get_root_id(self):
 
452
        """Return the id of this trees root"""
 
453
        inv = self.read_working_inventory()
 
454
        return inv.root.file_id
 
455
        
 
456
    def _get_store_filename(self, file_id):
 
457
        ## XXX: badly named; this is not in the store at all
 
458
        return self.abspath(self.id2path(file_id))
 
459
 
 
460
    @needs_read_lock
 
461
    def clone(self, to_bzrdir, revision_id=None, basis=None):
 
462
        """Duplicate this working tree into to_bzr, including all state.
 
463
        
 
464
        Specifically modified files are kept as modified, but
 
465
        ignored and unknown files are discarded.
 
466
 
 
467
        If you want to make a new line of development, see bzrdir.sprout()
 
468
 
 
469
        revision
 
470
            If not None, the cloned tree will have its last revision set to 
 
471
            revision, and and difference between the source trees last revision
 
472
            and this one merged in.
 
473
 
 
474
        basis
 
475
            If not None, a closer copy of a tree which may have some files in
 
476
            common, and which file content should be preferentially copied from.
 
477
        """
 
478
        # assumes the target bzr dir format is compatible.
 
479
        result = self._format.initialize(to_bzrdir)
 
480
        self.copy_content_into(result, revision_id)
 
481
        return result
 
482
 
 
483
    @needs_read_lock
 
484
    def copy_content_into(self, tree, revision_id=None):
 
485
        """Copy the current content and user files of this tree into tree."""
 
486
        if revision_id is None:
 
487
            transform_tree(tree, self)
 
488
        else:
 
489
            # TODO now merge from tree.last_revision to revision
 
490
            transform_tree(tree, self)
 
491
            tree.set_last_revision(revision_id)
 
492
 
 
493
    @needs_write_lock
 
494
    def commit(self, message=None, revprops=None, *args, **kwargs):
 
495
        # avoid circular imports
 
496
        from bzrlib.commit import Commit
 
497
        if revprops is None:
 
498
            revprops = {}
 
499
        if not 'branch-nick' in revprops:
 
500
            revprops['branch-nick'] = self.branch.nick
 
501
        # args for wt.commit start at message from the Commit.commit method,
 
502
        # but with branch a kwarg now, passing in args as is results in the
 
503
        #message being used for the branch
 
504
        args = (DEPRECATED_PARAMETER, message, ) + args
 
505
        Commit().commit(working_tree=self, revprops=revprops, *args, **kwargs)
 
506
        self._set_inventory(self.read_working_inventory())
 
507
 
 
508
    def id2abspath(self, file_id):
 
509
        return self.abspath(self.id2path(file_id))
 
510
 
 
511
    def has_id(self, file_id):
 
512
        # files that have been deleted are excluded
 
513
        inv = self._inventory
 
514
        if not inv.has_id(file_id):
 
515
            return False
 
516
        path = inv.id2path(file_id)
 
517
        return bzrlib.osutils.lexists(self.abspath(path))
 
518
 
 
519
    def has_or_had_id(self, file_id):
 
520
        if file_id == self.inventory.root.file_id:
 
521
            return True
 
522
        return self.inventory.has_id(file_id)
 
523
 
 
524
    __contains__ = has_id
 
525
 
 
526
    def get_file_size(self, file_id):
 
527
        return os.path.getsize(self.id2abspath(file_id))
 
528
 
 
529
    @needs_read_lock
 
530
    def get_file_sha1(self, file_id):
 
531
        path = self._inventory.id2path(file_id)
 
532
        return self._hashcache.get_sha1(path)
 
533
 
 
534
    def is_executable(self, file_id):
 
535
        if not supports_executable():
 
536
            return self._inventory[file_id].executable
 
537
        else:
 
538
            path = self._inventory.id2path(file_id)
 
539
            mode = os.lstat(self.abspath(path)).st_mode
 
540
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
 
541
 
 
542
    @needs_write_lock
 
543
    def add(self, files, ids=None):
 
544
        """Make files versioned.
 
545
 
 
546
        Note that the command line normally calls smart_add instead,
 
547
        which can automatically recurse.
 
548
 
 
549
        This adds the files to the inventory, so that they will be
 
550
        recorded by the next commit.
 
551
 
 
552
        files
 
553
            List of paths to add, relative to the base of the tree.
 
554
 
 
555
        ids
 
556
            If set, use these instead of automatically generated ids.
 
557
            Must be the same length as the list of files, but may
 
558
            contain None for ids that are to be autogenerated.
 
559
 
 
560
        TODO: Perhaps have an option to add the ids even if the files do
 
561
              not (yet) exist.
 
562
 
 
563
        TODO: Perhaps callback with the ids and paths as they're added.
 
564
        """
 
565
        # TODO: Re-adding a file that is removed in the working copy
 
566
        # should probably put it back with the previous ID.
 
567
        if isinstance(files, basestring):
 
568
            assert(ids is None or isinstance(ids, basestring))
 
569
            files = [files]
 
570
            if ids is not None:
 
571
                ids = [ids]
 
572
 
 
573
        if ids is None:
 
574
            ids = [None] * len(files)
 
575
        else:
 
576
            assert(len(ids) == len(files))
 
577
 
 
578
        inv = self.read_working_inventory()
 
579
        for f,file_id in zip(files, ids):
 
580
            if self.is_control_filename(f):
 
581
                raise BzrError("cannot add control file %s" % quotefn(f))
 
582
 
 
583
            fp = splitpath(f)
 
584
 
 
585
            if len(fp) == 0:
 
586
                raise BzrError("cannot add top-level %r" % f)
 
587
 
 
588
            fullpath = normpath(self.abspath(f))
 
589
 
 
590
            try:
 
591
                kind = file_kind(fullpath)
 
592
            except OSError, e:
 
593
                if e.errno == errno.ENOENT:
 
594
                    raise NoSuchFile(fullpath)
 
595
                # maybe something better?
 
596
                raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
 
597
 
 
598
            if not InventoryEntry.versionable_kind(kind):
 
599
                raise BzrError('cannot add: not a versionable file ('
 
600
                               'i.e. regular file, symlink or directory): %s' % quotefn(f))
 
601
 
 
602
            if file_id is None:
 
603
                inv.add_path(f, kind=kind)
 
604
            else:
 
605
                inv.add_path(f, kind=kind, file_id=file_id)
 
606
 
 
607
        self._write_inventory(inv)
 
608
 
 
609
    @needs_write_lock
 
610
    def add_pending_merge(self, *revision_ids):
 
611
        # TODO: Perhaps should check at this point that the
 
612
        # history of the revision is actually present?
 
613
        p = self.pending_merges()
 
614
        updated = False
 
615
        for rev_id in revision_ids:
 
616
            if rev_id in p:
 
617
                continue
 
618
            p.append(rev_id)
 
619
            updated = True
 
620
        if updated:
 
621
            self.set_pending_merges(p)
 
622
 
 
623
    @needs_read_lock
 
624
    def pending_merges(self):
 
625
        """Return a list of pending merges.
 
626
 
 
627
        These are revisions that have been merged into the working
 
628
        directory but not yet committed.
 
629
        """
 
630
        try:
 
631
            merges_file = self._control_files.get_utf8('pending-merges')
 
632
        except OSError, e:
 
633
            if e.errno != errno.ENOENT:
 
634
                raise
 
635
            return []
 
636
        p = []
 
637
        for l in merges_file.readlines():
 
638
            p.append(l.rstrip('\n'))
 
639
        return p
 
640
 
 
641
    @needs_write_lock
 
642
    def set_pending_merges(self, rev_list):
 
643
        self._control_files.put_utf8('pending-merges', '\n'.join(rev_list))
 
644
 
 
645
    @needs_write_lock
 
646
    def set_merge_modified(self, modified_hashes):
 
647
        def iter_stanzas():
 
648
            for file_id, hash in modified_hashes.iteritems():
 
649
                yield Stanza(file_id=file_id, hash=hash)
 
650
        self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
 
651
 
 
652
    @needs_write_lock
 
653
    def _put_rio(self, filename, stanzas, header):
 
654
        my_file = rio_file(stanzas, header)
 
655
        self._control_files.put(filename, my_file)
 
656
 
 
657
    @needs_read_lock
 
658
    def merge_modified(self):
 
659
        try:
 
660
            hashfile = self._control_files.get('merge-hashes')
 
661
        except NoSuchFile:
 
662
            return {}
 
663
        merge_hashes = {}
 
664
        try:
 
665
            if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
 
666
                raise MergeModifiedFormatError()
 
667
        except StopIteration:
 
668
            raise MergeModifiedFormatError()
 
669
        for s in RioReader(hashfile):
 
670
            file_id = s.get("file_id")
 
671
            if file_id not in self.inventory:
 
672
                continue
 
673
            hash = s.get("hash")
 
674
            if hash == self.get_file_sha1(file_id):
 
675
                merge_hashes[file_id] = hash
 
676
        return merge_hashes
 
677
 
 
678
    def get_symlink_target(self, file_id):
 
679
        return os.readlink(self.id2abspath(file_id))
 
680
 
 
681
    def file_class(self, filename):
 
682
        if self.path2id(filename):
 
683
            return 'V'
 
684
        elif self.is_ignored(filename):
 
685
            return 'I'
 
686
        else:
 
687
            return '?'
 
688
 
 
689
    def list_files(self):
 
690
        """Recursively list all files as (path, class, kind, id).
 
691
 
 
692
        Lists, but does not descend into unversioned directories.
 
693
 
 
694
        This does not include files that have been deleted in this
 
695
        tree.
 
696
 
 
697
        Skips the control directory.
 
698
        """
 
699
        inv = self._inventory
 
700
 
 
701
        def descend(from_dir_relpath, from_dir_id, dp):
 
702
            ls = os.listdir(dp)
 
703
            ls.sort()
 
704
            for f in ls:
 
705
                ## TODO: If we find a subdirectory with its own .bzr
 
706
                ## directory, then that is a separate tree and we
 
707
                ## should exclude it.
 
708
 
 
709
                # the bzrdir for this tree
 
710
                if self.bzrdir.transport.base.endswith(f + '/'):
 
711
                    continue
 
712
 
 
713
                # path within tree
 
714
                fp = appendpath(from_dir_relpath, f)
 
715
 
 
716
                # absolute path
 
717
                fap = appendpath(dp, f)
 
718
                
 
719
                f_ie = inv.get_child(from_dir_id, f)
 
720
                if f_ie:
 
721
                    c = 'V'
 
722
                elif self.is_ignored(fp):
 
723
                    c = 'I'
 
724
                else:
 
725
                    c = '?'
 
726
 
 
727
                fk = file_kind(fap)
 
728
 
 
729
                if f_ie:
 
730
                    if f_ie.kind != fk:
 
731
                        raise BzrCheckError("file %r entered as kind %r id %r, "
 
732
                                            "now of kind %r"
 
733
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
 
734
 
 
735
                # make a last minute entry
 
736
                if f_ie:
 
737
                    entry = f_ie
 
738
                else:
 
739
                    if fk == 'directory':
 
740
                        entry = TreeDirectory()
 
741
                    elif fk == 'file':
 
742
                        entry = TreeFile()
 
743
                    elif fk == 'symlink':
 
744
                        entry = TreeLink()
 
745
                    else:
 
746
                        entry = TreeEntry()
 
747
                
 
748
                yield fp, c, fk, (f_ie and f_ie.file_id), entry
 
749
 
 
750
                if fk != 'directory':
 
751
                    continue
 
752
 
 
753
                if c != 'V':
 
754
                    # don't descend unversioned directories
 
755
                    continue
 
756
                
 
757
                for ff in descend(fp, f_ie.file_id, fap):
 
758
                    yield ff
 
759
 
 
760
        for f in descend(u'', inv.root.file_id, self.basedir):
 
761
            yield f
 
762
 
 
763
    @needs_write_lock
 
764
    def move(self, from_paths, to_name):
 
765
        """Rename files.
 
766
 
 
767
        to_name must exist in the inventory.
 
768
 
 
769
        If to_name exists and is a directory, the files are moved into
 
770
        it, keeping their old names.  
 
771
 
 
772
        Note that to_name is only the last component of the new name;
 
773
        this doesn't change the directory.
 
774
 
 
775
        This returns a list of (from_path, to_path) pairs for each
 
776
        entry that is moved.
 
777
        """
 
778
        result = []
 
779
        ## TODO: Option to move IDs only
 
780
        assert not isinstance(from_paths, basestring)
 
781
        inv = self.inventory
 
782
        to_abs = self.abspath(to_name)
 
783
        if not isdir(to_abs):
 
784
            raise BzrError("destination %r is not a directory" % to_abs)
 
785
        if not self.has_filename(to_name):
 
786
            raise BzrError("destination %r not in working directory" % to_abs)
 
787
        to_dir_id = inv.path2id(to_name)
 
788
        if to_dir_id == None and to_name != '':
 
789
            raise BzrError("destination %r is not a versioned directory" % to_name)
 
790
        to_dir_ie = inv[to_dir_id]
 
791
        if to_dir_ie.kind not in ('directory', 'root_directory'):
 
792
            raise BzrError("destination %r is not a directory" % to_abs)
 
793
 
 
794
        to_idpath = inv.get_idpath(to_dir_id)
 
795
 
 
796
        for f in from_paths:
 
797
            if not self.has_filename(f):
 
798
                raise BzrError("%r does not exist in working tree" % f)
 
799
            f_id = inv.path2id(f)
 
800
            if f_id == None:
 
801
                raise BzrError("%r is not versioned" % f)
 
802
            name_tail = splitpath(f)[-1]
 
803
            dest_path = appendpath(to_name, name_tail)
 
804
            if self.has_filename(dest_path):
 
805
                raise BzrError("destination %r already exists" % dest_path)
 
806
            if f_id in to_idpath:
 
807
                raise BzrError("can't move %r to a subdirectory of itself" % f)
 
808
 
 
809
        # OK, so there's a race here, it's possible that someone will
 
810
        # create a file in this interval and then the rename might be
 
811
        # left half-done.  But we should have caught most problems.
 
812
        orig_inv = deepcopy(self.inventory)
 
813
        try:
 
814
            for f in from_paths:
 
815
                name_tail = splitpath(f)[-1]
 
816
                dest_path = appendpath(to_name, name_tail)
 
817
                result.append((f, dest_path))
 
818
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
 
819
                try:
 
820
                    rename(self.abspath(f), self.abspath(dest_path))
 
821
                except OSError, e:
 
822
                    raise BzrError("failed to rename %r to %r: %s" %
 
823
                                   (f, dest_path, e[1]),
 
824
                            ["rename rolled back"])
 
825
        except:
 
826
            # restore the inventory on error
 
827
            self._set_inventory(orig_inv)
 
828
            raise
 
829
        self._write_inventory(inv)
 
830
        return result
 
831
 
 
832
    @needs_write_lock
 
833
    def rename_one(self, from_rel, to_rel):
 
834
        """Rename one file.
 
835
 
 
836
        This can change the directory or the filename or both.
 
837
        """
 
838
        inv = self.inventory
 
839
        if not self.has_filename(from_rel):
 
840
            raise BzrError("can't rename: old working file %r does not exist" % from_rel)
 
841
        if self.has_filename(to_rel):
 
842
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
 
843
 
 
844
        file_id = inv.path2id(from_rel)
 
845
        if file_id == None:
 
846
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
 
847
 
 
848
        entry = inv[file_id]
 
849
        from_parent = entry.parent_id
 
850
        from_name = entry.name
 
851
        
 
852
        if inv.path2id(to_rel):
 
853
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
 
854
 
 
855
        to_dir, to_tail = os.path.split(to_rel)
 
856
        to_dir_id = inv.path2id(to_dir)
 
857
        if to_dir_id == None and to_dir != '':
 
858
            raise BzrError("can't determine destination directory id for %r" % to_dir)
 
859
 
 
860
        mutter("rename_one:")
 
861
        mutter("  file_id    {%s}" % file_id)
 
862
        mutter("  from_rel   %r" % from_rel)
 
863
        mutter("  to_rel     %r" % to_rel)
 
864
        mutter("  to_dir     %r" % to_dir)
 
865
        mutter("  to_dir_id  {%s}" % to_dir_id)
 
866
 
 
867
        inv.rename(file_id, to_dir_id, to_tail)
 
868
 
 
869
        from_abs = self.abspath(from_rel)
 
870
        to_abs = self.abspath(to_rel)
 
871
        try:
 
872
            rename(from_abs, to_abs)
 
873
        except OSError, e:
 
874
            inv.rename(file_id, from_parent, from_name)
 
875
            raise BzrError("failed to rename %r to %r: %s"
 
876
                    % (from_abs, to_abs, e[1]),
 
877
                    ["rename rolled back"])
 
878
        self._write_inventory(inv)
 
879
 
 
880
    @needs_read_lock
 
881
    def unknowns(self):
 
882
        """Return all unknown files.
 
883
 
 
884
        These are files in the working directory that are not versioned or
 
885
        control files or ignored.
 
886
        
 
887
        >>> from bzrlib.bzrdir import ScratchDir
 
888
        >>> d = ScratchDir(files=['foo', 'foo~'])
 
889
        >>> b = d.open_branch()
 
890
        >>> tree = d.open_workingtree()
 
891
        >>> map(str, tree.unknowns())
 
892
        ['foo']
 
893
        >>> tree.add('foo')
 
894
        >>> list(b.unknowns())
 
895
        []
 
896
        >>> tree.remove('foo')
 
897
        >>> list(b.unknowns())
 
898
        [u'foo']
 
899
        """
 
900
        for subp in self.extras():
 
901
            if not self.is_ignored(subp):
 
902
                yield subp
 
903
 
 
904
    @deprecated_method(zero_eight)
 
905
    def iter_conflicts(self):
 
906
        """List all files in the tree that have text or content conflicts.
 
907
        DEPRECATED.  Use conflicts instead."""
 
908
        return self._iter_conflicts()
 
909
 
 
910
    def _iter_conflicts(self):
 
911
        conflicted = set()
 
912
        for path in (s[0] for s in self.list_files()):
 
913
            stem = get_conflicted_stem(path)
 
914
            if stem is None:
 
915
                continue
 
916
            if stem not in conflicted:
 
917
                conflicted.add(stem)
 
918
                yield stem
 
919
 
 
920
    @needs_write_lock
 
921
    def pull(self, source, overwrite=False, stop_revision=None):
 
922
        top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
923
        source.lock_read()
 
924
        try:
 
925
            pp = ProgressPhase("Pull phase", 2, top_pb)
 
926
            pp.next_phase()
 
927
            old_revision_history = self.branch.revision_history()
 
928
            basis_tree = self.basis_tree()
 
929
            count = self.branch.pull(source, overwrite, stop_revision)
 
930
            new_revision_history = self.branch.revision_history()
 
931
            if new_revision_history != old_revision_history:
 
932
                pp.next_phase()
 
933
                if len(old_revision_history):
 
934
                    other_revision = old_revision_history[-1]
 
935
                else:
 
936
                    other_revision = None
 
937
                repository = self.branch.repository
 
938
                pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
939
                try:
 
940
                    merge_inner(self.branch,
 
941
                                self.branch.basis_tree(),
 
942
                                basis_tree, 
 
943
                                this_tree=self, 
 
944
                                pb=pb)
 
945
                finally:
 
946
                    pb.finished()
 
947
                self.set_last_revision(self.branch.last_revision())
 
948
            return count
 
949
        finally:
 
950
            source.unlock()
 
951
            top_pb.finished()
 
952
 
 
953
    def extras(self):
 
954
        """Yield all unknown files in this WorkingTree.
 
955
 
 
956
        If there are any unknown directories then only the directory is
 
957
        returned, not all its children.  But if there are unknown files
 
958
        under a versioned subdirectory, they are returned.
 
959
 
 
960
        Currently returned depth-first, sorted by name within directories.
 
961
        """
 
962
        ## TODO: Work from given directory downwards
 
963
        for path, dir_entry in self.inventory.directories():
 
964
            mutter("search for unknowns in %r", path)
 
965
            dirabs = self.abspath(path)
 
966
            if not isdir(dirabs):
 
967
                # e.g. directory deleted
 
968
                continue
 
969
 
 
970
            fl = []
 
971
            for subf in os.listdir(dirabs):
 
972
                if (subf != '.bzr'
 
973
                    and (subf not in dir_entry.children)):
 
974
                    fl.append(subf)
 
975
            
 
976
            fl.sort()
 
977
            for subf in fl:
 
978
                subp = appendpath(path, subf)
 
979
                yield subp
 
980
 
 
981
 
 
982
    def ignored_files(self):
 
983
        """Yield list of PATH, IGNORE_PATTERN"""
 
984
        for subp in self.extras():
 
985
            pat = self.is_ignored(subp)
 
986
            if pat != None:
 
987
                yield subp, pat
 
988
 
 
989
 
 
990
    def get_ignore_list(self):
 
991
        """Return list of ignore patterns.
 
992
 
 
993
        Cached in the Tree object after the first call.
 
994
        """
 
995
        if hasattr(self, '_ignorelist'):
 
996
            return self._ignorelist
 
997
 
 
998
        l = bzrlib.DEFAULT_IGNORE[:]
 
999
        if self.has_filename(bzrlib.IGNORE_FILENAME):
 
1000
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
 
1001
            l.extend([line.rstrip("\n\r") for line in f.readlines()])
 
1002
        self._ignorelist = l
 
1003
        return l
 
1004
 
 
1005
 
 
1006
    def is_ignored(self, filename):
 
1007
        r"""Check whether the filename matches an ignore pattern.
 
1008
 
 
1009
        Patterns containing '/' or '\' need to match the whole path;
 
1010
        others match against only the last component.
 
1011
 
 
1012
        If the file is ignored, returns the pattern which caused it to
 
1013
        be ignored, otherwise None.  So this can simply be used as a
 
1014
        boolean if desired."""
 
1015
 
 
1016
        # TODO: Use '**' to match directories, and other extended
 
1017
        # globbing stuff from cvs/rsync.
 
1018
 
 
1019
        # XXX: fnmatch is actually not quite what we want: it's only
 
1020
        # approximately the same as real Unix fnmatch, and doesn't
 
1021
        # treat dotfiles correctly and allows * to match /.
 
1022
        # Eventually it should be replaced with something more
 
1023
        # accurate.
 
1024
        
 
1025
        basename = splitpath(filename)[-1]
 
1026
        for pat in self.get_ignore_list():
 
1027
            if '/' in pat or '\\' in pat:
 
1028
                
 
1029
                # as a special case, you can put ./ at the start of a
 
1030
                # pattern; this is good to match in the top-level
 
1031
                # only;
 
1032
                if pat[:2] in ('./', '.\\'):
 
1033
                    newpat = pat[2:]
 
1034
                else:
 
1035
                    newpat = pat
 
1036
                if fnmatch.fnmatchcase(filename, newpat):
 
1037
                    return pat
 
1038
            else:
 
1039
                if fnmatch.fnmatchcase(basename, pat):
 
1040
                    return pat
 
1041
        return None
 
1042
 
 
1043
    def kind(self, file_id):
 
1044
        return file_kind(self.id2abspath(file_id))
 
1045
 
 
1046
    @needs_read_lock
 
1047
    def last_revision(self):
 
1048
        """Return the last revision id of this working tree.
 
1049
 
 
1050
        In early branch formats this was == the branch last_revision,
 
1051
        but that cannot be relied upon - for working tree operations,
 
1052
        always use tree.last_revision().
 
1053
        """
 
1054
        return self.branch.last_revision()
 
1055
 
 
1056
    def is_locked(self):
 
1057
        return self._control_files.is_locked()
 
1058
 
 
1059
    def lock_read(self):
 
1060
        """See Branch.lock_read, and WorkingTree.unlock."""
 
1061
        self.branch.lock_read()
 
1062
        try:
 
1063
            return self._control_files.lock_read()
 
1064
        except:
 
1065
            self.branch.unlock()
 
1066
            raise
 
1067
 
 
1068
    def lock_write(self):
 
1069
        """See Branch.lock_write, and WorkingTree.unlock."""
 
1070
        self.branch.lock_write()
 
1071
        try:
 
1072
            return self._control_files.lock_write()
 
1073
        except:
 
1074
            self.branch.unlock()
 
1075
            raise
 
1076
 
 
1077
    def get_physical_lock_status(self):
 
1078
        return self._control_files.get_physical_lock_status()
 
1079
 
 
1080
    def _basis_inventory_name(self):
 
1081
        return 'basis-inventory'
 
1082
 
 
1083
    @needs_write_lock
 
1084
    def set_last_revision(self, new_revision):
 
1085
        """Change the last revision in the working tree."""
 
1086
        if self._change_last_revision(new_revision):
 
1087
            self._cache_basis_inventory(new_revision)
 
1088
 
 
1089
    def _change_last_revision(self, new_revision):
 
1090
        """Template method part of set_last_revision to perform the change.
 
1091
        
 
1092
        This is used to allow WorkingTree3 instances to not affect branch
 
1093
        when their last revision is set.
 
1094
        """
 
1095
        if new_revision is None:
 
1096
            self.branch.set_revision_history([])
 
1097
            return False
 
1098
        # current format is locked in with the branch
 
1099
        revision_history = self.branch.revision_history()
 
1100
        try:
 
1101
            position = revision_history.index(new_revision)
 
1102
        except ValueError:
 
1103
            raise errors.NoSuchRevision(self.branch, new_revision)
 
1104
        self.branch.set_revision_history(revision_history[:position + 1])
 
1105
        return True
 
1106
 
 
1107
    def _cache_basis_inventory(self, new_revision):
 
1108
        """Cache new_revision as the basis inventory."""
 
1109
        try:
 
1110
            # this double handles the inventory - unpack and repack - 
 
1111
            # but is easier to understand. We can/should put a conditional
 
1112
            # in here based on whether the inventory is in the latest format
 
1113
            # - perhaps we should repack all inventories on a repository
 
1114
            # upgrade ?
 
1115
            inv = self.branch.repository.get_inventory(new_revision)
 
1116
            inv.revision_id = new_revision
 
1117
            xml = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
 
1118
 
 
1119
            path = self._basis_inventory_name()
 
1120
            self._control_files.put_utf8(path, xml)
 
1121
        except WeaveRevisionNotPresent:
 
1122
            pass
 
1123
 
 
1124
    def read_basis_inventory(self):
 
1125
        """Read the cached basis inventory."""
 
1126
        path = self._basis_inventory_name()
 
1127
        return self._control_files.get_utf8(path).read()
 
1128
        
 
1129
    @needs_read_lock
 
1130
    def read_working_inventory(self):
 
1131
        """Read the working inventory."""
 
1132
        # ElementTree does its own conversion from UTF-8, so open in
 
1133
        # binary.
 
1134
        result = bzrlib.xml5.serializer_v5.read_inventory(
 
1135
            self._control_files.get('inventory'))
 
1136
        self._set_inventory(result)
 
1137
        return result
 
1138
 
 
1139
    @needs_write_lock
 
1140
    def remove(self, files, verbose=False):
 
1141
        """Remove nominated files from the working inventory..
 
1142
 
 
1143
        This does not remove their text.  This does not run on XXX on what? RBC
 
1144
 
 
1145
        TODO: Refuse to remove modified files unless --force is given?
 
1146
 
 
1147
        TODO: Do something useful with directories.
 
1148
 
 
1149
        TODO: Should this remove the text or not?  Tough call; not
 
1150
        removing may be useful and the user can just use use rm, and
 
1151
        is the opposite of add.  Removing it is consistent with most
 
1152
        other tools.  Maybe an option.
 
1153
        """
 
1154
        ## TODO: Normalize names
 
1155
        ## TODO: Remove nested loops; better scalability
 
1156
        if isinstance(files, basestring):
 
1157
            files = [files]
 
1158
 
 
1159
        inv = self.inventory
 
1160
 
 
1161
        # do this before any modifications
 
1162
        for f in files:
 
1163
            fid = inv.path2id(f)
 
1164
            if not fid:
 
1165
                # TODO: Perhaps make this just a warning, and continue?
 
1166
                # This tends to happen when 
 
1167
                raise NotVersionedError(path=f)
 
1168
            mutter("remove inventory entry %s {%s}", quotefn(f), fid)
 
1169
            if verbose:
 
1170
                # having remove it, it must be either ignored or unknown
 
1171
                if self.is_ignored(f):
 
1172
                    new_status = 'I'
 
1173
                else:
 
1174
                    new_status = '?'
 
1175
                show_status(new_status, inv[fid].kind, quotefn(f))
 
1176
            del inv[fid]
 
1177
 
 
1178
        self._write_inventory(inv)
 
1179
 
 
1180
    @needs_write_lock
 
1181
    def revert(self, filenames, old_tree=None, backups=True, 
 
1182
               pb=DummyProgress()):
 
1183
        from transform import revert
 
1184
        from conflicts import resolve
 
1185
        if old_tree is None:
 
1186
            old_tree = self.basis_tree()
 
1187
        conflicts = revert(self, old_tree, filenames, backups, pb)
 
1188
        if not len(filenames):
 
1189
            self.set_pending_merges([])
 
1190
            resolve(self)
 
1191
        else:
 
1192
            resolve(self, filenames, ignore_misses=True)
 
1193
        return conflicts
 
1194
 
 
1195
    # XXX: This method should be deprecated in favour of taking in a proper
 
1196
    # new Inventory object.
 
1197
    @needs_write_lock
 
1198
    def set_inventory(self, new_inventory_list):
 
1199
        from bzrlib.inventory import (Inventory,
 
1200
                                      InventoryDirectory,
 
1201
                                      InventoryEntry,
 
1202
                                      InventoryFile,
 
1203
                                      InventoryLink)
 
1204
        inv = Inventory(self.get_root_id())
 
1205
        for path, file_id, parent, kind in new_inventory_list:
 
1206
            name = os.path.basename(path)
 
1207
            if name == "":
 
1208
                continue
 
1209
            # fixme, there should be a factory function inv,add_?? 
 
1210
            if kind == 'directory':
 
1211
                inv.add(InventoryDirectory(file_id, name, parent))
 
1212
            elif kind == 'file':
 
1213
                inv.add(InventoryFile(file_id, name, parent))
 
1214
            elif kind == 'symlink':
 
1215
                inv.add(InventoryLink(file_id, name, parent))
 
1216
            else:
 
1217
                raise BzrError("unknown kind %r" % kind)
 
1218
        self._write_inventory(inv)
 
1219
 
 
1220
    @needs_write_lock
 
1221
    def set_root_id(self, file_id):
 
1222
        """Set the root id for this tree."""
 
1223
        inv = self.read_working_inventory()
 
1224
        orig_root_id = inv.root.file_id
 
1225
        del inv._byid[inv.root.file_id]
 
1226
        inv.root.file_id = file_id
 
1227
        inv._byid[inv.root.file_id] = inv.root
 
1228
        for fid in inv:
 
1229
            entry = inv[fid]
 
1230
            if entry.parent_id == orig_root_id:
 
1231
                entry.parent_id = inv.root.file_id
 
1232
        self._write_inventory(inv)
 
1233
 
 
1234
    def unlock(self):
 
1235
        """See Branch.unlock.
 
1236
        
 
1237
        WorkingTree locking just uses the Branch locking facilities.
 
1238
        This is current because all working trees have an embedded branch
 
1239
        within them. IF in the future, we were to make branch data shareable
 
1240
        between multiple working trees, i.e. via shared storage, then we 
 
1241
        would probably want to lock both the local tree, and the branch.
 
1242
        """
 
1243
        # FIXME: We want to write out the hashcache only when the last lock on
 
1244
        # this working copy is released.  Peeking at the lock count is a bit
 
1245
        # of a nasty hack; probably it's better to have a transaction object,
 
1246
        # which can do some finalization when it's either successfully or
 
1247
        # unsuccessfully completed.  (Denys's original patch did that.)
 
1248
        # RBC 20060206 hookinhg into transaction will couple lock and transaction
 
1249
        # wrongly. Hookinh into unllock on the control files object is fine though.
 
1250
        
 
1251
        # TODO: split this per format so there is no ugly if block
 
1252
        if self._hashcache.needs_write and (
 
1253
            # dedicated lock files
 
1254
            self._control_files._lock_count==1 or 
 
1255
            # shared lock files
 
1256
            (self._control_files is self.branch.control_files and 
 
1257
             self._control_files._lock_count==3)):
 
1258
            self._hashcache.write()
 
1259
        # reverse order of locking.
 
1260
        try:
 
1261
            return self._control_files.unlock()
 
1262
        finally:
 
1263
            self.branch.unlock()
 
1264
 
 
1265
    @needs_write_lock
 
1266
    def update(self):
 
1267
        """Update a working tree along its branch.
 
1268
 
 
1269
        This will update the branch if its bound too, which means we have multiple trees involved:
 
1270
        The new basis tree of the master.
 
1271
        The old basis tree of the branch.
 
1272
        The old basis tree of the working tree.
 
1273
        The current working tree state.
 
1274
        pathologically all three may be different, and non ancestors of each other.
 
1275
        Conceptually we want to:
 
1276
        Preserve the wt.basis->wt.state changes
 
1277
        Transform the wt.basis to the new master basis.
 
1278
        Apply a merge of the old branch basis to get any 'local' changes from it into the tree.
 
1279
        Restore the wt.basis->wt.state changes.
 
1280
 
 
1281
        There isn't a single operation at the moment to do that, so we:
 
1282
        Merge current state -> basis tree of the master w.r.t. the old tree basis.
 
1283
        Do a 'normal' merge of the old branch basis if it is relevant.
 
1284
        """
 
1285
        old_tip = self.branch.update()
 
1286
        if old_tip is not None:
 
1287
            self.add_pending_merge(old_tip)
 
1288
        self.branch.lock_read()
 
1289
        try:
 
1290
            result = 0
 
1291
            if self.last_revision() != self.branch.last_revision():
 
1292
                # merge tree state up to new branch tip.
 
1293
                basis = self.basis_tree()
 
1294
                to_tree = self.branch.basis_tree()
 
1295
                result += merge_inner(self.branch,
 
1296
                                      to_tree,
 
1297
                                      basis,
 
1298
                                      this_tree=self)
 
1299
                self.set_last_revision(self.branch.last_revision())
 
1300
            if old_tip and old_tip != self.last_revision():
 
1301
                # our last revision was not the prior branch last reivison
 
1302
                # and we have converted that last revision to a pending merge.
 
1303
                # base is somewhere between the branch tip now
 
1304
                # and the now pending merge
 
1305
                from bzrlib.revision import common_ancestor
 
1306
                try:
 
1307
                    base_rev_id = common_ancestor(self.branch.last_revision(),
 
1308
                                                  old_tip,
 
1309
                                                  self.branch.repository)
 
1310
                except errors.NoCommonAncestor:
 
1311
                    base_rev_id = None
 
1312
                base_tree = self.branch.repository.revision_tree(base_rev_id)
 
1313
                other_tree = self.branch.repository.revision_tree(old_tip)
 
1314
                result += merge_inner(self.branch,
 
1315
                                      other_tree,
 
1316
                                      base_tree,
 
1317
                                      this_tree=self)
 
1318
            return result
 
1319
        finally:
 
1320
            self.branch.unlock()
 
1321
 
 
1322
    @needs_write_lock
 
1323
    def _write_inventory(self, inv):
 
1324
        """Write inventory as the current inventory."""
 
1325
        sio = StringIO()
 
1326
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
 
1327
        sio.seek(0)
 
1328
        self._control_files.put('inventory', sio)
 
1329
        self._set_inventory(inv)
 
1330
        mutter('wrote working inventory')
 
1331
 
 
1332
    def set_conflicts(self, arg):
 
1333
        raise UnsupportedOperation(self.set_conflicts, self)
 
1334
 
 
1335
    @needs_read_lock
 
1336
    def conflicts(self):
 
1337
        conflicts = ConflictList()
 
1338
        for conflicted in self._iter_conflicts():
 
1339
            text = True
 
1340
            try:
 
1341
                if file_kind(self.abspath(conflicted)) != "file":
 
1342
                    text = False
 
1343
            except OSError, e:
 
1344
                if e.errno == errno.ENOENT:
 
1345
                    text = False
 
1346
                else:
 
1347
                    raise
 
1348
            if text is True:
 
1349
                for suffix in ('.THIS', '.OTHER'):
 
1350
                    try:
 
1351
                        kind = file_kind(self.abspath(conflicted+suffix))
 
1352
                    except OSError, e:
 
1353
                        if e.errno == errno.ENOENT:
 
1354
                            text = False
 
1355
                            break
 
1356
                        else:
 
1357
                            raise
 
1358
                    if kind != "file":
 
1359
                        text = False
 
1360
                        break
 
1361
            ctype = {True: 'text conflict', False: 'contents conflict'}[text]
 
1362
            conflicts.append(Conflict.factory(ctype, path=conflicted,
 
1363
                             file_id=self.path2id(conflicted)))
 
1364
        return conflicts
 
1365
 
 
1366
 
 
1367
class WorkingTree3(WorkingTree):
 
1368
    """This is the Format 3 working tree.
 
1369
 
 
1370
    This differs from the base WorkingTree by:
 
1371
     - having its own file lock
 
1372
     - having its own last-revision property.
 
1373
 
 
1374
    This is new in bzr 0.8
 
1375
    """
 
1376
 
 
1377
    @needs_read_lock
 
1378
    def last_revision(self):
 
1379
        """See WorkingTree.last_revision."""
 
1380
        try:
 
1381
            return self._control_files.get_utf8('last-revision').read()
 
1382
        except NoSuchFile:
 
1383
            return None
 
1384
 
 
1385
    def _change_last_revision(self, revision_id):
 
1386
        """See WorkingTree._change_last_revision."""
 
1387
        if revision_id is None or revision_id == NULL_REVISION:
 
1388
            try:
 
1389
                self._control_files._transport.delete('last-revision')
 
1390
            except errors.NoSuchFile:
 
1391
                pass
 
1392
            return False
 
1393
        else:
 
1394
            try:
 
1395
                self.branch.revision_history().index(revision_id)
 
1396
            except ValueError:
 
1397
                raise errors.NoSuchRevision(self.branch, revision_id)
 
1398
            self._control_files.put_utf8('last-revision', revision_id)
 
1399
            return True
 
1400
 
 
1401
    @needs_write_lock
 
1402
    def set_conflicts(self, conflicts):
 
1403
        self._put_rio('conflicts', conflicts.to_stanzas(), 
 
1404
                      CONFLICT_HEADER_1)
 
1405
 
 
1406
    @needs_read_lock
 
1407
    def conflicts(self):
 
1408
        try:
 
1409
            confile = self._control_files.get('conflicts')
 
1410
        except NoSuchFile:
 
1411
            return ConflictList()
 
1412
        try:
 
1413
            if confile.next() != CONFLICT_HEADER_1 + '\n':
 
1414
                raise ConflictFormatError()
 
1415
        except StopIteration:
 
1416
            raise ConflictFormatError()
 
1417
        return ConflictList.from_stanzas(RioReader(confile))
 
1418
 
 
1419
 
 
1420
def get_conflicted_stem(path):
 
1421
    for suffix in CONFLICT_SUFFIXES:
 
1422
        if path.endswith(suffix):
 
1423
            return path[:-len(suffix)]
 
1424
 
 
1425
@deprecated_function(zero_eight)
 
1426
def is_control_file(filename):
 
1427
    """See WorkingTree.is_control_filename(filename)."""
 
1428
    ## FIXME: better check
 
1429
    filename = normpath(filename)
 
1430
    while filename != '':
 
1431
        head, tail = os.path.split(filename)
 
1432
        ## mutter('check %r for control file' % ((head, tail),))
 
1433
        if tail == '.bzr':
 
1434
            return True
 
1435
        if filename == head:
 
1436
            break
 
1437
        filename = head
 
1438
    return False
 
1439
 
 
1440
 
 
1441
class WorkingTreeFormat(object):
 
1442
    """An encapsulation of the initialization and open routines for a format.
 
1443
 
 
1444
    Formats provide three things:
 
1445
     * An initialization routine,
 
1446
     * a format string,
 
1447
     * an open routine.
 
1448
 
 
1449
    Formats are placed in an dict by their format string for reference 
 
1450
    during workingtree opening. Its not required that these be instances, they
 
1451
    can be classes themselves with class methods - it simply depends on 
 
1452
    whether state is needed for a given format or not.
 
1453
 
 
1454
    Once a format is deprecated, just deprecate the initialize and open
 
1455
    methods on the format class. Do not deprecate the object, as the 
 
1456
    object will be created every time regardless.
 
1457
    """
 
1458
 
 
1459
    _default_format = None
 
1460
    """The default format used for new trees."""
 
1461
 
 
1462
    _formats = {}
 
1463
    """The known formats."""
 
1464
 
 
1465
    @classmethod
 
1466
    def find_format(klass, a_bzrdir):
 
1467
        """Return the format for the working tree object in a_bzrdir."""
 
1468
        try:
 
1469
            transport = a_bzrdir.get_workingtree_transport(None)
 
1470
            format_string = transport.get("format").read()
 
1471
            return klass._formats[format_string]
 
1472
        except NoSuchFile:
 
1473
            raise errors.NoWorkingTree(base=transport.base)
 
1474
        except KeyError:
 
1475
            raise errors.UnknownFormatError(format_string)
 
1476
 
 
1477
    @classmethod
 
1478
    def get_default_format(klass):
 
1479
        """Return the current default format."""
 
1480
        return klass._default_format
 
1481
 
 
1482
    def get_format_string(self):
 
1483
        """Return the ASCII format string that identifies this format."""
 
1484
        raise NotImplementedError(self.get_format_string)
 
1485
 
 
1486
    def get_format_description(self):
 
1487
        """Return the short description for this format."""
 
1488
        raise NotImplementedError(self.get_format_description)
 
1489
 
 
1490
    def is_supported(self):
 
1491
        """Is this format supported?
 
1492
 
 
1493
        Supported formats can be initialized and opened.
 
1494
        Unsupported formats may not support initialization or committing or 
 
1495
        some other features depending on the reason for not being supported.
 
1496
        """
 
1497
        return True
 
1498
 
 
1499
    @classmethod
 
1500
    def register_format(klass, format):
 
1501
        klass._formats[format.get_format_string()] = format
 
1502
 
 
1503
    @classmethod
 
1504
    def set_default_format(klass, format):
 
1505
        klass._default_format = format
 
1506
 
 
1507
    @classmethod
 
1508
    def unregister_format(klass, format):
 
1509
        assert klass._formats[format.get_format_string()] is format
 
1510
        del klass._formats[format.get_format_string()]
 
1511
 
 
1512
 
 
1513
 
 
1514
class WorkingTreeFormat2(WorkingTreeFormat):
 
1515
    """The second working tree format. 
 
1516
 
 
1517
    This format modified the hash cache from the format 1 hash cache.
 
1518
    """
 
1519
 
 
1520
    def get_format_description(self):
 
1521
        """See WorkingTreeFormat.get_format_description()."""
 
1522
        return "Working tree format 2"
 
1523
 
 
1524
    def stub_initialize_remote(self, control_files):
 
1525
        """As a special workaround create critical control files for a remote working tree
 
1526
        
 
1527
        This ensures that it can later be updated and dealt with locally,
 
1528
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with 
 
1529
        no working tree.  (See bug #43064).
 
1530
        """
 
1531
        sio = StringIO()
 
1532
        inv = Inventory()
 
1533
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
 
1534
        sio.seek(0)
 
1535
        control_files.put('inventory', sio)
 
1536
 
 
1537
        control_files.put_utf8('pending-merges', '')
 
1538
        
 
1539
 
 
1540
    def initialize(self, a_bzrdir, revision_id=None):
 
1541
        """See WorkingTreeFormat.initialize()."""
 
1542
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
1543
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
1544
        branch = a_bzrdir.open_branch()
 
1545
        if revision_id is not None:
 
1546
            branch.lock_write()
 
1547
            try:
 
1548
                revision_history = branch.revision_history()
 
1549
                try:
 
1550
                    position = revision_history.index(revision_id)
 
1551
                except ValueError:
 
1552
                    raise errors.NoSuchRevision(branch, revision_id)
 
1553
                branch.set_revision_history(revision_history[:position + 1])
 
1554
            finally:
 
1555
                branch.unlock()
 
1556
        revision = branch.last_revision()
 
1557
        inv = Inventory() 
 
1558
        wt = WorkingTree(a_bzrdir.root_transport.base,
 
1559
                         branch,
 
1560
                         inv,
 
1561
                         _internal=True,
 
1562
                         _format=self,
 
1563
                         _bzrdir=a_bzrdir)
 
1564
        wt._write_inventory(inv)
 
1565
        wt.set_root_id(inv.root.file_id)
 
1566
        wt.set_last_revision(revision)
 
1567
        wt.set_pending_merges([])
 
1568
        build_tree(wt.basis_tree(), wt)
 
1569
        return wt
 
1570
 
 
1571
    def __init__(self):
 
1572
        super(WorkingTreeFormat2, self).__init__()
 
1573
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
1574
 
 
1575
    def open(self, a_bzrdir, _found=False):
 
1576
        """Return the WorkingTree object for a_bzrdir
 
1577
 
 
1578
        _found is a private parameter, do not use it. It is used to indicate
 
1579
               if format probing has already been done.
 
1580
        """
 
1581
        if not _found:
 
1582
            # we are being called directly and must probe.
 
1583
            raise NotImplementedError
 
1584
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
1585
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
1586
        return WorkingTree(a_bzrdir.root_transport.base,
 
1587
                           _internal=True,
 
1588
                           _format=self,
 
1589
                           _bzrdir=a_bzrdir)
 
1590
 
 
1591
 
 
1592
class WorkingTreeFormat3(WorkingTreeFormat):
 
1593
    """The second working tree format updated to record a format marker.
 
1594
 
 
1595
    This format:
 
1596
        - exists within a metadir controlling .bzr
 
1597
        - includes an explicit version marker for the workingtree control
 
1598
          files, separate from the BzrDir format
 
1599
        - modifies the hash cache format
 
1600
        - is new in bzr 0.8
 
1601
        - uses a LockDir to guard access to the repository
 
1602
    """
 
1603
 
 
1604
    def get_format_string(self):
 
1605
        """See WorkingTreeFormat.get_format_string()."""
 
1606
        return "Bazaar-NG Working Tree format 3"
 
1607
 
 
1608
    def get_format_description(self):
 
1609
        """See WorkingTreeFormat.get_format_description()."""
 
1610
        return "Working tree format 3"
 
1611
 
 
1612
    _lock_file_name = 'lock'
 
1613
    _lock_class = LockDir
 
1614
 
 
1615
    def _open_control_files(self, a_bzrdir):
 
1616
        transport = a_bzrdir.get_workingtree_transport(None)
 
1617
        return LockableFiles(transport, self._lock_file_name, 
 
1618
                             self._lock_class)
 
1619
 
 
1620
    def initialize(self, a_bzrdir, revision_id=None):
 
1621
        """See WorkingTreeFormat.initialize().
 
1622
        
 
1623
        revision_id allows creating a working tree at a differnet
 
1624
        revision than the branch is at.
 
1625
        """
 
1626
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
1627
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
1628
        transport = a_bzrdir.get_workingtree_transport(self)
 
1629
        control_files = self._open_control_files(a_bzrdir)
 
1630
        control_files.create_lock()
 
1631
        control_files.lock_write()
 
1632
        control_files.put_utf8('format', self.get_format_string())
 
1633
        branch = a_bzrdir.open_branch()
 
1634
        if revision_id is None:
 
1635
            revision_id = branch.last_revision()
 
1636
        inv = Inventory() 
 
1637
        wt = WorkingTree3(a_bzrdir.root_transport.base,
 
1638
                         branch,
 
1639
                         inv,
 
1640
                         _internal=True,
 
1641
                         _format=self,
 
1642
                         _bzrdir=a_bzrdir,
 
1643
                         _control_files=control_files)
 
1644
        wt.lock_write()
 
1645
        try:
 
1646
            wt._write_inventory(inv)
 
1647
            wt.set_root_id(inv.root.file_id)
 
1648
            wt.set_last_revision(revision_id)
 
1649
            wt.set_pending_merges([])
 
1650
            build_tree(wt.basis_tree(), wt)
 
1651
        finally:
 
1652
            wt.unlock()
 
1653
            control_files.unlock()
 
1654
        return wt
 
1655
 
 
1656
    def __init__(self):
 
1657
        super(WorkingTreeFormat3, self).__init__()
 
1658
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1659
 
 
1660
    def open(self, a_bzrdir, _found=False):
 
1661
        """Return the WorkingTree object for a_bzrdir
 
1662
 
 
1663
        _found is a private parameter, do not use it. It is used to indicate
 
1664
               if format probing has already been done.
 
1665
        """
 
1666
        if not _found:
 
1667
            # we are being called directly and must probe.
 
1668
            raise NotImplementedError
 
1669
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
1670
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
1671
        control_files = self._open_control_files(a_bzrdir)
 
1672
        return WorkingTree3(a_bzrdir.root_transport.base,
 
1673
                           _internal=True,
 
1674
                           _format=self,
 
1675
                           _bzrdir=a_bzrdir,
 
1676
                           _control_files=control_files)
 
1677
 
 
1678
    def __str__(self):
 
1679
        return self.get_format_string()
 
1680
 
 
1681
 
 
1682
# formats which have no format string are not discoverable
 
1683
# and not independently creatable, so are not registered.
 
1684
__default_format = WorkingTreeFormat3()
 
1685
WorkingTreeFormat.register_format(__default_format)
 
1686
WorkingTreeFormat.set_default_format(__default_format)
 
1687
_legacy_formats = [WorkingTreeFormat2(),
 
1688
                   ]
 
1689
 
 
1690
 
 
1691
class WorkingTreeTestProviderAdapter(object):
 
1692
    """A tool to generate a suite testing multiple workingtree formats at once.
 
1693
 
 
1694
    This is done by copying the test once for each transport and injecting
 
1695
    the transport_server, transport_readonly_server, and workingtree_format
 
1696
    classes into each copy. Each copy is also given a new id() to make it
 
1697
    easy to identify.
 
1698
    """
 
1699
 
 
1700
    def __init__(self, transport_server, transport_readonly_server, formats):
 
1701
        self._transport_server = transport_server
 
1702
        self._transport_readonly_server = transport_readonly_server
 
1703
        self._formats = formats
 
1704
    
 
1705
    def adapt(self, test):
 
1706
        from bzrlib.tests import TestSuite
 
1707
        result = TestSuite()
 
1708
        for workingtree_format, bzrdir_format in self._formats:
 
1709
            new_test = deepcopy(test)
 
1710
            new_test.transport_server = self._transport_server
 
1711
            new_test.transport_readonly_server = self._transport_readonly_server
 
1712
            new_test.bzrdir_format = bzrdir_format
 
1713
            new_test.workingtree_format = workingtree_format
 
1714
            def make_new_test_id():
 
1715
                new_id = "%s(%s)" % (new_test.id(), workingtree_format.__class__.__name__)
 
1716
                return lambda: new_id
 
1717
            new_test.id = make_new_test_id()
 
1718
            result.addTest(new_test)
 
1719
        return result