/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

Merged John Meinel's integration

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 Canonical Ltd
 
2
 
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
 
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
 
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""WorkingTree object and friends.
 
18
 
 
19
A WorkingTree represents the editable working copy of a branch.
 
20
Operations which represent the WorkingTree are also done here, 
 
21
such as renaming or adding files.  The WorkingTree has an inventory 
 
22
which is updated by these operations.  A commit produces a 
 
23
new revision based on the workingtree and its inventory.
 
24
 
 
25
At the moment every WorkingTree has its own branch.  Remote
 
26
WorkingTrees aren't supported.
 
27
 
 
28
To get a WorkingTree, call WorkingTree(dir[, branch])
 
29
"""
 
30
 
 
31
 
 
32
# FIXME: I don't know if writing out the cache from the destructor is really a
 
33
# good idea, because destructors are considered poor taste in Python, and it's
 
34
# not predictable when it will be written out.
 
35
 
 
36
# TODO: Give the workingtree sole responsibility for the working inventory;
 
37
# remove the variable and references to it from the branch.  This may require
 
38
# updating the commit code so as to update the inventory within the working
 
39
# copy, and making sure there's only one WorkingTree for any directory on disk.
 
40
# At the momenthey may alias the inventory and have old copies of it in memory.
 
41
 
 
42
from copy import deepcopy
 
43
from cStringIO import StringIO
 
44
import errno
 
45
import fnmatch
 
46
import os
 
47
import stat
 
48
 
 
49
 
 
50
from bzrlib.atomicfile import AtomicFile
 
51
from bzrlib.branch import (Branch,
 
52
                           BzrBranchFormat4,
 
53
                           BzrBranchFormat5,
 
54
                           BzrBranchFormat6,
 
55
                           is_control_file,
 
56
                           quotefn)
 
57
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
58
from bzrlib.errors import (BzrCheckError,
 
59
                           BzrError,
 
60
                           DivergedBranches,
 
61
                           WeaveRevisionNotPresent,
 
62
                           NotBranchError,
 
63
                           NoSuchFile,
 
64
                           NotVersionedError)
 
65
from bzrlib.inventory import InventoryEntry
 
66
from bzrlib.lockable_files import LockableFiles
 
67
from bzrlib.osutils import (appendpath,
 
68
                            compact_date,
 
69
                            file_kind,
 
70
                            isdir,
 
71
                            getcwd,
 
72
                            pathjoin,
 
73
                            pumpfile,
 
74
                            safe_unicode,
 
75
                            splitpath,
 
76
                            rand_bytes,
 
77
                            abspath,
 
78
                            normpath,
 
79
                            realpath,
 
80
                            relpath,
 
81
                            rename,
 
82
                            supports_executable,
 
83
                            )
 
84
from bzrlib.symbol_versioning import *
 
85
from bzrlib.textui import show_status
 
86
import bzrlib.tree
 
87
from bzrlib.trace import mutter
 
88
from bzrlib.transport import get_transport
 
89
import bzrlib.xml5
 
90
 
 
91
 
 
92
def gen_file_id(name):
 
93
    """Return new file id.
 
94
 
 
95
    This should probably generate proper UUIDs, but for the moment we
 
96
    cope with just randomness because running uuidgen every time is
 
97
    slow."""
 
98
    import re
 
99
    from binascii import hexlify
 
100
    from time import time
 
101
 
 
102
    # get last component
 
103
    idx = name.rfind('/')
 
104
    if idx != -1:
 
105
        name = name[idx+1 : ]
 
106
    idx = name.rfind('\\')
 
107
    if idx != -1:
 
108
        name = name[idx+1 : ]
 
109
 
 
110
    # make it not a hidden file
 
111
    name = name.lstrip('.')
 
112
 
 
113
    # remove any wierd characters; we don't escape them but rather
 
114
    # just pull them out
 
115
    name = re.sub(r'[^\w.]', '', name)
 
116
 
 
117
    s = hexlify(rand_bytes(8))
 
118
    return '-'.join((name, compact_date(time()), s))
 
119
 
 
120
 
 
121
def gen_root_id():
 
122
    """Return a new tree-root file id."""
 
123
    return gen_file_id('TREE_ROOT')
 
124
 
 
125
 
 
126
class TreeEntry(object):
 
127
    """An entry that implements the minium interface used by commands.
 
128
 
 
129
    This needs further inspection, it may be better to have 
 
130
    InventoryEntries without ids - though that seems wrong. For now,
 
131
    this is a parallel hierarchy to InventoryEntry, and needs to become
 
132
    one of several things: decorates to that hierarchy, children of, or
 
133
    parents of it.
 
134
    Another note is that these objects are currently only used when there is
 
135
    no InventoryEntry available - i.e. for unversioned objects.
 
136
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
 
137
    """
 
138
 
 
139
    def __eq__(self, other):
 
140
        # yes, this us ugly, TODO: best practice __eq__ style.
 
141
        return (isinstance(other, TreeEntry)
 
142
                and other.__class__ == self.__class__)
 
143
 
 
144
    def kind_character(self):
 
145
        return "???"
 
146
 
 
147
 
 
148
class TreeDirectory(TreeEntry):
 
149
    """See TreeEntry. This is a directory in a working tree."""
 
150
 
 
151
    def __eq__(self, other):
 
152
        return (isinstance(other, TreeDirectory)
 
153
                and other.__class__ == self.__class__)
 
154
 
 
155
    def kind_character(self):
 
156
        return "/"
 
157
 
 
158
 
 
159
class TreeFile(TreeEntry):
 
160
    """See TreeEntry. This is a regular file in a working tree."""
 
161
 
 
162
    def __eq__(self, other):
 
163
        return (isinstance(other, TreeFile)
 
164
                and other.__class__ == self.__class__)
 
165
 
 
166
    def kind_character(self):
 
167
        return ''
 
168
 
 
169
 
 
170
class TreeLink(TreeEntry):
 
171
    """See TreeEntry. This is a symlink in a working tree."""
 
172
 
 
173
    def __eq__(self, other):
 
174
        return (isinstance(other, TreeLink)
 
175
                and other.__class__ == self.__class__)
 
176
 
 
177
    def kind_character(self):
 
178
        return ''
 
179
 
 
180
 
 
181
class WorkingTree(bzrlib.tree.Tree):
 
182
    """Working copy tree.
 
183
 
 
184
    The inventory is held in the `Branch` working-inventory, and the
 
185
    files are in a directory on disk.
 
186
 
 
187
    It is possible for a `WorkingTree` to have a filename which is
 
188
    not listed in the Inventory and vice versa.
 
189
    """
 
190
 
 
191
    def __init__(self, basedir='.', branch=None, _inventory=None, _control_files=None):
 
192
        """Construct a WorkingTree for basedir.
 
193
 
 
194
        If the branch is not supplied, it is opened automatically.
 
195
        If the branch is supplied, it must be the branch for this basedir.
 
196
        (branch.base is not cross checked, because for remote branches that
 
197
        would be meaningless).
 
198
        """
 
199
        from bzrlib.hashcache import HashCache
 
200
        from bzrlib.trace import note, mutter
 
201
        assert isinstance(basedir, basestring), \
 
202
            "base directory %r is not a string" % basedir
 
203
        basedir = safe_unicode(basedir)
 
204
        mutter("openeing working tree %r", basedir)
 
205
        if branch is None:
 
206
            branch = Branch.open(basedir)
 
207
        assert isinstance(branch, Branch), \
 
208
            "branch %r is not a Branch" % branch
 
209
        self.branch = branch
 
210
        self.basedir = realpath(basedir)
 
211
        # if branch is at our basedir and is a format 6 or less
 
212
        if (isinstance(self.branch._branch_format,
 
213
                       (BzrBranchFormat4, BzrBranchFormat5, BzrBranchFormat6))
 
214
            # might be able to share control object
 
215
            and self.branch.base.split('/')[-2] == self.basedir.split('/')[-1]):
 
216
            self._control_files = self.branch.control_files
 
217
        elif _control_files is not None:
 
218
            assert False, "not done yet"
 
219
#            self._control_files = _control_files
 
220
        else:
 
221
            self._control_files = LockableFiles(
 
222
                get_transport(self.basedir).clone(bzrlib.BZRDIR), 'branch-lock')
 
223
 
 
224
        # update the whole cache up front and write to disk if anything changed;
 
225
        # in the future we might want to do this more selectively
 
226
        # two possible ways offer themselves : in self._unlock, write the cache
 
227
        # if needed, or, when the cache sees a change, append it to the hash
 
228
        # cache file, and have the parser take the most recent entry for a
 
229
        # given path only.
 
230
        hc = self._hashcache = HashCache(basedir)
 
231
        hc.read()
 
232
        hc.scan()
 
233
 
 
234
        if hc.needs_write:
 
235
            mutter("write hc")
 
236
            hc.write()
 
237
 
 
238
        if _inventory is None:
 
239
            self._set_inventory(self.read_working_inventory())
 
240
        else:
 
241
            self._set_inventory(_inventory)
 
242
 
 
243
    def _set_inventory(self, inv):
 
244
        self._inventory = inv
 
245
        self.path2id = self._inventory.path2id
 
246
 
 
247
    @staticmethod
 
248
    def open_containing(path=None):
 
249
        """Open an existing working tree which has its root about path.
 
250
        
 
251
        This probes for a working tree at path and searches upwards from there.
 
252
 
 
253
        Basically we keep looking up until we find the control directory or
 
254
        run into /.  If there isn't one, raises NotBranchError.
 
255
        TODO: give this a new exception.
 
256
        If there is one, it is returned, along with the unused portion of path.
 
257
        """
 
258
        if path is None:
 
259
            path = getcwd()
 
260
        else:
 
261
            # sanity check.
 
262
            if path.find('://') != -1:
 
263
                raise NotBranchError(path=path)
 
264
        path = abspath(path)
 
265
        orig_path = path[:]
 
266
        tail = u''
 
267
        while True:
 
268
            try:
 
269
                return WorkingTree(path), tail
 
270
            except NotBranchError:
 
271
                pass
 
272
            if tail:
 
273
                tail = pathjoin(os.path.basename(path), tail)
 
274
            else:
 
275
                tail = os.path.basename(path)
 
276
            lastpath = path
 
277
            path = os.path.dirname(path)
 
278
            if lastpath == path:
 
279
                # reached the root, whatever that may be
 
280
                raise NotBranchError(path=orig_path)
 
281
 
 
282
    def __iter__(self):
 
283
        """Iterate through file_ids for this tree.
 
284
 
 
285
        file_ids are in a WorkingTree if they are in the working inventory
 
286
        and the working file exists.
 
287
        """
 
288
        inv = self._inventory
 
289
        for path, ie in inv.iter_entries():
 
290
            if bzrlib.osutils.lexists(self.abspath(path)):
 
291
                yield ie.file_id
 
292
 
 
293
    def __repr__(self):
 
294
        return "<%s of %s>" % (self.__class__.__name__,
 
295
                               getattr(self, 'basedir', None))
 
296
 
 
297
    def abspath(self, filename):
 
298
        return pathjoin(self.basedir, filename)
 
299
 
 
300
    @staticmethod
 
301
    def create(branch, directory):
 
302
        """Create a workingtree for branch at directory.
 
303
 
 
304
        If existing_directory already exists it must have a .bzr directory.
 
305
        If it does not exist, it will be created.
 
306
 
 
307
        This returns a new WorkingTree object for the new checkout.
 
308
 
 
309
        TODO FIXME RBC 20060124 when we have checkout formats in place this
 
310
        should accept an optional revisionid to checkout [and reject this if
 
311
        checking out into the same dir as a pre-checkout-aware branch format.]
 
312
 
 
313
        XXX: When BzrDir is present, these should be created through that 
 
314
        interface instead.
 
315
        """
 
316
        try:
 
317
            os.mkdir(directory)
 
318
        except OSError, e:
 
319
            if e.errno != errno.EEXIST:
 
320
                raise
 
321
        try:
 
322
            os.mkdir(pathjoin(directory, '.bzr'))
 
323
        except OSError, e:
 
324
            if e.errno != errno.EEXIST:
 
325
                raise
 
326
        inv = branch.repository.revision_tree(branch.last_revision()).inventory
 
327
        wt = WorkingTree(directory, branch, inv)
 
328
        wt._write_inventory(inv)
 
329
        if branch.last_revision() is not None:
 
330
            wt.set_last_revision(branch.last_revision())
 
331
        wt.set_pending_merges([])
 
332
        wt.revert([])
 
333
        return wt
 
334
 
 
335
    @staticmethod
 
336
    def create_standalone(directory):
 
337
        """Create a checkout and a branch at directory.
 
338
 
 
339
        Directory must exist and be empty.
 
340
 
 
341
        XXX: When BzrDir is present, these should be created through that 
 
342
        interface instead.
 
343
        """
 
344
        directory = safe_unicode(directory)
 
345
        b = Branch.create(directory)
 
346
        return WorkingTree.create(b, directory)
 
347
 
 
348
    def relpath(self, abs):
 
349
        """Return the local path portion from a given absolute path."""
 
350
        return relpath(self.basedir, abs)
 
351
 
 
352
    def has_filename(self, filename):
 
353
        return bzrlib.osutils.lexists(self.abspath(filename))
 
354
 
 
355
    def get_file(self, file_id):
 
356
        return self.get_file_byname(self.id2path(file_id))
 
357
 
 
358
    def get_file_byname(self, filename):
 
359
        return file(self.abspath(filename), 'rb')
 
360
 
 
361
    def get_root_id(self):
 
362
        """Return the id of this trees root"""
 
363
        inv = self.read_working_inventory()
 
364
        return inv.root.file_id
 
365
        
 
366
    def _get_store_filename(self, file_id):
 
367
        ## XXX: badly named; this is not in the store at all
 
368
        return self.abspath(self.id2path(file_id))
 
369
 
 
370
    @needs_write_lock
 
371
    def commit(self, *args, **kwargs):
 
372
        from bzrlib.commit import Commit
 
373
        # args for wt.commit start at message from the Commit.commit method,
 
374
        # but with branch a kwarg now, passing in args as is results in the
 
375
        #message being used for the branch
 
376
        args = (DEPRECATED_PARAMETER, ) + args
 
377
        Commit().commit(working_tree=self, *args, **kwargs)
 
378
        self._set_inventory(self.read_working_inventory())
 
379
 
 
380
    def id2abspath(self, file_id):
 
381
        return self.abspath(self.id2path(file_id))
 
382
 
 
383
    def has_id(self, file_id):
 
384
        # files that have been deleted are excluded
 
385
        inv = self._inventory
 
386
        if not inv.has_id(file_id):
 
387
            return False
 
388
        path = inv.id2path(file_id)
 
389
        return bzrlib.osutils.lexists(self.abspath(path))
 
390
 
 
391
    def has_or_had_id(self, file_id):
 
392
        if file_id == self.inventory.root.file_id:
 
393
            return True
 
394
        return self.inventory.has_id(file_id)
 
395
 
 
396
    __contains__ = has_id
 
397
 
 
398
    def get_file_size(self, file_id):
 
399
        return os.path.getsize(self.id2abspath(file_id))
 
400
 
 
401
    @needs_read_lock
 
402
    def get_file_sha1(self, file_id):
 
403
        path = self._inventory.id2path(file_id)
 
404
        return self._hashcache.get_sha1(path)
 
405
 
 
406
    def is_executable(self, file_id):
 
407
        if not supports_executable():
 
408
            return self._inventory[file_id].executable
 
409
        else:
 
410
            path = self._inventory.id2path(file_id)
 
411
            mode = os.lstat(self.abspath(path)).st_mode
 
412
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
 
413
 
 
414
    @needs_write_lock
 
415
    def add(self, files, ids=None):
 
416
        """Make files versioned.
 
417
 
 
418
        Note that the command line normally calls smart_add instead,
 
419
        which can automatically recurse.
 
420
 
 
421
        This adds the files to the inventory, so that they will be
 
422
        recorded by the next commit.
 
423
 
 
424
        files
 
425
            List of paths to add, relative to the base of the tree.
 
426
 
 
427
        ids
 
428
            If set, use these instead of automatically generated ids.
 
429
            Must be the same length as the list of files, but may
 
430
            contain None for ids that are to be autogenerated.
 
431
 
 
432
        TODO: Perhaps have an option to add the ids even if the files do
 
433
              not (yet) exist.
 
434
 
 
435
        TODO: Perhaps callback with the ids and paths as they're added.
 
436
        """
 
437
        # TODO: Re-adding a file that is removed in the working copy
 
438
        # should probably put it back with the previous ID.
 
439
        if isinstance(files, basestring):
 
440
            assert(ids is None or isinstance(ids, basestring))
 
441
            files = [files]
 
442
            if ids is not None:
 
443
                ids = [ids]
 
444
 
 
445
        if ids is None:
 
446
            ids = [None] * len(files)
 
447
        else:
 
448
            assert(len(ids) == len(files))
 
449
 
 
450
        inv = self.read_working_inventory()
 
451
        for f,file_id in zip(files, ids):
 
452
            if is_control_file(f):
 
453
                raise BzrError("cannot add control file %s" % quotefn(f))
 
454
 
 
455
            fp = splitpath(f)
 
456
 
 
457
            if len(fp) == 0:
 
458
                raise BzrError("cannot add top-level %r" % f)
 
459
 
 
460
            fullpath = normpath(self.abspath(f))
 
461
 
 
462
            try:
 
463
                kind = file_kind(fullpath)
 
464
            except OSError:
 
465
                # maybe something better?
 
466
                raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
 
467
 
 
468
            if not InventoryEntry.versionable_kind(kind):
 
469
                raise BzrError('cannot add: not a versionable file ('
 
470
                               'i.e. regular file, symlink or directory): %s' % quotefn(f))
 
471
 
 
472
            if file_id is None:
 
473
                file_id = gen_file_id(f)
 
474
            inv.add_path(f, kind=kind, file_id=file_id)
 
475
 
 
476
            mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
 
477
        self._write_inventory(inv)
 
478
 
 
479
    @needs_write_lock
 
480
    def add_pending_merge(self, *revision_ids):
 
481
        # TODO: Perhaps should check at this point that the
 
482
        # history of the revision is actually present?
 
483
        p = self.pending_merges()
 
484
        updated = False
 
485
        for rev_id in revision_ids:
 
486
            if rev_id in p:
 
487
                continue
 
488
            p.append(rev_id)
 
489
            updated = True
 
490
        if updated:
 
491
            self.set_pending_merges(p)
 
492
 
 
493
    @needs_read_lock
 
494
    def pending_merges(self):
 
495
        """Return a list of pending merges.
 
496
 
 
497
        These are revisions that have been merged into the working
 
498
        directory but not yet committed.
 
499
        """
 
500
        try:
 
501
            merges_file = self._control_files.get_utf8('pending-merges')
 
502
        except OSError, e:
 
503
            if e.errno != errno.ENOENT:
 
504
                raise
 
505
            return []
 
506
        p = []
 
507
        for l in merges_file.readlines():
 
508
            p.append(l.rstrip('\n'))
 
509
        return p
 
510
 
 
511
    @needs_write_lock
 
512
    def set_pending_merges(self, rev_list):
 
513
        self._control_files.put_utf8('pending-merges', '\n'.join(rev_list))
 
514
 
 
515
    def get_symlink_target(self, file_id):
 
516
        return os.readlink(self.id2abspath(file_id))
 
517
 
 
518
    def file_class(self, filename):
 
519
        if self.path2id(filename):
 
520
            return 'V'
 
521
        elif self.is_ignored(filename):
 
522
            return 'I'
 
523
        else:
 
524
            return '?'
 
525
 
 
526
 
 
527
    def list_files(self):
 
528
        """Recursively list all files as (path, class, kind, id).
 
529
 
 
530
        Lists, but does not descend into unversioned directories.
 
531
 
 
532
        This does not include files that have been deleted in this
 
533
        tree.
 
534
 
 
535
        Skips the control directory.
 
536
        """
 
537
        inv = self._inventory
 
538
 
 
539
        def descend(from_dir_relpath, from_dir_id, dp):
 
540
            ls = os.listdir(dp)
 
541
            ls.sort()
 
542
            for f in ls:
 
543
                ## TODO: If we find a subdirectory with its own .bzr
 
544
                ## directory, then that is a separate tree and we
 
545
                ## should exclude it.
 
546
                if bzrlib.BZRDIR == f:
 
547
                    continue
 
548
 
 
549
                # path within tree
 
550
                fp = appendpath(from_dir_relpath, f)
 
551
 
 
552
                # absolute path
 
553
                fap = appendpath(dp, f)
 
554
                
 
555
                f_ie = inv.get_child(from_dir_id, f)
 
556
                if f_ie:
 
557
                    c = 'V'
 
558
                elif self.is_ignored(fp):
 
559
                    c = 'I'
 
560
                else:
 
561
                    c = '?'
 
562
 
 
563
                fk = file_kind(fap)
 
564
 
 
565
                if f_ie:
 
566
                    if f_ie.kind != fk:
 
567
                        raise BzrCheckError("file %r entered as kind %r id %r, "
 
568
                                            "now of kind %r"
 
569
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
 
570
 
 
571
                # make a last minute entry
 
572
                if f_ie:
 
573
                    entry = f_ie
 
574
                else:
 
575
                    if fk == 'directory':
 
576
                        entry = TreeDirectory()
 
577
                    elif fk == 'file':
 
578
                        entry = TreeFile()
 
579
                    elif fk == 'symlink':
 
580
                        entry = TreeLink()
 
581
                    else:
 
582
                        entry = TreeEntry()
 
583
                
 
584
                yield fp, c, fk, (f_ie and f_ie.file_id), entry
 
585
 
 
586
                if fk != 'directory':
 
587
                    continue
 
588
 
 
589
                if c != 'V':
 
590
                    # don't descend unversioned directories
 
591
                    continue
 
592
                
 
593
                for ff in descend(fp, f_ie.file_id, fap):
 
594
                    yield ff
 
595
 
 
596
        for f in descend(u'', inv.root.file_id, self.basedir):
 
597
            yield f
 
598
 
 
599
    @needs_write_lock
 
600
    def move(self, from_paths, to_name):
 
601
        """Rename files.
 
602
 
 
603
        to_name must exist in the inventory.
 
604
 
 
605
        If to_name exists and is a directory, the files are moved into
 
606
        it, keeping their old names.  
 
607
 
 
608
        Note that to_name is only the last component of the new name;
 
609
        this doesn't change the directory.
 
610
 
 
611
        This returns a list of (from_path, to_path) pairs for each
 
612
        entry that is moved.
 
613
        """
 
614
        result = []
 
615
        ## TODO: Option to move IDs only
 
616
        assert not isinstance(from_paths, basestring)
 
617
        inv = self.inventory
 
618
        to_abs = self.abspath(to_name)
 
619
        if not isdir(to_abs):
 
620
            raise BzrError("destination %r is not a directory" % to_abs)
 
621
        if not self.has_filename(to_name):
 
622
            raise BzrError("destination %r not in working directory" % to_abs)
 
623
        to_dir_id = inv.path2id(to_name)
 
624
        if to_dir_id == None and to_name != '':
 
625
            raise BzrError("destination %r is not a versioned directory" % to_name)
 
626
        to_dir_ie = inv[to_dir_id]
 
627
        if to_dir_ie.kind not in ('directory', 'root_directory'):
 
628
            raise BzrError("destination %r is not a directory" % to_abs)
 
629
 
 
630
        to_idpath = inv.get_idpath(to_dir_id)
 
631
 
 
632
        for f in from_paths:
 
633
            if not self.has_filename(f):
 
634
                raise BzrError("%r does not exist in working tree" % f)
 
635
            f_id = inv.path2id(f)
 
636
            if f_id == None:
 
637
                raise BzrError("%r is not versioned" % f)
 
638
            name_tail = splitpath(f)[-1]
 
639
            dest_path = appendpath(to_name, name_tail)
 
640
            if self.has_filename(dest_path):
 
641
                raise BzrError("destination %r already exists" % dest_path)
 
642
            if f_id in to_idpath:
 
643
                raise BzrError("can't move %r to a subdirectory of itself" % f)
 
644
 
 
645
        # OK, so there's a race here, it's possible that someone will
 
646
        # create a file in this interval and then the rename might be
 
647
        # left half-done.  But we should have caught most problems.
 
648
        orig_inv = deepcopy(self.inventory)
 
649
        try:
 
650
            for f in from_paths:
 
651
                name_tail = splitpath(f)[-1]
 
652
                dest_path = appendpath(to_name, name_tail)
 
653
                result.append((f, dest_path))
 
654
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
 
655
                try:
 
656
                    rename(self.abspath(f), self.abspath(dest_path))
 
657
                except OSError, e:
 
658
                    raise BzrError("failed to rename %r to %r: %s" %
 
659
                                   (f, dest_path, e[1]),
 
660
                            ["rename rolled back"])
 
661
        except:
 
662
            # restore the inventory on error
 
663
            self._set_inventory(orig_inv)
 
664
            raise
 
665
        self._write_inventory(inv)
 
666
        return result
 
667
 
 
668
    @needs_write_lock
 
669
    def rename_one(self, from_rel, to_rel):
 
670
        """Rename one file.
 
671
 
 
672
        This can change the directory or the filename or both.
 
673
        """
 
674
        inv = self.inventory
 
675
        if not self.has_filename(from_rel):
 
676
            raise BzrError("can't rename: old working file %r does not exist" % from_rel)
 
677
        if self.has_filename(to_rel):
 
678
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
 
679
 
 
680
        file_id = inv.path2id(from_rel)
 
681
        if file_id == None:
 
682
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
 
683
 
 
684
        entry = inv[file_id]
 
685
        from_parent = entry.parent_id
 
686
        from_name = entry.name
 
687
        
 
688
        if inv.path2id(to_rel):
 
689
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
 
690
 
 
691
        to_dir, to_tail = os.path.split(to_rel)
 
692
        to_dir_id = inv.path2id(to_dir)
 
693
        if to_dir_id == None and to_dir != '':
 
694
            raise BzrError("can't determine destination directory id for %r" % to_dir)
 
695
 
 
696
        mutter("rename_one:")
 
697
        mutter("  file_id    {%s}" % file_id)
 
698
        mutter("  from_rel   %r" % from_rel)
 
699
        mutter("  to_rel     %r" % to_rel)
 
700
        mutter("  to_dir     %r" % to_dir)
 
701
        mutter("  to_dir_id  {%s}" % to_dir_id)
 
702
 
 
703
        inv.rename(file_id, to_dir_id, to_tail)
 
704
 
 
705
        from_abs = self.abspath(from_rel)
 
706
        to_abs = self.abspath(to_rel)
 
707
        try:
 
708
            rename(from_abs, to_abs)
 
709
        except OSError, e:
 
710
            inv.rename(file_id, from_parent, from_name)
 
711
            raise BzrError("failed to rename %r to %r: %s"
 
712
                    % (from_abs, to_abs, e[1]),
 
713
                    ["rename rolled back"])
 
714
        self._write_inventory(inv)
 
715
 
 
716
    @needs_read_lock
 
717
    def unknowns(self):
 
718
        """Return all unknown files.
 
719
 
 
720
        These are files in the working directory that are not versioned or
 
721
        control files or ignored.
 
722
        
 
723
        >>> from bzrlib.branch import ScratchBranch
 
724
        >>> b = ScratchBranch(files=['foo', 'foo~'])
 
725
        >>> tree = WorkingTree(b.base, b)
 
726
        >>> map(str, tree.unknowns())
 
727
        ['foo']
 
728
        >>> tree.add('foo')
 
729
        >>> list(b.unknowns())
 
730
        []
 
731
        >>> tree.remove('foo')
 
732
        >>> list(b.unknowns())
 
733
        [u'foo']
 
734
        """
 
735
        for subp in self.extras():
 
736
            if not self.is_ignored(subp):
 
737
                yield subp
 
738
 
 
739
    def iter_conflicts(self):
 
740
        conflicted = set()
 
741
        for path in (s[0] for s in self.list_files()):
 
742
            stem = get_conflicted_stem(path)
 
743
            if stem is None:
 
744
                continue
 
745
            if stem not in conflicted:
 
746
                conflicted.add(stem)
 
747
                yield stem
 
748
 
 
749
    @needs_write_lock
 
750
    def pull(self, source, overwrite=False, stop_revision=None):
 
751
        from bzrlib.merge import merge_inner
 
752
        source.lock_read()
 
753
        try:
 
754
            old_revision_history = self.branch.revision_history()
 
755
            count = self.branch.pull(source, overwrite,stop_revision)
 
756
            new_revision_history = self.branch.revision_history()
 
757
            if new_revision_history != old_revision_history:
 
758
                if len(old_revision_history):
 
759
                    other_revision = old_revision_history[-1]
 
760
                else:
 
761
                    other_revision = None
 
762
                repository = self.branch.repository
 
763
                merge_inner(self.branch,
 
764
                            self.branch.basis_tree(), 
 
765
                            repository.revision_tree(other_revision),
 
766
                            this_tree=self)
 
767
                self.set_last_revision(self.branch.last_revision())
 
768
            return count
 
769
        finally:
 
770
            source.unlock()
 
771
 
 
772
    def extras(self):
 
773
        """Yield all unknown files in this WorkingTree.
 
774
 
 
775
        If there are any unknown directories then only the directory is
 
776
        returned, not all its children.  But if there are unknown files
 
777
        under a versioned subdirectory, they are returned.
 
778
 
 
779
        Currently returned depth-first, sorted by name within directories.
 
780
        """
 
781
        ## TODO: Work from given directory downwards
 
782
        for path, dir_entry in self.inventory.directories():
 
783
            mutter("search for unknowns in %r", path)
 
784
            dirabs = self.abspath(path)
 
785
            if not isdir(dirabs):
 
786
                # e.g. directory deleted
 
787
                continue
 
788
 
 
789
            fl = []
 
790
            for subf in os.listdir(dirabs):
 
791
                if (subf != '.bzr'
 
792
                    and (subf not in dir_entry.children)):
 
793
                    fl.append(subf)
 
794
            
 
795
            fl.sort()
 
796
            for subf in fl:
 
797
                subp = appendpath(path, subf)
 
798
                yield subp
 
799
 
 
800
 
 
801
    def ignored_files(self):
 
802
        """Yield list of PATH, IGNORE_PATTERN"""
 
803
        for subp in self.extras():
 
804
            pat = self.is_ignored(subp)
 
805
            if pat != None:
 
806
                yield subp, pat
 
807
 
 
808
 
 
809
    def get_ignore_list(self):
 
810
        """Return list of ignore patterns.
 
811
 
 
812
        Cached in the Tree object after the first call.
 
813
        """
 
814
        if hasattr(self, '_ignorelist'):
 
815
            return self._ignorelist
 
816
 
 
817
        l = bzrlib.DEFAULT_IGNORE[:]
 
818
        if self.has_filename(bzrlib.IGNORE_FILENAME):
 
819
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
 
820
            l.extend([line.rstrip("\n\r") for line in f.readlines()])
 
821
        self._ignorelist = l
 
822
        return l
 
823
 
 
824
 
 
825
    def is_ignored(self, filename):
 
826
        r"""Check whether the filename matches an ignore pattern.
 
827
 
 
828
        Patterns containing '/' or '\' need to match the whole path;
 
829
        others match against only the last component.
 
830
 
 
831
        If the file is ignored, returns the pattern which caused it to
 
832
        be ignored, otherwise None.  So this can simply be used as a
 
833
        boolean if desired."""
 
834
 
 
835
        # TODO: Use '**' to match directories, and other extended
 
836
        # globbing stuff from cvs/rsync.
 
837
 
 
838
        # XXX: fnmatch is actually not quite what we want: it's only
 
839
        # approximately the same as real Unix fnmatch, and doesn't
 
840
        # treat dotfiles correctly and allows * to match /.
 
841
        # Eventually it should be replaced with something more
 
842
        # accurate.
 
843
        
 
844
        for pat in self.get_ignore_list():
 
845
            if '/' in pat or '\\' in pat:
 
846
                
 
847
                # as a special case, you can put ./ at the start of a
 
848
                # pattern; this is good to match in the top-level
 
849
                # only;
 
850
                
 
851
                if (pat[:2] == './') or (pat[:2] == '.\\'):
 
852
                    newpat = pat[2:]
 
853
                else:
 
854
                    newpat = pat
 
855
                if fnmatch.fnmatchcase(filename, newpat):
 
856
                    return pat
 
857
            else:
 
858
                if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
 
859
                    return pat
 
860
        else:
 
861
            return None
 
862
 
 
863
    def kind(self, file_id):
 
864
        return file_kind(self.id2abspath(file_id))
 
865
 
 
866
    def lock_read(self):
 
867
        """See Branch.lock_read, and WorkingTree.unlock."""
 
868
        return self.branch.lock_read()
 
869
 
 
870
    def lock_write(self):
 
871
        """See Branch.lock_write, and WorkingTree.unlock."""
 
872
        return self.branch.lock_write()
 
873
 
 
874
    def _basis_inventory_name(self, revision_id):
 
875
        return 'basis-inventory.%s' % revision_id
 
876
 
 
877
    def set_last_revision(self, new_revision, old_revision=None):
 
878
        if old_revision is not None:
 
879
            try:
 
880
                path = self._basis_inventory_name(old_revision)
 
881
                path = self.branch.control_files._escape(path)
 
882
                self.branch.control_files._transport.delete(path)
 
883
            except NoSuchFile:
 
884
                pass
 
885
        try:
 
886
            xml = self.branch.repository.get_inventory_xml(new_revision)
 
887
            path = self._basis_inventory_name(new_revision)
 
888
            self.branch.control_files.put_utf8(path, xml)
 
889
        except WeaveRevisionNotPresent:
 
890
            pass
 
891
 
 
892
    def read_basis_inventory(self, revision_id):
 
893
        """Read the cached basis inventory."""
 
894
        path = self._basis_inventory_name(revision_id)
 
895
        return self.branch.control_files.get_utf8(path).read()
 
896
        
 
897
    @needs_read_lock
 
898
    def read_working_inventory(self):
 
899
        """Read the working inventory."""
 
900
        # ElementTree does its own conversion from UTF-8, so open in
 
901
        # binary.
 
902
        return bzrlib.xml5.serializer_v5.read_inventory(
 
903
            self._control_files.get('inventory'))
 
904
 
 
905
    @needs_write_lock
 
906
    def remove(self, files, verbose=False):
 
907
        """Remove nominated files from the working inventory..
 
908
 
 
909
        This does not remove their text.  This does not run on XXX on what? RBC
 
910
 
 
911
        TODO: Refuse to remove modified files unless --force is given?
 
912
 
 
913
        TODO: Do something useful with directories.
 
914
 
 
915
        TODO: Should this remove the text or not?  Tough call; not
 
916
        removing may be useful and the user can just use use rm, and
 
917
        is the opposite of add.  Removing it is consistent with most
 
918
        other tools.  Maybe an option.
 
919
        """
 
920
        ## TODO: Normalize names
 
921
        ## TODO: Remove nested loops; better scalability
 
922
        if isinstance(files, basestring):
 
923
            files = [files]
 
924
 
 
925
        inv = self.inventory
 
926
 
 
927
        # do this before any modifications
 
928
        for f in files:
 
929
            fid = inv.path2id(f)
 
930
            if not fid:
 
931
                # TODO: Perhaps make this just a warning, and continue?
 
932
                # This tends to happen when 
 
933
                raise NotVersionedError(path=f)
 
934
            mutter("remove inventory entry %s {%s}", quotefn(f), fid)
 
935
            if verbose:
 
936
                # having remove it, it must be either ignored or unknown
 
937
                if self.is_ignored(f):
 
938
                    new_status = 'I'
 
939
                else:
 
940
                    new_status = '?'
 
941
                show_status(new_status, inv[fid].kind, quotefn(f))
 
942
            del inv[fid]
 
943
 
 
944
        self._write_inventory(inv)
 
945
 
 
946
    @needs_write_lock
 
947
    def revert(self, filenames, old_tree=None, backups=True):
 
948
        from transform import revert
 
949
        if old_tree is None:
 
950
            old_tree = self.branch.basis_tree()
 
951
        revert(self, old_tree, filenames, backups)
 
952
        if not len(filenames):
 
953
            self.set_pending_merges([])
 
954
 
 
955
    @needs_write_lock
 
956
    def set_inventory(self, new_inventory_list):
 
957
        from bzrlib.inventory import (Inventory,
 
958
                                      InventoryDirectory,
 
959
                                      InventoryEntry,
 
960
                                      InventoryFile,
 
961
                                      InventoryLink)
 
962
        inv = Inventory(self.get_root_id())
 
963
        for path, file_id, parent, kind in new_inventory_list:
 
964
            name = os.path.basename(path)
 
965
            if name == "":
 
966
                continue
 
967
            # fixme, there should be a factory function inv,add_?? 
 
968
            if kind == 'directory':
 
969
                inv.add(InventoryDirectory(file_id, name, parent))
 
970
            elif kind == 'file':
 
971
                inv.add(InventoryFile(file_id, name, parent))
 
972
            elif kind == 'symlink':
 
973
                inv.add(InventoryLink(file_id, name, parent))
 
974
            else:
 
975
                raise BzrError("unknown kind %r" % kind)
 
976
        self._write_inventory(inv)
 
977
 
 
978
    @needs_write_lock
 
979
    def set_root_id(self, file_id):
 
980
        """Set the root id for this tree."""
 
981
        inv = self.read_working_inventory()
 
982
        orig_root_id = inv.root.file_id
 
983
        del inv._byid[inv.root.file_id]
 
984
        inv.root.file_id = file_id
 
985
        inv._byid[inv.root.file_id] = inv.root
 
986
        for fid in inv:
 
987
            entry = inv[fid]
 
988
            if entry.parent_id in (None, orig_root_id):
 
989
                entry.parent_id = inv.root.file_id
 
990
        self._write_inventory(inv)
 
991
 
 
992
    def unlock(self):
 
993
        """See Branch.unlock.
 
994
        
 
995
        WorkingTree locking just uses the Branch locking facilities.
 
996
        This is current because all working trees have an embedded branch
 
997
        within them. IF in the future, we were to make branch data shareable
 
998
        between multiple working trees, i.e. via shared storage, then we 
 
999
        would probably want to lock both the local tree, and the branch.
 
1000
        """
 
1001
        # FIXME: We want to write out the hashcache only when the last lock on
 
1002
        # this working copy is released.  Peeking at the lock count is a bit
 
1003
        # of a nasty hack; probably it's better to have a transaction object,
 
1004
        # which can do some finalization when it's either successfully or
 
1005
        # unsuccessfully completed.  (Denys's original patch did that.)
 
1006
        if self._hashcache.needs_write and self.branch.control_files._lock_count==1:
 
1007
            self._hashcache.write()
 
1008
        return self.branch.unlock()
 
1009
 
 
1010
    @needs_write_lock
 
1011
    def _write_inventory(self, inv):
 
1012
        """Write inventory as the current inventory."""
 
1013
        sio = StringIO()
 
1014
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
 
1015
        sio.seek(0)
 
1016
        self._control_files.put('inventory', sio)
 
1017
        self._set_inventory(inv)
 
1018
        mutter('wrote working inventory')
 
1019
            
 
1020
 
 
1021
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
 
1022
def get_conflicted_stem(path):
 
1023
    for suffix in CONFLICT_SUFFIXES:
 
1024
        if path.endswith(suffix):
 
1025
            return path[:-len(suffix)]