/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: Aaron Bentley
  • Date: 2005-10-06 03:15:08 UTC
  • mto: (1185.12.13)
  • mto: This revision was merged to the branch mainline in revision 1419.
  • Revision ID: aaron.bentley@utoronto.ca-20051006031508-35ad4e5af9f9aff7
Added test_commit.py

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