~bzr-pqm/bzr/bzr.dev

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