1# Copyright (C) 2010 Google Inc. All rights reserved.
2#
3# Redistribution and use in source and binary forms, with or without
4# modification, are permitted provided that the following conditions are
5# met:
6#
7#     * Redistributions of source code must retain the above copyright
8# notice, this list of conditions and the following disclaimer.
9#     * Redistributions in binary form must reproduce the above
10# copyright notice, this list of conditions and the following disclaimer
11# in the documentation and/or other materials provided with the
12# distribution.
13#     * Neither the name of Google Inc. nor the names of its
14# contributors may be used to endorse or promote products derived from
15# this software without specific prior written permission.
16#
17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29"""Wrapper object for the file system / source tree."""
30
31from __future__ import with_statement
32
33import codecs
34import errno
35import exceptions
36import glob
37import os
38import shutil
39import tempfile
40import time
41
42from webkitpy.common.system import ospath
43
44class FileSystem(object):
45    """FileSystem interface for webkitpy.
46
47    Unless otherwise noted, all paths are allowed to be either absolute
48    or relative."""
49    def __init__(self):
50        self._sep = os.sep
51
52    def _get_sep(self):
53        return self._sep
54
55    sep = property(_get_sep, doc="pathname separator")
56
57    def abspath(self, path):
58        return os.path.abspath(path)
59
60    def basename(self, path):
61        """Wraps os.path.basename()."""
62        return os.path.basename(path)
63
64    def chdir(self, path):
65        """Wraps os.chdir()."""
66        return os.chdir(path)
67
68    def copyfile(self, source, destination):
69        """Copies the contents of the file at the given path to the destination
70        path."""
71        shutil.copyfile(source, destination)
72
73    def dirname(self, path):
74        """Wraps os.path.dirname()."""
75        return os.path.dirname(path)
76
77    def exists(self, path):
78        """Return whether the path exists in the filesystem."""
79        return os.path.exists(path)
80
81    def files_under(self, path, dirs_to_skip=[], file_filter=None):
82        """Return the list of all files under the given path in topdown order.
83
84        Args:
85            dirs_to_skip: a list of directories to skip over during the
86                traversal (e.g., .svn, resources, etc.)
87            file_filter: if not None, the filter will be invoked
88                with the filesystem object and the dirname and basename of
89                each file found. The file is included in the result if the
90                callback returns True.
91        """
92        def filter_all(fs, dirpath, basename):
93            return True
94
95        file_filter = file_filter or filter_all
96        files = []
97        if self.isfile(path):
98            if file_filter(self, self.dirname(path), self.basename(path)):
99                files.append(path)
100            return files
101
102        if self.basename(path) in dirs_to_skip:
103            return []
104
105        for (dirpath, dirnames, filenames) in os.walk(path):
106            for d in dirs_to_skip:
107                if d in dirnames:
108                    dirnames.remove(d)
109
110            for filename in filenames:
111                if file_filter(self, dirpath, filename):
112                    files.append(self.join(dirpath, filename))
113        return files
114
115    def getcwd(self):
116        """Wraps os.getcwd()."""
117        return os.getcwd()
118
119    def glob(self, path):
120        """Wraps glob.glob()."""
121        return glob.glob(path)
122
123    def isabs(self, path):
124        """Return whether the path is an absolute path."""
125        return os.path.isabs(path)
126
127    def isfile(self, path):
128        """Return whether the path refers to a file."""
129        return os.path.isfile(path)
130
131    def isdir(self, path):
132        """Return whether the path refers to a directory."""
133        return os.path.isdir(path)
134
135    def join(self, *comps):
136        """Return the path formed by joining the components."""
137        return os.path.join(*comps)
138
139    def listdir(self, path):
140        """Return the contents of the directory pointed to by path."""
141        return os.listdir(path)
142
143    def mkdtemp(self, **kwargs):
144        """Create and return a uniquely named directory.
145
146        This is like tempfile.mkdtemp, but if used in a with statement
147        the directory will self-delete at the end of the block (if the
148        directory is empty; non-empty directories raise errors). The
149        directory can be safely deleted inside the block as well, if so
150        desired.
151
152        Note that the object returned is not a string and does not support all of the string
153        methods. If you need a string, coerce the object to a string and go from there.
154        """
155        class TemporaryDirectory(object):
156            def __init__(self, **kwargs):
157                self._kwargs = kwargs
158                self._directory_path = tempfile.mkdtemp(**self._kwargs)
159
160            def __str__(self):
161                return self._directory_path
162
163            def __enter__(self):
164                return self._directory_path
165
166            def __exit__(self, type, value, traceback):
167                # Only self-delete if necessary.
168
169                # FIXME: Should we delete non-empty directories?
170                if os.path.exists(self._directory_path):
171                    os.rmdir(self._directory_path)
172
173        return TemporaryDirectory(**kwargs)
174
175    def maybe_make_directory(self, *path):
176        """Create the specified directory if it doesn't already exist."""
177        try:
178            os.makedirs(self.join(*path))
179        except OSError, e:
180            if e.errno != errno.EEXIST:
181                raise
182
183    def move(self, source, destination):
184        shutil.move(source, destination)
185
186    def mtime(self, path):
187        return os.stat(path).st_mtime
188
189    def normpath(self, path):
190        """Wraps os.path.normpath()."""
191        return os.path.normpath(path)
192
193    def open_binary_tempfile(self, suffix):
194        """Create, open, and return a binary temp file. Returns a tuple of the file and the name."""
195        temp_fd, temp_name = tempfile.mkstemp(suffix)
196        f = os.fdopen(temp_fd, 'wb')
197        return f, temp_name
198
199    def open_text_file_for_writing(self, path, append=False):
200        """Returns a file handle suitable for writing to."""
201        mode = 'w'
202        if append:
203            mode = 'a'
204        return codecs.open(path, mode, 'utf8')
205
206    def open_binary_file_for_reading(self, path):
207        return codecs.open(path, 'rb')
208
209    def read_binary_file(self, path):
210        """Return the contents of the file at the given path as a byte string."""
211        with file(path, 'rb') as f:
212            return f.read()
213
214    def read_text_file(self, path):
215        """Return the contents of the file at the given path as a Unicode string.
216
217        The file is read assuming it is a UTF-8 encoded file with no BOM."""
218        with codecs.open(path, 'r', 'utf8') as f:
219            return f.read()
220
221    def relpath(self, path, start='.'):
222        return ospath.relpath(path, start)
223
224    class _WindowsError(exceptions.OSError):
225        """Fake exception for Linux and Mac."""
226        pass
227
228    def remove(self, path, osremove=os.remove):
229        """On Windows, if a process was recently killed and it held on to a
230        file, the OS will hold on to the file for a short while.  This makes
231        attempts to delete the file fail.  To work around that, this method
232        will retry for a few seconds until Windows is done with the file."""
233        try:
234            exceptions.WindowsError
235        except AttributeError:
236            exceptions.WindowsError = FileSystem._WindowsError
237
238        retry_timeout_sec = 3.0
239        sleep_interval = 0.1
240        while True:
241            try:
242                osremove(path)
243                return True
244            except exceptions.WindowsError, e:
245                time.sleep(sleep_interval)
246                retry_timeout_sec -= sleep_interval
247                if retry_timeout_sec < 0:
248                    raise e
249
250    def rmtree(self, path):
251        """Delete the directory rooted at path, empty or no."""
252        shutil.rmtree(path, ignore_errors=True)
253
254    def read_binary_file(self, path):
255        """Return the contents of the file at the given path as a byte string."""
256        with file(path, 'rb') as f:
257            return f.read()
258
259    def read_text_file(self, path):
260        """Return the contents of the file at the given path as a Unicode string.
261
262        The file is read assuming it is a UTF-8 encoded file with no BOM."""
263        with codecs.open(path, 'r', 'utf8') as f:
264            return f.read()
265
266    def splitext(self, path):
267        """Return (dirname + os.sep + basename, '.' + ext)"""
268        return os.path.splitext(path)
269
270    def write_binary_file(self, path, contents):
271        """Write the contents to the file at the given location."""
272        with file(path, 'wb') as f:
273            f.write(contents)
274
275    def write_text_file(self, path, contents):
276        """Write the contents to the file at the given location.
277
278        The file is written encoded as UTF-8 with no BOM."""
279        with codecs.open(path, 'w', 'utf8') as f:
280            f.write(contents)
281