1
# Copyright (C) 2005 Canonical Ltd
 
 
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.
 
 
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.
 
 
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
 
 
17
# TODO: Don't allow WorkingTrees to be constructed for remote branches.
 
 
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.
 
 
28
from bzrlib.osutils import appendpath, file_kind, isdir, splitpath
 
 
29
from bzrlib.errors import BzrCheckError
 
 
30
from bzrlib.trace import mutter
 
 
32
class TreeEntry(object):
 
 
33
    """An entry that implements the minium interface used by commands.
 
 
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
 
 
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
 
 
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__)
 
 
50
    def kind_character(self):
 
 
54
class TreeDirectory(TreeEntry):
 
 
55
    """See TreeEntry. This is a directory in a working tree."""
 
 
57
    def __eq__(self, other):
 
 
58
        return (isinstance(other, TreeDirectory)
 
 
59
                and other.__class__ == self.__class__)
 
 
61
    def kind_character(self):
 
 
65
class TreeFile(TreeEntry):
 
 
66
    """See TreeEntry. This is a regular file in a working tree."""
 
 
68
    def __eq__(self, other):
 
 
69
        return (isinstance(other, TreeFile)
 
 
70
                and other.__class__ == self.__class__)
 
 
72
    def kind_character(self):
 
 
76
class TreeLink(TreeEntry):
 
 
77
    """See TreeEntry. This is a symlink in a working tree."""
 
 
79
    def __eq__(self, other):
 
 
80
        return (isinstance(other, TreeLink)
 
 
81
                and other.__class__ == self.__class__)
 
 
83
    def kind_character(self):
 
 
87
class WorkingTree(bzrlib.tree.Tree):
 
 
90
    The inventory is held in the `Branch` working-inventory, and the
 
 
91
    files are in a directory on disk.
 
 
93
    It is possible for a `WorkingTree` to have a filename which is
 
 
94
    not listed in the Inventory and vice versa.
 
 
96
    def __init__(self, basedir, inv):
 
 
97
        from bzrlib.hashcache import HashCache
 
 
98
        from bzrlib.trace import note, mutter
 
 
100
        self._inventory = inv
 
 
101
        self.basedir = basedir
 
 
102
        self.path2id = inv.path2id
 
 
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)
 
 
116
        if self._hashcache.needs_write:
 
 
117
            self._hashcache.write()
 
 
121
        """Iterate through file_ids for this tree.
 
 
123
        file_ids are in a WorkingTree if they are in the working inventory
 
 
124
        and the working file exists.
 
 
126
        inv = self._inventory
 
 
127
        for path, ie in inv.iter_entries():
 
 
128
            if bzrlib.osutils.lexists(self.abspath(path)):
 
 
133
        return "<%s of %s>" % (self.__class__.__name__,
 
 
134
                               getattr(self, 'basedir', None))
 
 
138
    def abspath(self, filename):
 
 
139
        return os.path.join(self.basedir, filename)
 
 
141
    def has_filename(self, filename):
 
 
142
        return bzrlib.osutils.lexists(self.abspath(filename))
 
 
144
    def get_file(self, file_id):
 
 
145
        return self.get_file_byname(self.id2path(file_id))
 
 
147
    def get_file_byname(self, filename):
 
 
148
        return file(self.abspath(filename), 'rb')
 
 
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))
 
 
155
    def id2abspath(self, file_id):
 
 
156
        return self.abspath(self.id2path(file_id))
 
 
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):
 
 
164
        path = inv.id2path(file_id)
 
 
165
        return bzrlib.osutils.lexists(self.abspath(path))
 
 
168
    __contains__ = has_id
 
 
171
    def get_file_size(self, file_id):
 
 
172
        return os.path.getsize(self.id2abspath(file_id))
 
 
174
    def get_file_sha1(self, file_id):
 
 
175
        path = self._inventory.id2path(file_id)
 
 
176
        return self._hashcache.get_sha1(path)
 
 
179
    def is_executable(self, file_id):
 
 
181
            return self._inventory[file_id].executable
 
 
183
            path = self._inventory.id2path(file_id)
 
 
184
            mode = os.lstat(self.abspath(path)).st_mode
 
 
185
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC&mode)
 
 
187
    def get_symlink_target(self, file_id):
 
 
188
        return os.readlink(self.id2abspath(file_id))
 
 
190
    def file_class(self, filename):
 
 
191
        if self.path2id(filename):
 
 
193
        elif self.is_ignored(filename):
 
 
199
    def list_files(self):
 
 
200
        """Recursively list all files as (path, class, kind, id).
 
 
202
        Lists, but does not descend into unversioned directories.
 
 
204
        This does not include files that have been deleted in this
 
 
207
        Skips the control directory.
 
 
209
        inv = self._inventory
 
 
211
        def descend(from_dir_relpath, from_dir_id, dp):
 
 
215
                ## TODO: If we find a subdirectory with its own .bzr
 
 
216
                ## directory, then that is a separate tree and we
 
 
217
                ## should exclude it.
 
 
218
                if bzrlib.BZRDIR == f:
 
 
222
                fp = appendpath(from_dir_relpath, f)
 
 
225
                fap = appendpath(dp, f)
 
 
227
                f_ie = inv.get_child(from_dir_id, f)
 
 
230
                elif self.is_ignored(fp):
 
 
239
                        raise BzrCheckError("file %r entered as kind %r id %r, "
 
 
241
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
 
 
243
                # make a last minute entry
 
 
247
                    if fk == 'directory':
 
 
248
                        entry = TreeDirectory()
 
 
251
                    elif fk == 'symlink':
 
 
256
                yield fp, c, fk, (f_ie and f_ie.file_id), entry
 
 
258
                if fk != 'directory':
 
 
262
                    # don't descend unversioned directories
 
 
265
                for ff in descend(fp, f_ie.file_id, fap):
 
 
268
        for f in descend('', inv.root.file_id, self.basedir):
 
 
274
        for subp in self.extras():
 
 
275
            if not self.is_ignored(subp):
 
 
278
    def iter_conflicts(self):
 
 
280
        for path in (s[0] for s in self.list_files()):
 
 
281
            stem = get_conflicted_stem(path)
 
 
284
            if stem not in conflicted:
 
 
289
        """Yield all unknown files in this WorkingTree.
 
 
291
        If there are any unknown directories then only the directory is
 
 
292
        returned, not all its children.  But if there are unknown files
 
 
293
        under a versioned subdirectory, they are returned.
 
 
295
        Currently returned depth-first, sorted by name within directories.
 
 
297
        ## TODO: Work from given directory downwards
 
 
298
        for path, dir_entry in self.inventory.directories():
 
 
299
            mutter("search for unknowns in %r" % path)
 
 
300
            dirabs = self.abspath(path)
 
 
301
            if not isdir(dirabs):
 
 
302
                # e.g. directory deleted
 
 
306
            for subf in os.listdir(dirabs):
 
 
308
                    and (subf not in dir_entry.children)):
 
 
313
                subp = appendpath(path, subf)
 
 
317
    def ignored_files(self):
 
 
318
        """Yield list of PATH, IGNORE_PATTERN"""
 
 
319
        for subp in self.extras():
 
 
320
            pat = self.is_ignored(subp)
 
 
325
    def get_ignore_list(self):
 
 
326
        """Return list of ignore patterns.
 
 
328
        Cached in the Tree object after the first call.
 
 
330
        if hasattr(self, '_ignorelist'):
 
 
331
            return self._ignorelist
 
 
333
        l = bzrlib.DEFAULT_IGNORE[:]
 
 
334
        if self.has_filename(bzrlib.IGNORE_FILENAME):
 
 
335
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
 
 
336
            l.extend([line.rstrip("\n\r") for line in f.readlines()])
 
 
341
    def is_ignored(self, filename):
 
 
342
        r"""Check whether the filename matches an ignore pattern.
 
 
344
        Patterns containing '/' or '\' need to match the whole path;
 
 
345
        others match against only the last component.
 
 
347
        If the file is ignored, returns the pattern which caused it to
 
 
348
        be ignored, otherwise None.  So this can simply be used as a
 
 
349
        boolean if desired."""
 
 
351
        # TODO: Use '**' to match directories, and other extended
 
 
352
        # globbing stuff from cvs/rsync.
 
 
354
        # XXX: fnmatch is actually not quite what we want: it's only
 
 
355
        # approximately the same as real Unix fnmatch, and doesn't
 
 
356
        # treat dotfiles correctly and allows * to match /.
 
 
357
        # Eventually it should be replaced with something more
 
 
360
        for pat in self.get_ignore_list():
 
 
361
            if '/' in pat or '\\' in pat:
 
 
363
                # as a special case, you can put ./ at the start of a
 
 
364
                # pattern; this is good to match in the top-level
 
 
367
                if (pat[:2] == './') or (pat[:2] == '.\\'):
 
 
371
                if fnmatch.fnmatchcase(filename, newpat):
 
 
374
                if fnmatch.fnmatchcase(splitpath(filename)[-1], pat):
 
 
379
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
 
 
380
def get_conflicted_stem(path):
 
 
381
    for suffix in CONFLICT_SUFFIXES:
 
 
382
        if path.endswith(suffix):
 
 
383
            return path[:-len(suffix)]