/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
453 by Martin Pool
- Split WorkingTree into its own file
45
import os
1398 by Robert Collins
integrate in Gustavos x-bit patch
46
import stat
1140 by Martin Pool
- lift out import statements within WorkingTree
47
import fnmatch
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
48
 
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
49
from bzrlib.branch import Branch, needs_read_lock, needs_write_lock, quotefn
453 by Martin Pool
- Split WorkingTree into its own file
50
import bzrlib.tree
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
51
from bzrlib.osutils import (appendpath,
52
                            file_kind,
53
                            isdir,
54
                            pumpfile,
55
                            splitpath,
56
                            relpath)
1185.12.60 by Aaron Bentley
Merge from mainline
57
from bzrlib.errors import BzrCheckError, DivergedBranches, NotVersionedError
1140 by Martin Pool
- lift out import statements within WorkingTree
58
from bzrlib.trace import mutter
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
59
import bzrlib.xml5
453 by Martin Pool
- Split WorkingTree into its own file
60
1465 by Robert Collins
Bugfix the new pull --clobber to not generate spurious conflicts.
61
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
62
class TreeEntry(object):
63
    """An entry that implements the minium interface used by commands.
64
65
    This needs further inspection, it may be better to have 
66
    InventoryEntries without ids - though that seems wrong. For now,
67
    this is a parallel hierarchy to InventoryEntry, and needs to become
68
    one of several things: decorates to that hierarchy, children of, or
69
    parents of it.
1399.1.3 by Robert Collins
move change detection for text and metadata from delta to entry.detect_changes
70
    Another note is that these objects are currently only used when there is
71
    no InventoryEntry available - i.e. for unversioned objects.
72
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
73
    """
74
 
75
    def __eq__(self, other):
76
        # yes, this us ugly, TODO: best practice __eq__ style.
77
        return (isinstance(other, TreeEntry)
78
                and other.__class__ == self.__class__)
79
 
80
    def kind_character(self):
81
        return "???"
82
83
84
class TreeDirectory(TreeEntry):
85
    """See TreeEntry. This is a directory in a working tree."""
86
87
    def __eq__(self, other):
88
        return (isinstance(other, TreeDirectory)
89
                and other.__class__ == self.__class__)
90
91
    def kind_character(self):
92
        return "/"
93
94
95
class TreeFile(TreeEntry):
96
    """See TreeEntry. This is a regular file in a working tree."""
97
98
    def __eq__(self, other):
99
        return (isinstance(other, TreeFile)
100
                and other.__class__ == self.__class__)
101
102
    def kind_character(self):
103
        return ''
104
105
106
class TreeLink(TreeEntry):
107
    """See TreeEntry. This is a symlink in a working tree."""
108
109
    def __eq__(self, other):
110
        return (isinstance(other, TreeLink)
111
                and other.__class__ == self.__class__)
112
113
    def kind_character(self):
114
        return ''
115
116
453 by Martin Pool
- Split WorkingTree into its own file
117
class WorkingTree(bzrlib.tree.Tree):
118
    """Working copy tree.
119
120
    The inventory is held in the `Branch` working-inventory, and the
121
    files are in a directory on disk.
122
123
    It is possible for a `WorkingTree` to have a filename which is
124
    not listed in the Inventory and vice versa.
125
    """
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
126
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
127
    def __init__(self, basedir, branch=None):
128
        """Construct a WorkingTree for basedir.
129
130
        If the branch is not supplied, it is opened automatically.
131
        If the branch is supplied, it must be the branch for this basedir.
132
        (branch.base is not cross checked, because for remote branches that
133
        would be meaningless).
134
        """
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.
135
        from bzrlib.hashcache import HashCache
136
        from bzrlib.trace import note, mutter
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
137
        assert isinstance(basedir, basestring), \
138
            "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.
139
        if branch is None:
140
            branch = Branch.open(basedir)
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
141
        assert isinstance(branch, Branch), \
142
            "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.
143
        self.branch = branch
453 by Martin Pool
- Split WorkingTree into its own file
144
        self.basedir = basedir
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
145
        self._inventory = self.read_working_inventory()
146
        self.path2id = self._inventory.path2id
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.
147
148
        # update the whole cache up front and write to disk if anything changed;
149
        # in the future we might want to do this more selectively
1467 by Robert Collins
WorkingTree.__del__ has been removed.
150
        # two possible ways offer themselves : in self._unlock, write the cache
151
        # if needed, or, when the cache sees a change, append it to the hash
152
        # cache file, and have the parser take the most recent entry for a
153
        # 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.
154
        hc = self._hashcache = HashCache(basedir)
155
        hc.read()
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
156
        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.
157
158
        if hc.needs_write:
159
            mutter("write hc")
160
            hc.write()
453 by Martin Pool
- Split WorkingTree into its own file
161
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
162
    def __iter__(self):
163
        """Iterate through file_ids for this tree.
164
165
        file_ids are in a WorkingTree if they are in the working inventory
166
        and the working file exists.
167
        """
168
        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.
169
        for path, ie in inv.iter_entries():
1092.2.6 by Robert Collins
symlink support updated to work
170
            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.
171
                yield ie.file_id
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
172
173
453 by Martin Pool
- Split WorkingTree into its own file
174
    def __repr__(self):
175
        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
176
                               getattr(self, 'basedir', None))
453 by Martin Pool
- Split WorkingTree into its own file
177
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.
178
179
453 by Martin Pool
- Split WorkingTree into its own file
180
    def abspath(self, filename):
181
        return os.path.join(self.basedir, filename)
182
1457.1.3 by Robert Collins
make Branch.relpath delegate to the working tree.
183
    def relpath(self, abspath):
184
        """Return the local path portion from a given absolute path."""
185
        return relpath(self.basedir, abspath)
186
453 by Martin Pool
- Split WorkingTree into its own file
187
    def has_filename(self, filename):
1092.2.6 by Robert Collins
symlink support updated to work
188
        return bzrlib.osutils.lexists(self.abspath(filename))
453 by Martin Pool
- Split WorkingTree into its own file
189
190
    def get_file(self, file_id):
191
        return self.get_file_byname(self.id2path(file_id))
192
193
    def get_file_byname(self, filename):
194
        return file(self.abspath(filename), 'rb')
195
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
196
    def get_root_id(self):
197
        """Return the id of this trees root"""
198
        inv = self.read_working_inventory()
199
        return inv.root.file_id
200
        
453 by Martin Pool
- Split WorkingTree into its own file
201
    def _get_store_filename(self, file_id):
202
        ## XXX: badly named; this isn't in the store at all
203
        return self.abspath(self.id2path(file_id))
204
1248 by Martin Pool
- new weave based cleanup [broken]
205
206
    def id2abspath(self, file_id):
207
        return self.abspath(self.id2path(file_id))
208
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
209
                
1185.12.39 by abentley
Propogated has_or_had_id to Tree
210
    def has_id(self, file_id):
453 by Martin Pool
- Split WorkingTree into its own file
211
        # files that have been deleted are excluded
1185.12.39 by abentley
Propogated has_or_had_id to Tree
212
        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.
213
        if not inv.has_id(file_id):
453 by Martin Pool
- Split WorkingTree into its own file
214
            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.
215
        path = inv.id2path(file_id)
1092.2.6 by Robert Collins
symlink support updated to work
216
        return bzrlib.osutils.lexists(self.abspath(path))
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
217
1185.12.39 by abentley
Propogated has_or_had_id to Tree
218
    def has_or_had_id(self, file_id):
219
        if file_id == self.inventory.root.file_id:
220
            return True
221
        return self.inventory.has_id(file_id)
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
222
223
    __contains__ = has_id
224
    
225
453 by Martin Pool
- Split WorkingTree into its own file
226
    def get_file_size(self, file_id):
1248 by Martin Pool
- new weave based cleanup [broken]
227
        return os.path.getsize(self.id2abspath(file_id))
453 by Martin Pool
- Split WorkingTree into its own file
228
229
    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.
230
        path = self._inventory.id2path(file_id)
231
        return self._hashcache.get_sha1(path)
453 by Martin Pool
- Split WorkingTree into its own file
232
1398 by Robert Collins
integrate in Gustavos x-bit patch
233
234
    def is_executable(self, file_id):
235
        if os.name == "nt":
236
            return self._inventory[file_id].executable
237
        else:
238
            path = self._inventory.id2path(file_id)
239
            mode = os.lstat(self.abspath(path)).st_mode
240
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
241
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
242
    @needs_write_lock
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
243
    def add_pending_merge(self, *revision_ids):
244
        # TODO: Perhaps should check at this point that the
245
        # history of the revision is actually present?
246
        p = self.pending_merges()
247
        updated = False
248
        for rev_id in revision_ids:
249
            if rev_id in p:
250
                continue
251
            p.append(rev_id)
252
            updated = True
253
        if updated:
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
254
            self.set_pending_merges(p)
1457.1.15 by Robert Collins
Move add_pending_merge to WorkingTree.
255
1457.1.14 by Robert Collins
Move pending_merges() to WorkingTree.
256
    def pending_merges(self):
257
        """Return a list of pending merges.
258
259
        These are revisions that have been merged into the working
260
        directory but not yet committed.
261
        """
262
        cfn = self.branch._rel_controlfilename('pending-merges')
263
        if not self.branch._transport.has(cfn):
264
            return []
265
        p = []
266
        for l in self.branch.controlfile('pending-merges', 'r').readlines():
267
            p.append(l.rstrip('\n'))
268
        return p
269
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
270
    @needs_write_lock
271
    def set_pending_merges(self, rev_list):
272
        self.branch.put_controlfile('pending-merges', '\n'.join(rev_list))
273
1092.2.6 by Robert Collins
symlink support updated to work
274
    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
275
        return os.readlink(self.id2abspath(file_id))
453 by Martin Pool
- Split WorkingTree into its own file
276
277
    def file_class(self, filename):
278
        if self.path2id(filename):
279
            return 'V'
280
        elif self.is_ignored(filename):
281
            return 'I'
282
        else:
283
            return '?'
284
285
286
    def list_files(self):
287
        """Recursively list all files as (path, class, kind, id).
288
289
        Lists, but does not descend into unversioned directories.
290
291
        This does not include files that have been deleted in this
292
        tree.
293
294
        Skips the control directory.
295
        """
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.
296
        inv = self._inventory
453 by Martin Pool
- Split WorkingTree into its own file
297
298
        def descend(from_dir_relpath, from_dir_id, dp):
299
            ls = os.listdir(dp)
300
            ls.sort()
301
            for f in ls:
302
                ## TODO: If we find a subdirectory with its own .bzr
303
                ## directory, then that is a separate tree and we
304
                ## should exclude it.
305
                if bzrlib.BZRDIR == f:
306
                    continue
307
308
                # path within tree
309
                fp = appendpath(from_dir_relpath, f)
310
311
                # absolute path
312
                fap = appendpath(dp, f)
313
                
314
                f_ie = inv.get_child(from_dir_id, f)
315
                if f_ie:
316
                    c = 'V'
317
                elif self.is_ignored(fp):
318
                    c = 'I'
319
                else:
320
                    c = '?'
321
322
                fk = file_kind(fap)
323
324
                if f_ie:
325
                    if f_ie.kind != fk:
326
                        raise BzrCheckError("file %r entered as kind %r id %r, "
327
                                            "now of kind %r"
328
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
329
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
330
                # make a last minute entry
331
                if f_ie:
332
                    entry = f_ie
333
                else:
334
                    if fk == 'directory':
335
                        entry = TreeDirectory()
336
                    elif fk == 'file':
337
                        entry = TreeFile()
338
                    elif fk == 'symlink':
339
                        entry = TreeLink()
340
                    else:
341
                        entry = TreeEntry()
342
                
343
                yield fp, c, fk, (f_ie and f_ie.file_id), entry
453 by Martin Pool
- Split WorkingTree into its own file
344
345
                if fk != 'directory':
346
                    continue
347
348
                if c != 'V':
349
                    # don't descend unversioned directories
350
                    continue
351
                
352
                for ff in descend(fp, f_ie.file_id, fap):
353
                    yield ff
354
355
        for f in descend('', inv.root.file_id, self.basedir):
356
            yield f
357
            
358
359
360
    def unknowns(self):
361
        for subp in self.extras():
362
            if not self.is_ignored(subp):
363
                yield subp
364
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
365
    def iter_conflicts(self):
366
        conflicted = set()
367
        for path in (s[0] for s in self.list_files()):
368
            stem = get_conflicted_stem(path)
369
            if stem is None:
370
                continue
371
            if stem not in conflicted:
372
                conflicted.add(stem)
373
                yield stem
453 by Martin Pool
- Split WorkingTree into its own file
374
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
375
    @needs_write_lock
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
376
    def pull(self, source, overwrite=False):
1465 by Robert Collins
Bugfix the new pull --clobber to not generate spurious conflicts.
377
        from bzrlib.merge import merge_inner
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
378
        source.lock_read()
379
        try:
380
            old_revision_history = self.branch.revision_history()
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
381
            self.branch.pull(source, overwrite)
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
382
            new_revision_history = self.branch.revision_history()
383
            if new_revision_history != old_revision_history:
1465 by Robert Collins
Bugfix the new pull --clobber to not generate spurious conflicts.
384
                if len(old_revision_history):
385
                    other_revision = old_revision_history[-1]
386
                else:
387
                    other_revision = None
388
                merge_inner(self.branch,
389
                            self.branch.basis_tree(), 
390
                            self.branch.revision_tree(other_revision))
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
391
        finally:
392
            source.unlock()
393
453 by Martin Pool
- Split WorkingTree into its own file
394
    def extras(self):
395
        """Yield all unknown files in this WorkingTree.
396
397
        If there are any unknown directories then only the directory is
398
        returned, not all its children.  But if there are unknown files
399
        under a versioned subdirectory, they are returned.
400
401
        Currently returned depth-first, sorted by name within directories.
402
        """
403
        ## TODO: Work from given directory downwards
404
        for path, dir_entry in self.inventory.directories():
405
            mutter("search for unknowns in %r" % path)
406
            dirabs = self.abspath(path)
407
            if not isdir(dirabs):
408
                # e.g. directory deleted
409
                continue
410
411
            fl = []
412
            for subf in os.listdir(dirabs):
413
                if (subf != '.bzr'
414
                    and (subf not in dir_entry.children)):
415
                    fl.append(subf)
416
            
417
            fl.sort()
418
            for subf in fl:
419
                subp = appendpath(path, subf)
420
                yield subp
421
422
423
    def ignored_files(self):
424
        """Yield list of PATH, IGNORE_PATTERN"""
425
        for subp in self.extras():
426
            pat = self.is_ignored(subp)
427
            if pat != None:
428
                yield subp, pat
429
430
431
    def get_ignore_list(self):
432
        """Return list of ignore patterns.
433
434
        Cached in the Tree object after the first call.
435
        """
436
        if hasattr(self, '_ignorelist'):
437
            return self._ignorelist
438
439
        l = bzrlib.DEFAULT_IGNORE[:]
440
        if self.has_filename(bzrlib.IGNORE_FILENAME):
441
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
442
            l.extend([line.rstrip("\n\r") for line in f.readlines()])
443
        self._ignorelist = l
444
        return l
445
446
447
    def is_ignored(self, filename):
448
        r"""Check whether the filename matches an ignore pattern.
449
450
        Patterns containing '/' or '\' need to match the whole path;
451
        others match against only the last component.
452
453
        If the file is ignored, returns the pattern which caused it to
454
        be ignored, otherwise None.  So this can simply be used as a
455
        boolean if desired."""
456
457
        # TODO: Use '**' to match directories, and other extended
458
        # globbing stuff from cvs/rsync.
459
460
        # XXX: fnmatch is actually not quite what we want: it's only
461
        # approximately the same as real Unix fnmatch, and doesn't
462
        # treat dotfiles correctly and allows * to match /.
463
        # Eventually it should be replaced with something more
464
        # accurate.
465
        
466
        for pat in self.get_ignore_list():
467
            if '/' in pat or '\\' in pat:
468
                
469
                # as a special case, you can put ./ at the start of a
470
                # pattern; this is good to match in the top-level
471
                # only;
472
                
473
                if (pat[:2] == './') or (pat[:2] == '.\\'):
474
                    newpat = pat[2:]
475
                else:
476
                    newpat = pat
477
                if fnmatch.fnmatchcase(filename, newpat):
478
                    return pat
479
            else:
480
                if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
481
                    return pat
482
        else:
483
            return None
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
484
1185.12.28 by Aaron Bentley
Removed use of readonly path for executability test
485
    def kind(self, file_id):
486
        return file_kind(self.id2abspath(file_id))
487
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
488
    def lock_read(self):
489
        """See Branch.lock_read, and WorkingTree.unlock."""
490
        return self.branch.lock_read()
491
492
    def lock_write(self):
493
        """See Branch.lock_write, and WorkingTree.unlock."""
494
        return self.branch.lock_write()
495
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
496
    @needs_read_lock
497
    def read_working_inventory(self):
498
        """Read the working inventory."""
499
        # ElementTree does its own conversion from UTF-8, so open in
500
        # binary.
501
        f = self.branch.controlfile('inventory', 'rb')
502
        return bzrlib.xml5.serializer_v5.read_inventory(f)
503
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
504
    @needs_write_lock
505
    def remove(self, files, verbose=False):
506
        """Remove nominated files from the working inventory..
507
508
        This does not remove their text.  This does not run on XXX on what? RBC
509
510
        TODO: Refuse to remove modified files unless --force is given?
511
512
        TODO: Do something useful with directories.
513
514
        TODO: Should this remove the text or not?  Tough call; not
515
        removing may be useful and the user can just use use rm, and
516
        is the opposite of add.  Removing it is consistent with most
517
        other tools.  Maybe an option.
518
        """
519
        ## TODO: Normalize names
520
        ## TODO: Remove nested loops; better scalability
521
        if isinstance(files, basestring):
522
            files = [files]
523
524
        inv = self.inventory
525
526
        # do this before any modifications
527
        for f in files:
528
            fid = inv.path2id(f)
529
            if not fid:
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
530
                # TODO: Perhaps make this just a warning, and continue?
531
                # This tends to happen when 
532
                raise NotVersionedError(path=f)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
533
            mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
534
            if verbose:
535
                # having remove it, it must be either ignored or unknown
536
                if self.is_ignored(f):
537
                    new_status = 'I'
538
                else:
539
                    new_status = '?'
540
                show_status(new_status, inv[fid].kind, quotefn(f))
541
            del inv[fid]
542
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
543
        self._write_inventory(inv)
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
544
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
545
    @needs_write_lock
1501 by Robert Collins
Move revert from Branch to WorkingTree.
546
    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.
547
        from bzrlib.merge import merge_inner
1501 by Robert Collins
Move revert from Branch to WorkingTree.
548
        if old_tree is None:
549
            old_tree = self.branch.basis_tree()
1457.1.8 by Robert Collins
Replace the WorkingTree.revert method algorithm with a call to merge_inner.
550
        merge_inner(self.branch, old_tree,
551
                    self, ignore_zero=True,
552
                    backup_files=backups, 
553
                    interesting_files=filenames)
554
        if not len(filenames):
1457.1.16 by Robert Collins
Move set_pending_merges to WorkingTree.
555
            self.set_pending_merges([])
1501 by Robert Collins
Move revert from Branch to WorkingTree.
556
557
    @needs_write_lock
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
558
    def set_inventory(self, new_inventory_list):
559
        from bzrlib.inventory import (Inventory,
560
                                      InventoryDirectory,
561
                                      InventoryEntry,
562
                                      InventoryFile,
563
                                      InventoryLink)
564
        inv = Inventory(self.get_root_id())
565
        for path, file_id, parent, kind in new_inventory_list:
566
            name = os.path.basename(path)
567
            if name == "":
568
                continue
569
            # fixme, there should be a factory function inv,add_?? 
570
            if kind == 'directory':
571
                inv.add(InventoryDirectory(file_id, name, parent))
572
            elif kind == 'file':
573
                inv.add(InventoryFile(file_id, name, parent))
574
            elif kind == 'symlink':
575
                inv.add(InventoryLink(file_id, name, parent))
576
            else:
577
                raise BzrError("unknown kind %r" % kind)
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
578
        self._write_inventory(inv)
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
579
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
580
    @needs_write_lock
581
    def set_root_id(self, file_id):
582
        """Set the root id for this tree."""
583
        inv = self.read_working_inventory()
584
        orig_root_id = inv.root.file_id
585
        del inv._byid[inv.root.file_id]
586
        inv.root.file_id = file_id
587
        inv._byid[inv.root.file_id] = inv.root
588
        for fid in inv:
589
            entry = inv[fid]
590
            if entry.parent_id in (None, orig_root_id):
591
                entry.parent_id = inv.root.file_id
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
592
        self._write_inventory(inv)
1457.1.10 by Robert Collins
Move set_root_id to WorkingTree.
593
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
594
    def unlock(self):
595
        """See Branch.unlock.
596
        
597
        WorkingTree locking just uses the Branch locking facilities.
598
        This is current because all working trees have an embedded branch
599
        within them. IF in the future, we were to make branch data shareable
600
        between multiple working trees, i.e. via shared storage, then we 
601
        would probably want to lock both the local tree, and the branch.
602
        """
603
        return self.branch.unlock()
604
1457.1.11 by Robert Collins
Move _write_inventory to WorkingTree.
605
    @needs_write_lock
606
    def _write_inventory(self, inv):
607
        """Write inventory as the current inventory."""
608
        from cStringIO import StringIO
609
        from bzrlib.atomicfile import AtomicFile
610
        sio = StringIO()
611
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
612
        sio.seek(0)
613
        f = AtomicFile(self.branch.controlfilename('inventory'))
614
        try:
615
            pumpfile(sio, f)
616
            f.commit()
617
        finally:
618
            f.close()
619
        mutter('wrote working inventory')
620
            
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
621
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
622
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
623
def get_conflicted_stem(path):
624
    for suffix in CONFLICT_SUFFIXES:
625
        if path.endswith(suffix):
626
            return path[:-len(suffix)]