/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/workingtree.py

  • Committer: abentley
  • Date: 2005-10-16 05:15:58 UTC
  • mfrom: (1457)
  • mto: (1185.25.1)
  • mto: This revision was merged to the branch mainline in revision 1460.
  • Revision ID: abentley@lappy-20051016051558-502eb6c3601ceb90
Merged Robert's latest

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
 
 
17
# TODO: Don't allow WorkingTrees to be constructed for remote branches.
 
18
 
 
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
 
 
23
import os
 
24
import stat
 
25
import fnmatch
 
26
        
 
27
import bzrlib.tree
 
28
from bzrlib.osutils import appendpath, file_kind, isdir, splitpath
 
29
from bzrlib.errors import BzrCheckError
 
30
from bzrlib.trace import mutter
 
31
 
 
32
class TreeEntry(object):
 
33
    """An entry that implements the minium interface used by commands.
 
34
 
 
35
    This needs further inspection, it may be better to have 
 
36
    InventoryEntries without ids - though that seems wrong. For now,
 
37
    this is a parallel hierarchy to InventoryEntry, and needs to become
 
38
    one of several things: decorates to that hierarchy, children of, or
 
39
    parents of it.
 
40
    Another note is that these objects are currently only used when there is
 
41
    no InventoryEntry available - i.e. for unversioned objects.
 
42
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
 
43
    """
 
44
 
 
45
    def __eq__(self, other):
 
46
        # yes, this us ugly, TODO: best practice __eq__ style.
 
47
        return (isinstance(other, TreeEntry)
 
48
                and other.__class__ == self.__class__)
 
49
 
 
50
    def kind_character(self):
 
51
        return "???"
 
52
 
 
53
 
 
54
class TreeDirectory(TreeEntry):
 
55
    """See TreeEntry. This is a directory in a working tree."""
 
56
 
 
57
    def __eq__(self, other):
 
58
        return (isinstance(other, TreeDirectory)
 
59
                and other.__class__ == self.__class__)
 
60
 
 
61
    def kind_character(self):
 
62
        return "/"
 
63
 
 
64
 
 
65
class TreeFile(TreeEntry):
 
66
    """See TreeEntry. This is a regular file in a working tree."""
 
67
 
 
68
    def __eq__(self, other):
 
69
        return (isinstance(other, TreeFile)
 
70
                and other.__class__ == self.__class__)
 
71
 
 
72
    def kind_character(self):
 
73
        return ''
 
74
 
 
75
 
 
76
class TreeLink(TreeEntry):
 
77
    """See TreeEntry. This is a symlink in a working tree."""
 
78
 
 
79
    def __eq__(self, other):
 
80
        return (isinstance(other, TreeLink)
 
81
                and other.__class__ == self.__class__)
 
82
 
 
83
    def kind_character(self):
 
84
        return ''
 
85
 
 
86
 
 
87
class WorkingTree(bzrlib.tree.Tree):
 
88
    """Working copy tree.
 
89
 
 
90
    The inventory is held in the `Branch` working-inventory, and the
 
91
    files are in a directory on disk.
 
92
 
 
93
    It is possible for a `WorkingTree` to have a filename which is
 
94
    not listed in the Inventory and vice versa.
 
95
    """
 
96
    def __init__(self, basedir, inv):
 
97
        from bzrlib.hashcache import HashCache
 
98
        from bzrlib.trace import note, mutter
 
99
 
 
100
        self._inventory = inv
 
101
        self.basedir = basedir
 
102
        self.path2id = inv.path2id
 
103
 
 
104
        # update the whole cache up front and write to disk if anything changed;
 
105
        # in the future we might want to do this more selectively
 
106
        hc = self._hashcache = HashCache(basedir)
 
107
        hc.read()
 
108
        hc.scan()
 
109
 
 
110
        if hc.needs_write:
 
111
            mutter("write hc")
 
112
            hc.write()
 
113
            
 
114
            
 
115
    def __del__(self):
 
116
        if self._hashcache.needs_write:
 
117
            self._hashcache.write()
 
118
 
 
119
 
 
120
    def __iter__(self):
 
121
        """Iterate through file_ids for this tree.
 
122
 
 
123
        file_ids are in a WorkingTree if they are in the working inventory
 
124
        and the working file exists.
 
125
        """
 
126
        inv = self._inventory
 
127
        for path, ie in inv.iter_entries():
 
128
            if bzrlib.osutils.lexists(self.abspath(path)):
 
129
                yield ie.file_id
 
130
 
 
131
 
 
132
    def __repr__(self):
 
133
        return "<%s of %s>" % (self.__class__.__name__,
 
134
                               getattr(self, 'basedir', None))
 
135
 
 
136
 
 
137
 
 
138
    def abspath(self, filename):
 
139
        return os.path.join(self.basedir, filename)
 
140
 
 
141
    def has_filename(self, filename):
 
142
        return bzrlib.osutils.lexists(self.abspath(filename))
 
143
 
 
144
    def get_file(self, file_id):
 
145
        return self.get_file_byname(self.id2path(file_id))
 
146
 
 
147
    def get_file_byname(self, filename):
 
148
        return file(self.abspath(filename), 'rb')
 
149
 
 
150
    def _get_store_filename(self, file_id):
 
151
        ## XXX: badly named; this isn't in the store at all
 
152
        return self.abspath(self.id2path(file_id))
 
153
 
 
154
 
 
155
    def id2abspath(self, file_id):
 
156
        return self.abspath(self.id2path(file_id))
 
157
 
 
158
                
 
159
    def has_id(self, file_id):
 
160
        # files that have been deleted are excluded
 
161
        inv = self._inventory
 
162
        if not inv.has_id(file_id):
 
163
            return False
 
164
        path = inv.id2path(file_id)
 
165
        return bzrlib.osutils.lexists(self.abspath(path))
 
166
 
 
167
    def has_or_had_id(self, file_id):
 
168
        if file_id == self.inventory.root.file_id:
 
169
            return True
 
170
        return self.inventory.has_id(file_id)
 
171
 
 
172
    __contains__ = has_id
 
173
    
 
174
 
 
175
    def get_file_size(self, file_id):
 
176
        return os.path.getsize(self.id2abspath(file_id))
 
177
 
 
178
    def get_file_sha1(self, file_id):
 
179
        path = self._inventory.id2path(file_id)
 
180
        return self._hashcache.get_sha1(path)
 
181
 
 
182
 
 
183
    def is_executable(self, file_id):
 
184
        if os.name == "nt":
 
185
            return self._inventory[file_id].executable
 
186
        else:
 
187
            path = self._inventory.id2path(file_id)
 
188
            mode = os.lstat(self.abspath(path)).st_mode
 
189
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
 
190
 
 
191
    def get_symlink_target(self, file_id):
 
192
        return os.readlink(self.id2abspath(file_id))
 
193
 
 
194
    def file_class(self, filename):
 
195
        if self.path2id(filename):
 
196
            return 'V'
 
197
        elif self.is_ignored(filename):
 
198
            return 'I'
 
199
        else:
 
200
            return '?'
 
201
 
 
202
 
 
203
    def list_files(self):
 
204
        """Recursively list all files as (path, class, kind, id).
 
205
 
 
206
        Lists, but does not descend into unversioned directories.
 
207
 
 
208
        This does not include files that have been deleted in this
 
209
        tree.
 
210
 
 
211
        Skips the control directory.
 
212
        """
 
213
        inv = self._inventory
 
214
 
 
215
        def descend(from_dir_relpath, from_dir_id, dp):
 
216
            ls = os.listdir(dp)
 
217
            ls.sort()
 
218
            for f in ls:
 
219
                ## TODO: If we find a subdirectory with its own .bzr
 
220
                ## directory, then that is a separate tree and we
 
221
                ## should exclude it.
 
222
                if bzrlib.BZRDIR == f:
 
223
                    continue
 
224
 
 
225
                # path within tree
 
226
                fp = appendpath(from_dir_relpath, f)
 
227
 
 
228
                # absolute path
 
229
                fap = appendpath(dp, f)
 
230
                
 
231
                f_ie = inv.get_child(from_dir_id, f)
 
232
                if f_ie:
 
233
                    c = 'V'
 
234
                elif self.is_ignored(fp):
 
235
                    c = 'I'
 
236
                else:
 
237
                    c = '?'
 
238
 
 
239
                fk = file_kind(fap)
 
240
 
 
241
                if f_ie:
 
242
                    if f_ie.kind != fk:
 
243
                        raise BzrCheckError("file %r entered as kind %r id %r, "
 
244
                                            "now of kind %r"
 
245
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
 
246
 
 
247
                # make a last minute entry
 
248
                if f_ie:
 
249
                    entry = f_ie
 
250
                else:
 
251
                    if fk == 'directory':
 
252
                        entry = TreeDirectory()
 
253
                    elif fk == 'file':
 
254
                        entry = TreeFile()
 
255
                    elif fk == 'symlink':
 
256
                        entry = TreeLink()
 
257
                    else:
 
258
                        entry = TreeEntry()
 
259
                
 
260
                yield fp, c, fk, (f_ie and f_ie.file_id), entry
 
261
 
 
262
                if fk != 'directory':
 
263
                    continue
 
264
 
 
265
                if c != 'V':
 
266
                    # don't descend unversioned directories
 
267
                    continue
 
268
                
 
269
                for ff in descend(fp, f_ie.file_id, fap):
 
270
                    yield ff
 
271
 
 
272
        for f in descend('', inv.root.file_id, self.basedir):
 
273
            yield f
 
274
            
 
275
 
 
276
 
 
277
    def unknowns(self):
 
278
        for subp in self.extras():
 
279
            if not self.is_ignored(subp):
 
280
                yield subp
 
281
 
 
282
    def iter_conflicts(self):
 
283
        conflicted = set()
 
284
        for path in (s[0] for s in self.list_files()):
 
285
            stem = get_conflicted_stem(path)
 
286
            if stem is None:
 
287
                continue
 
288
            if stem not in conflicted:
 
289
                conflicted.add(stem)
 
290
                yield stem
 
291
 
 
292
    def extras(self):
 
293
        """Yield all unknown files in this WorkingTree.
 
294
 
 
295
        If there are any unknown directories then only the directory is
 
296
        returned, not all its children.  But if there are unknown files
 
297
        under a versioned subdirectory, they are returned.
 
298
 
 
299
        Currently returned depth-first, sorted by name within directories.
 
300
        """
 
301
        ## TODO: Work from given directory downwards
 
302
        for path, dir_entry in self.inventory.directories():
 
303
            mutter("search for unknowns in %r" % path)
 
304
            dirabs = self.abspath(path)
 
305
            if not isdir(dirabs):
 
306
                # e.g. directory deleted
 
307
                continue
 
308
 
 
309
            fl = []
 
310
            for subf in os.listdir(dirabs):
 
311
                if (subf != '.bzr'
 
312
                    and (subf not in dir_entry.children)):
 
313
                    fl.append(subf)
 
314
            
 
315
            fl.sort()
 
316
            for subf in fl:
 
317
                subp = appendpath(path, subf)
 
318
                yield subp
 
319
 
 
320
 
 
321
    def ignored_files(self):
 
322
        """Yield list of PATH, IGNORE_PATTERN"""
 
323
        for subp in self.extras():
 
324
            pat = self.is_ignored(subp)
 
325
            if pat != None:
 
326
                yield subp, pat
 
327
 
 
328
 
 
329
    def get_ignore_list(self):
 
330
        """Return list of ignore patterns.
 
331
 
 
332
        Cached in the Tree object after the first call.
 
333
        """
 
334
        if hasattr(self, '_ignorelist'):
 
335
            return self._ignorelist
 
336
 
 
337
        l = bzrlib.DEFAULT_IGNORE[:]
 
338
        if self.has_filename(bzrlib.IGNORE_FILENAME):
 
339
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
 
340
            l.extend([line.rstrip("\n\r") for line in f.readlines()])
 
341
        self._ignorelist = l
 
342
        return l
 
343
 
 
344
 
 
345
    def is_ignored(self, filename):
 
346
        r"""Check whether the filename matches an ignore pattern.
 
347
 
 
348
        Patterns containing '/' or '\' need to match the whole path;
 
349
        others match against only the last component.
 
350
 
 
351
        If the file is ignored, returns the pattern which caused it to
 
352
        be ignored, otherwise None.  So this can simply be used as a
 
353
        boolean if desired."""
 
354
 
 
355
        # TODO: Use '**' to match directories, and other extended
 
356
        # globbing stuff from cvs/rsync.
 
357
 
 
358
        # XXX: fnmatch is actually not quite what we want: it's only
 
359
        # approximately the same as real Unix fnmatch, and doesn't
 
360
        # treat dotfiles correctly and allows * to match /.
 
361
        # Eventually it should be replaced with something more
 
362
        # accurate.
 
363
        
 
364
        for pat in self.get_ignore_list():
 
365
            if '/' in pat or '\\' in pat:
 
366
                
 
367
                # as a special case, you can put ./ at the start of a
 
368
                # pattern; this is good to match in the top-level
 
369
                # only;
 
370
                
 
371
                if (pat[:2] == './') or (pat[:2] == '.\\'):
 
372
                    newpat = pat[2:]
 
373
                else:
 
374
                    newpat = pat
 
375
                if fnmatch.fnmatchcase(filename, newpat):
 
376
                    return pat
 
377
            else:
 
378
                if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
 
379
                    return pat
 
380
        else:
 
381
            return None
 
382
 
 
383
    def kind(self, file_id):
 
384
        return file_kind(self.id2abspath(file_id))
 
385
 
 
386
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
 
387
def get_conflicted_stem(path):
 
388
    for suffix in CONFLICT_SUFFIXES:
 
389
        if path.endswith(suffix):
 
390
            return path[:-len(suffix)]