~bzr-pqm/bzr/bzr.dev

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