/brz/remove-bazaar

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