/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
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.
17
# TODO: Don't allow WorkingTrees to be constructed for remote branches.
453 by Martin Pool
- Split WorkingTree into its own file
18
956 by Martin Pool
doc
19
# FIXME: I don't know if writing out the cache from the destructor is really a
20
# good idea, because destructors are considered poor taste in Python, and
21
# it's not predictable when it will be written out.
22
453 by Martin Pool
- Split WorkingTree into its own file
23
import os
1398 by Robert Collins
integrate in Gustavos x-bit patch
24
import stat
1140 by Martin Pool
- lift out import statements within WorkingTree
25
import fnmatch
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
26
 
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
27
from bzrlib.branch import Branch, needs_read_lock, needs_write_lock, quotefn
453 by Martin Pool
- Split WorkingTree into its own file
28
import bzrlib.tree
1457.1.3 by Robert Collins
make Branch.relpath delegate to the working tree.
29
from bzrlib.osutils import appendpath, file_kind, isdir, splitpath, relpath
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
30
from bzrlib.errors import BzrCheckError, DivergedBranches
1140 by Martin Pool
- lift out import statements within WorkingTree
31
from bzrlib.trace import mutter
453 by Martin Pool
- Split WorkingTree into its own file
32
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
33
class TreeEntry(object):
34
    """An entry that implements the minium interface used by commands.
35
36
    This needs further inspection, it may be better to have 
37
    InventoryEntries without ids - though that seems wrong. For now,
38
    this is a parallel hierarchy to InventoryEntry, and needs to become
39
    one of several things: decorates to that hierarchy, children of, or
40
    parents of it.
1399.1.3 by Robert Collins
move change detection for text and metadata from delta to entry.detect_changes
41
    Another note is that these objects are currently only used when there is
42
    no InventoryEntry available - i.e. for unversioned objects.
43
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
44
    """
45
 
46
    def __eq__(self, other):
47
        # yes, this us ugly, TODO: best practice __eq__ style.
48
        return (isinstance(other, TreeEntry)
49
                and other.__class__ == self.__class__)
50
 
51
    def kind_character(self):
52
        return "???"
53
54
55
class TreeDirectory(TreeEntry):
56
    """See TreeEntry. This is a directory in a working tree."""
57
58
    def __eq__(self, other):
59
        return (isinstance(other, TreeDirectory)
60
                and other.__class__ == self.__class__)
61
62
    def kind_character(self):
63
        return "/"
64
65
66
class TreeFile(TreeEntry):
67
    """See TreeEntry. This is a regular file in a working tree."""
68
69
    def __eq__(self, other):
70
        return (isinstance(other, TreeFile)
71
                and other.__class__ == self.__class__)
72
73
    def kind_character(self):
74
        return ''
75
76
77
class TreeLink(TreeEntry):
78
    """See TreeEntry. This is a symlink in a working tree."""
79
80
    def __eq__(self, other):
81
        return (isinstance(other, TreeLink)
82
                and other.__class__ == self.__class__)
83
84
    def kind_character(self):
85
        return ''
86
87
453 by Martin Pool
- Split WorkingTree into its own file
88
class WorkingTree(bzrlib.tree.Tree):
89
    """Working copy tree.
90
91
    The inventory is held in the `Branch` working-inventory, and the
92
    files are in a directory on disk.
93
94
    It is possible for a `WorkingTree` to have a filename which is
95
    not listed in the Inventory and vice versa.
96
    """
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
97
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
98
    def __init__(self, basedir, branch=None):
99
        """Construct a WorkingTree for basedir.
100
101
        If the branch is not supplied, it is opened automatically.
102
        If the branch is supplied, it must be the branch for this basedir.
103
        (branch.base is not cross checked, because for remote branches that
104
        would be meaningless).
105
        """
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.
106
        from bzrlib.hashcache import HashCache
107
        from bzrlib.trace import note, mutter
108
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
109
        if branch is None:
110
            branch = Branch.open(basedir)
111
        self._inventory = branch.inventory
112
        self.path2id = self._inventory.path2id
113
        self.branch = branch
453 by Martin Pool
- Split WorkingTree into its own file
114
        self.basedir = basedir
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.
115
116
        # update the whole cache up front and write to disk if anything changed;
117
        # in the future we might want to do this more selectively
118
        hc = self._hashcache = HashCache(basedir)
119
        hc.read()
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
120
        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.
121
122
        if hc.needs_write:
123
            mutter("write hc")
124
            hc.write()
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
125
            
126
            
127
    def __del__(self):
128
        if self._hashcache.needs_write:
129
            self._hashcache.write()
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.
130
453 by Martin Pool
- Split WorkingTree into its own file
131
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
132
    def __iter__(self):
133
        """Iterate through file_ids for this tree.
134
135
        file_ids are in a WorkingTree if they are in the working inventory
136
        and the working file exists.
137
        """
138
        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.
139
        for path, ie in inv.iter_entries():
1092.2.6 by Robert Collins
symlink support updated to work
140
            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.
141
                yield ie.file_id
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
142
143
453 by Martin Pool
- Split WorkingTree into its own file
144
    def __repr__(self):
145
        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
146
                               getattr(self, 'basedir', None))
453 by Martin Pool
- Split WorkingTree into its own file
147
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.
148
149
453 by Martin Pool
- Split WorkingTree into its own file
150
    def abspath(self, filename):
151
        return os.path.join(self.basedir, filename)
152
1457.1.3 by Robert Collins
make Branch.relpath delegate to the working tree.
153
    def relpath(self, abspath):
154
        """Return the local path portion from a given absolute path."""
155
        return relpath(self.basedir, abspath)
156
453 by Martin Pool
- Split WorkingTree into its own file
157
    def has_filename(self, filename):
1092.2.6 by Robert Collins
symlink support updated to work
158
        return bzrlib.osutils.lexists(self.abspath(filename))
453 by Martin Pool
- Split WorkingTree into its own file
159
160
    def get_file(self, file_id):
161
        return self.get_file_byname(self.id2path(file_id))
162
163
    def get_file_byname(self, filename):
164
        return file(self.abspath(filename), 'rb')
165
166
    def _get_store_filename(self, file_id):
167
        ## XXX: badly named; this isn't in the store at all
168
        return self.abspath(self.id2path(file_id))
169
1248 by Martin Pool
- new weave based cleanup [broken]
170
171
    def id2abspath(self, file_id):
172
        return self.abspath(self.id2path(file_id))
173
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
174
                
1185.12.39 by abentley
Propogated has_or_had_id to Tree
175
    def has_id(self, file_id):
453 by Martin Pool
- Split WorkingTree into its own file
176
        # files that have been deleted are excluded
1185.12.39 by abentley
Propogated has_or_had_id to Tree
177
        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.
178
        if not inv.has_id(file_id):
453 by Martin Pool
- Split WorkingTree into its own file
179
            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.
180
        path = inv.id2path(file_id)
1092.2.6 by Robert Collins
symlink support updated to work
181
        return bzrlib.osutils.lexists(self.abspath(path))
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
182
1185.12.39 by abentley
Propogated has_or_had_id to Tree
183
    def has_or_had_id(self, file_id):
184
        if file_id == self.inventory.root.file_id:
185
            return True
186
        return self.inventory.has_id(file_id)
462 by Martin Pool
- New form 'file_id in tree' to check if the file is present
187
188
    __contains__ = has_id
189
    
190
453 by Martin Pool
- Split WorkingTree into its own file
191
    def get_file_size(self, file_id):
1248 by Martin Pool
- new weave based cleanup [broken]
192
        return os.path.getsize(self.id2abspath(file_id))
453 by Martin Pool
- Split WorkingTree into its own file
193
194
    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.
195
        path = self._inventory.id2path(file_id)
196
        return self._hashcache.get_sha1(path)
453 by Martin Pool
- Split WorkingTree into its own file
197
1398 by Robert Collins
integrate in Gustavos x-bit patch
198
199
    def is_executable(self, file_id):
200
        if os.name == "nt":
201
            return self._inventory[file_id].executable
202
        else:
203
            path = self._inventory.id2path(file_id)
204
            mode = os.lstat(self.abspath(path)).st_mode
205
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
206
1092.2.6 by Robert Collins
symlink support updated to work
207
    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
208
        return os.readlink(self.id2abspath(file_id))
453 by Martin Pool
- Split WorkingTree into its own file
209
210
    def file_class(self, filename):
211
        if self.path2id(filename):
212
            return 'V'
213
        elif self.is_ignored(filename):
214
            return 'I'
215
        else:
216
            return '?'
217
218
219
    def list_files(self):
220
        """Recursively list all files as (path, class, kind, id).
221
222
        Lists, but does not descend into unversioned directories.
223
224
        This does not include files that have been deleted in this
225
        tree.
226
227
        Skips the control directory.
228
        """
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.
229
        inv = self._inventory
453 by Martin Pool
- Split WorkingTree into its own file
230
231
        def descend(from_dir_relpath, from_dir_id, dp):
232
            ls = os.listdir(dp)
233
            ls.sort()
234
            for f in ls:
235
                ## TODO: If we find a subdirectory with its own .bzr
236
                ## directory, then that is a separate tree and we
237
                ## should exclude it.
238
                if bzrlib.BZRDIR == f:
239
                    continue
240
241
                # path within tree
242
                fp = appendpath(from_dir_relpath, f)
243
244
                # absolute path
245
                fap = appendpath(dp, f)
246
                
247
                f_ie = inv.get_child(from_dir_id, f)
248
                if f_ie:
249
                    c = 'V'
250
                elif self.is_ignored(fp):
251
                    c = 'I'
252
                else:
253
                    c = '?'
254
255
                fk = file_kind(fap)
256
257
                if f_ie:
258
                    if f_ie.kind != fk:
259
                        raise BzrCheckError("file %r entered as kind %r id %r, "
260
                                            "now of kind %r"
261
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
262
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
263
                # make a last minute entry
264
                if f_ie:
265
                    entry = f_ie
266
                else:
267
                    if fk == 'directory':
268
                        entry = TreeDirectory()
269
                    elif fk == 'file':
270
                        entry = TreeFile()
271
                    elif fk == 'symlink':
272
                        entry = TreeLink()
273
                    else:
274
                        entry = TreeEntry()
275
                
276
                yield fp, c, fk, (f_ie and f_ie.file_id), entry
453 by Martin Pool
- Split WorkingTree into its own file
277
278
                if fk != 'directory':
279
                    continue
280
281
                if c != 'V':
282
                    # don't descend unversioned directories
283
                    continue
284
                
285
                for ff in descend(fp, f_ie.file_id, fap):
286
                    yield ff
287
288
        for f in descend('', inv.root.file_id, self.basedir):
289
            yield f
290
            
291
292
293
    def unknowns(self):
294
        for subp in self.extras():
295
            if not self.is_ignored(subp):
296
                yield subp
297
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
298
    def iter_conflicts(self):
299
        conflicted = set()
300
        for path in (s[0] for s in self.list_files()):
301
            stem = get_conflicted_stem(path)
302
            if stem is None:
303
                continue
304
            if stem not in conflicted:
305
                conflicted.add(stem)
306
                yield stem
453 by Martin Pool
- Split WorkingTree into its own file
307
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
308
    @needs_write_lock
1442.1.68 by Robert Collins
'bzr pull' now accepts '--clobber'.
309
    def pull(self, source, remember=False, clobber=False):
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
310
        from bzrlib.merge import merge
311
        source.lock_read()
312
        try:
313
            old_revno = self.branch.revno()
314
            old_revision_history = self.branch.revision_history()
315
            try:
316
                self.branch.update_revisions(source)
317
            except DivergedBranches:
1442.1.68 by Robert Collins
'bzr pull' now accepts '--clobber'.
318
                if not clobber:
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
319
                    raise
1442.1.68 by Robert Collins
'bzr pull' now accepts '--clobber'.
320
                self.branch.set_revision_history(source.revision_history())
1442.1.67 by Robert Collins
Factor out the guts of 'pull' from the command into WorkingTree.pull().
321
            new_revision_history = self.branch.revision_history()
322
            if new_revision_history != old_revision_history:
323
                merge((self.basedir, -1), (self.basedir, old_revno), check_clean=False)
324
            if self.branch.get_parent() is None or remember:
325
                self.branch.set_parent(source.base)
326
        finally:
327
            source.unlock()
328
453 by Martin Pool
- Split WorkingTree into its own file
329
    def extras(self):
330
        """Yield all unknown files in this WorkingTree.
331
332
        If there are any unknown directories then only the directory is
333
        returned, not all its children.  But if there are unknown files
334
        under a versioned subdirectory, they are returned.
335
336
        Currently returned depth-first, sorted by name within directories.
337
        """
338
        ## TODO: Work from given directory downwards
339
        for path, dir_entry in self.inventory.directories():
340
            mutter("search for unknowns in %r" % path)
341
            dirabs = self.abspath(path)
342
            if not isdir(dirabs):
343
                # e.g. directory deleted
344
                continue
345
346
            fl = []
347
            for subf in os.listdir(dirabs):
348
                if (subf != '.bzr'
349
                    and (subf not in dir_entry.children)):
350
                    fl.append(subf)
351
            
352
            fl.sort()
353
            for subf in fl:
354
                subp = appendpath(path, subf)
355
                yield subp
356
357
358
    def ignored_files(self):
359
        """Yield list of PATH, IGNORE_PATTERN"""
360
        for subp in self.extras():
361
            pat = self.is_ignored(subp)
362
            if pat != None:
363
                yield subp, pat
364
365
366
    def get_ignore_list(self):
367
        """Return list of ignore patterns.
368
369
        Cached in the Tree object after the first call.
370
        """
371
        if hasattr(self, '_ignorelist'):
372
            return self._ignorelist
373
374
        l = bzrlib.DEFAULT_IGNORE[:]
375
        if self.has_filename(bzrlib.IGNORE_FILENAME):
376
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
377
            l.extend([line.rstrip("\n\r") for line in f.readlines()])
378
        self._ignorelist = l
379
        return l
380
381
382
    def is_ignored(self, filename):
383
        r"""Check whether the filename matches an ignore pattern.
384
385
        Patterns containing '/' or '\' need to match the whole path;
386
        others match against only the last component.
387
388
        If the file is ignored, returns the pattern which caused it to
389
        be ignored, otherwise None.  So this can simply be used as a
390
        boolean if desired."""
391
392
        # TODO: Use '**' to match directories, and other extended
393
        # globbing stuff from cvs/rsync.
394
395
        # XXX: fnmatch is actually not quite what we want: it's only
396
        # approximately the same as real Unix fnmatch, and doesn't
397
        # treat dotfiles correctly and allows * to match /.
398
        # Eventually it should be replaced with something more
399
        # accurate.
400
        
401
        for pat in self.get_ignore_list():
402
            if '/' in pat or '\\' in pat:
403
                
404
                # as a special case, you can put ./ at the start of a
405
                # pattern; this is good to match in the top-level
406
                # only;
407
                
408
                if (pat[:2] == './') or (pat[:2] == '.\\'):
409
                    newpat = pat[2:]
410
                else:
411
                    newpat = pat
412
                if fnmatch.fnmatchcase(filename, newpat):
413
                    return pat
414
            else:
415
                if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
416
                    return pat
417
        else:
418
            return None
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
419
1185.12.28 by Aaron Bentley
Removed use of readonly path for executability test
420
    def kind(self, file_id):
421
        return file_kind(self.id2abspath(file_id))
422
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
423
    def lock_read(self):
424
        """See Branch.lock_read, and WorkingTree.unlock."""
425
        return self.branch.lock_read()
426
427
    def lock_write(self):
428
        """See Branch.lock_write, and WorkingTree.unlock."""
429
        return self.branch.lock_write()
430
431
    @needs_write_lock
432
    def remove(self, files, verbose=False):
433
        """Remove nominated files from the working inventory..
434
435
        This does not remove their text.  This does not run on XXX on what? RBC
436
437
        TODO: Refuse to remove modified files unless --force is given?
438
439
        TODO: Do something useful with directories.
440
441
        TODO: Should this remove the text or not?  Tough call; not
442
        removing may be useful and the user can just use use rm, and
443
        is the opposite of add.  Removing it is consistent with most
444
        other tools.  Maybe an option.
445
        """
446
        ## TODO: Normalize names
447
        ## TODO: Remove nested loops; better scalability
448
        if isinstance(files, basestring):
449
            files = [files]
450
451
        inv = self.inventory
452
453
        # do this before any modifications
454
        for f in files:
455
            fid = inv.path2id(f)
456
            if not fid:
457
                raise BzrError("cannot remove unversioned file %s" % quotefn(f))
458
            mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
459
            if verbose:
460
                # having remove it, it must be either ignored or unknown
461
                if self.is_ignored(f):
462
                    new_status = 'I'
463
                else:
464
                    new_status = '?'
465
                show_status(new_status, inv[fid].kind, quotefn(f))
466
            del inv[fid]
467
468
        self.branch._write_inventory(inv)
469
470
    def unlock(self):
471
        """See Branch.unlock.
472
        
473
        WorkingTree locking just uses the Branch locking facilities.
474
        This is current because all working trees have an embedded branch
475
        within them. IF in the future, we were to make branch data shareable
476
        between multiple working trees, i.e. via shared storage, then we 
477
        would probably want to lock both the local tree, and the branch.
478
        """
479
        return self.branch.unlock()
480
481
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
482
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
483
def get_conflicted_stem(path):
484
    for suffix in CONFLICT_SUFFIXES:
485
        if path.endswith(suffix):
486
            return path[:-len(suffix)]