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