/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/workingtree.py

  • Committer: John Arbash Meinel
  • Date: 2005-12-01 19:57:43 UTC
  • mto: (1185.50.19 bzr-jam-integration)
  • mto: This revision was merged to the branch mainline in revision 1532.
  • Revision ID: john@arbash-meinel.com-20051201195743-57aefc694d237938
Reintroduced ensure_config_dir_exists() for sftp

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