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