/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
1140 by Martin Pool
- lift out import statements within WorkingTree
30
from bzrlib.errors import BzrCheckError
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
308
    def extras(self):
309
        """Yield all unknown files in this WorkingTree.
310
311
        If there are any unknown directories then only the directory is
312
        returned, not all its children.  But if there are unknown files
313
        under a versioned subdirectory, they are returned.
314
315
        Currently returned depth-first, sorted by name within directories.
316
        """
317
        ## TODO: Work from given directory downwards
318
        for path, dir_entry in self.inventory.directories():
319
            mutter("search for unknowns in %r" % path)
320
            dirabs = self.abspath(path)
321
            if not isdir(dirabs):
322
                # e.g. directory deleted
323
                continue
324
325
            fl = []
326
            for subf in os.listdir(dirabs):
327
                if (subf != '.bzr'
328
                    and (subf not in dir_entry.children)):
329
                    fl.append(subf)
330
            
331
            fl.sort()
332
            for subf in fl:
333
                subp = appendpath(path, subf)
334
                yield subp
335
336
337
    def ignored_files(self):
338
        """Yield list of PATH, IGNORE_PATTERN"""
339
        for subp in self.extras():
340
            pat = self.is_ignored(subp)
341
            if pat != None:
342
                yield subp, pat
343
344
345
    def get_ignore_list(self):
346
        """Return list of ignore patterns.
347
348
        Cached in the Tree object after the first call.
349
        """
350
        if hasattr(self, '_ignorelist'):
351
            return self._ignorelist
352
353
        l = bzrlib.DEFAULT_IGNORE[:]
354
        if self.has_filename(bzrlib.IGNORE_FILENAME):
355
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
356
            l.extend([line.rstrip("\n\r") for line in f.readlines()])
357
        self._ignorelist = l
358
        return l
359
360
361
    def is_ignored(self, filename):
362
        r"""Check whether the filename matches an ignore pattern.
363
364
        Patterns containing '/' or '\' need to match the whole path;
365
        others match against only the last component.
366
367
        If the file is ignored, returns the pattern which caused it to
368
        be ignored, otherwise None.  So this can simply be used as a
369
        boolean if desired."""
370
371
        # TODO: Use '**' to match directories, and other extended
372
        # globbing stuff from cvs/rsync.
373
374
        # XXX: fnmatch is actually not quite what we want: it's only
375
        # approximately the same as real Unix fnmatch, and doesn't
376
        # treat dotfiles correctly and allows * to match /.
377
        # Eventually it should be replaced with something more
378
        # accurate.
379
        
380
        for pat in self.get_ignore_list():
381
            if '/' in pat or '\\' in pat:
382
                
383
                # as a special case, you can put ./ at the start of a
384
                # pattern; this is good to match in the top-level
385
                # only;
386
                
387
                if (pat[:2] == './') or (pat[:2] == '.\\'):
388
                    newpat = pat[2:]
389
                else:
390
                    newpat = pat
391
                if fnmatch.fnmatchcase(filename, newpat):
392
                    return pat
393
            else:
394
                if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
395
                    return pat
396
        else:
397
            return None
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
398
1185.12.28 by Aaron Bentley
Removed use of readonly path for executability test
399
    def kind(self, file_id):
400
        return file_kind(self.id2abspath(file_id))
401
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
402
    def lock_read(self):
403
        """See Branch.lock_read, and WorkingTree.unlock."""
404
        return self.branch.lock_read()
405
406
    def lock_write(self):
407
        """See Branch.lock_write, and WorkingTree.unlock."""
408
        return self.branch.lock_write()
409
410
    @needs_write_lock
411
    def remove(self, files, verbose=False):
412
        """Remove nominated files from the working inventory..
413
414
        This does not remove their text.  This does not run on XXX on what? RBC
415
416
        TODO: Refuse to remove modified files unless --force is given?
417
418
        TODO: Do something useful with directories.
419
420
        TODO: Should this remove the text or not?  Tough call; not
421
        removing may be useful and the user can just use use rm, and
422
        is the opposite of add.  Removing it is consistent with most
423
        other tools.  Maybe an option.
424
        """
425
        ## TODO: Normalize names
426
        ## TODO: Remove nested loops; better scalability
427
        if isinstance(files, basestring):
428
            files = [files]
429
430
        inv = self.inventory
431
432
        # do this before any modifications
433
        for f in files:
434
            fid = inv.path2id(f)
435
            if not fid:
436
                raise BzrError("cannot remove unversioned file %s" % quotefn(f))
437
            mutter("remove inventory entry %s {%s}" % (quotefn(f), fid))
438
            if verbose:
439
                # having remove it, it must be either ignored or unknown
440
                if self.is_ignored(f):
441
                    new_status = 'I'
442
                else:
443
                    new_status = '?'
444
                show_status(new_status, inv[fid].kind, quotefn(f))
445
            del inv[fid]
446
447
        self.branch._write_inventory(inv)
448
449
    def unlock(self):
450
        """See Branch.unlock.
451
        
452
        WorkingTree locking just uses the Branch locking facilities.
453
        This is current because all working trees have an embedded branch
454
        within them. IF in the future, we were to make branch data shareable
455
        between multiple working trees, i.e. via shared storage, then we 
456
        would probably want to lock both the local tree, and the branch.
457
        """
458
        return self.branch.unlock()
459
460
1185.14.6 by Aaron Bentley
Made iter_conflicts a WorkingTree method
461
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
462
def get_conflicted_stem(path):
463
    for suffix in CONFLICT_SUFFIXES:
464
        if path.endswith(suffix):
465
            return path[:-len(suffix)]