/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
17
18
import os
19
    
20
import bzrlib.tree
21
from errors import BzrCheckError
22
from trace import mutter
23
24
25
class WorkingTree(bzrlib.tree.Tree):
26
    """Working copy tree.
27
28
    The inventory is held in the `Branch` working-inventory, and the
29
    files are in a directory on disk.
30
31
    It is possible for a `WorkingTree` to have a filename which is
32
    not listed in the Inventory and vice versa.
33
    """
34
    _statcache = None
35
    
36
    def __init__(self, basedir, inv):
37
        self._inventory = inv
38
        self.basedir = basedir
39
        self.path2id = inv.path2id
40
41
    def __repr__(self):
42
        return "<%s of %s>" % (self.__class__.__name__,
43
                               self.basedir)
44
45
    def abspath(self, filename):
46
        return os.path.join(self.basedir, filename)
47
48
    def has_filename(self, filename):
49
        return os.path.exists(self.abspath(filename))
50
51
    def get_file(self, file_id):
52
        return self.get_file_byname(self.id2path(file_id))
53
54
    def get_file_byname(self, filename):
55
        return file(self.abspath(filename), 'rb')
56
57
    def _get_store_filename(self, file_id):
58
        ## XXX: badly named; this isn't in the store at all
59
        return self.abspath(self.id2path(file_id))
60
61
    def has_id(self, file_id):
62
        # files that have been deleted are excluded
63
        if not self.inventory.has_id(file_id):
64
            return False
65
        import os
66
        return os.access(self.abspath(self.inventory.id2path(file_id)), os.F_OK)
67
68
    def get_file_size(self, file_id):
69
        import os, stat
70
        return os.stat(self._get_store_filename(file_id))[stat.ST_SIZE]
71
72
73
    def get_file_sha1(self, file_id):
74
        import statcache
75
        if not self._statcache:
76
            self._statcache = statcache.update_cache(self.basedir, self.inventory)
77
78
        return self._statcache[file_id][statcache.SC_SHA1]
79
80
81
    def file_class(self, filename):
82
        if self.path2id(filename):
83
            return 'V'
84
        elif self.is_ignored(filename):
85
            return 'I'
86
        else:
87
            return '?'
88
89
90
    def list_files(self):
91
        """Recursively list all files as (path, class, kind, id).
92
93
        Lists, but does not descend into unversioned directories.
94
95
        This does not include files that have been deleted in this
96
        tree.
97
98
        Skips the control directory.
99
        """
100
        from osutils import appendpath, file_kind
101
        import os
102
103
        inv = self.inventory
104
105
        def descend(from_dir_relpath, from_dir_id, dp):
106
            ls = os.listdir(dp)
107
            ls.sort()
108
            for f in ls:
109
                ## TODO: If we find a subdirectory with its own .bzr
110
                ## directory, then that is a separate tree and we
111
                ## should exclude it.
112
                if bzrlib.BZRDIR == f:
113
                    continue
114
115
                # path within tree
116
                fp = appendpath(from_dir_relpath, f)
117
118
                # absolute path
119
                fap = appendpath(dp, f)
120
                
121
                f_ie = inv.get_child(from_dir_id, f)
122
                if f_ie:
123
                    c = 'V'
124
                elif self.is_ignored(fp):
125
                    c = 'I'
126
                else:
127
                    c = '?'
128
129
                fk = file_kind(fap)
130
131
                if f_ie:
132
                    if f_ie.kind != fk:
133
                        raise BzrCheckError("file %r entered as kind %r id %r, "
134
                                            "now of kind %r"
135
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
136
137
                yield fp, c, fk, (f_ie and f_ie.file_id)
138
139
                if fk != 'directory':
140
                    continue
141
142
                if c != 'V':
143
                    # don't descend unversioned directories
144
                    continue
145
                
146
                for ff in descend(fp, f_ie.file_id, fap):
147
                    yield ff
148
149
        for f in descend('', inv.root.file_id, self.basedir):
150
            yield f
151
            
152
153
154
    def unknowns(self):
155
        for subp in self.extras():
156
            if not self.is_ignored(subp):
157
                yield subp
158
159
160
    def extras(self):
161
        """Yield all unknown files in this WorkingTree.
162
163
        If there are any unknown directories then only the directory is
164
        returned, not all its children.  But if there are unknown files
165
        under a versioned subdirectory, they are returned.
166
167
        Currently returned depth-first, sorted by name within directories.
168
        """
169
        ## TODO: Work from given directory downwards
170
        from osutils import isdir, appendpath
171
        
172
        for path, dir_entry in self.inventory.directories():
173
            mutter("search for unknowns in %r" % path)
174
            dirabs = self.abspath(path)
175
            if not isdir(dirabs):
176
                # e.g. directory deleted
177
                continue
178
179
            fl = []
180
            for subf in os.listdir(dirabs):
181
                if (subf != '.bzr'
182
                    and (subf not in dir_entry.children)):
183
                    fl.append(subf)
184
            
185
            fl.sort()
186
            for subf in fl:
187
                subp = appendpath(path, subf)
188
                yield subp
189
190
191
    def ignored_files(self):
192
        """Yield list of PATH, IGNORE_PATTERN"""
193
        for subp in self.extras():
194
            pat = self.is_ignored(subp)
195
            if pat != None:
196
                yield subp, pat
197
198
199
    def get_ignore_list(self):
200
        """Return list of ignore patterns.
201
202
        Cached in the Tree object after the first call.
203
        """
204
        if hasattr(self, '_ignorelist'):
205
            return self._ignorelist
206
207
        l = bzrlib.DEFAULT_IGNORE[:]
208
        if self.has_filename(bzrlib.IGNORE_FILENAME):
209
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
210
            l.extend([line.rstrip("\n\r") for line in f.readlines()])
211
        self._ignorelist = l
212
        return l
213
214
215
    def is_ignored(self, filename):
216
        r"""Check whether the filename matches an ignore pattern.
217
218
        Patterns containing '/' or '\' need to match the whole path;
219
        others match against only the last component.
220
221
        If the file is ignored, returns the pattern which caused it to
222
        be ignored, otherwise None.  So this can simply be used as a
223
        boolean if desired."""
224
225
        # TODO: Use '**' to match directories, and other extended
226
        # globbing stuff from cvs/rsync.
227
228
        # XXX: fnmatch is actually not quite what we want: it's only
229
        # approximately the same as real Unix fnmatch, and doesn't
230
        # treat dotfiles correctly and allows * to match /.
231
        # Eventually it should be replaced with something more
232
        # accurate.
233
        
234
        import fnmatch
235
        from osutils import splitpath
236
        
237
        for pat in self.get_ignore_list():
238
            if '/' in pat or '\\' in pat:
239
                
240
                # as a special case, you can put ./ at the start of a
241
                # pattern; this is good to match in the top-level
242
                # only;
243
                
244
                if (pat[:2] == './') or (pat[:2] == '.\\'):
245
                    newpat = pat[2:]
246
                else:
247
                    newpat = pat
248
                if fnmatch.fnmatchcase(filename, newpat):
249
                    return pat
250
            else:
251
                if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
252
                    return pat
253
        else:
254
            return None
255
        
256
257
        
258
        
259