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