1 # Copyright (C) 2010 Google Inc. All rights reserved.
3 # Redistribution and use in source and binary forms, with or without
4 # modification, are permitted provided that the following conditions are
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
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.
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.
29 """Wrapper object for the file system / source tree."""
31 from __future__ import with_statement
42 class FileSystem(object):
43 """FileSystem interface for webkitpy.
45 Unless otherwise noted, all paths are allowed to be either absolute
48 def basename(self, path):
49 """Wraps os.path.basename()."""
50 return os.path.basename(path)
52 def copyfile(self, source, destination):
53 """Copies the contents of the file at the given path to the destination
55 shutil.copyfile(source, destination)
57 def dirname(self, path):
58 """Wraps os.path.dirname()."""
59 return os.path.dirname(path)
61 def exists(self, path):
62 """Return whether the path exists in the filesystem."""
63 return os.path.exists(path)
65 def files_under(self, path, dirs_to_skip=[], file_filter=None):
66 """Return the list of all files under the given path in topdown order.
69 dirs_to_skip: a list of directories to skip over during the
70 traversal (e.g., .svn, resources, etc.)
71 file_filter: if not None, the filter will be invoked
72 with the filesystem object and the dirname and basename of
73 each file found. The file is included in the result if the
74 callback returns True.
76 def filter_all(fs, dirpath, basename):
79 file_filter = file_filter or filter_all
82 if file_filter(self, self.dirname(path), self.basename(path)):
86 if self.basename(path) in dirs_to_skip:
89 for (dirpath, dirnames, filenames) in os.walk(path):
90 for d in dirs_to_skip:
94 for filename in filenames:
95 if file_filter(self, dirpath, filename):
96 files.append(self.join(dirpath, filename))
100 """Wraps glob.glob()."""
101 return glob.glob(path)
103 def isfile(self, path):
104 """Return whether the path refers to a file."""
105 return os.path.isfile(path)
107 def isdir(self, path):
108 """Return whether the path refers to a directory."""
109 return os.path.isdir(path)
111 def join(self, *comps):
112 """Return the path formed by joining the components."""
113 return os.path.join(*comps)
115 def listdir(self, path):
116 """Return the contents of the directory pointed to by path."""
117 return os.listdir(path)
119 def mkdtemp(self, **kwargs):
120 """Create and return a uniquely named directory.
122 This is like tempfile.mkdtemp, but if used in a with statement
123 the directory will self-delete at the end of the block (if the
124 directory is empty; non-empty directories raise errors). The
125 directory can be safely deleted inside the block as well, if so
128 Note that the object returned is not a string and does not support all of the string
129 methods. If you need a string, coerce the object to a string and go from there.
131 class TemporaryDirectory(object):
132 def __init__(self, **kwargs):
133 self._kwargs = kwargs
134 self._directory_path = tempfile.mkdtemp(**self._kwargs)
137 return self._directory_path
140 return self._directory_path
142 def __exit__(self, type, value, traceback):
143 # Only self-delete if necessary.
145 # FIXME: Should we delete non-empty directories?
146 if os.path.exists(self._directory_path):
147 os.rmdir(self._directory_path)
149 return TemporaryDirectory(**kwargs)
151 def maybe_make_directory(self, *path):
152 """Create the specified directory if it doesn't already exist."""
154 os.makedirs(self.join(*path))
156 if e.errno != errno.EEXIST:
159 def move(self, src, dest):
160 shutil.move(src, dest)
162 def normpath(self, path):
163 """Wraps os.path.normpath()."""
164 return os.path.normpath(path)
166 def open_binary_tempfile(self, suffix):
167 """Create, open, and return a binary temp file. Returns a tuple of the file and the name."""
168 temp_fd, temp_name = tempfile.mkstemp(suffix)
169 f = os.fdopen(temp_fd, 'wb')
172 def read_binary_file(self, path):
173 """Return the contents of the file at the given path as a byte string."""
174 with file(path, 'rb') as f:
177 def read_text_file(self, path):
178 """Return the contents of the file at the given path as a Unicode string.
180 The file is read assuming it is a UTF-8 encoded file with no BOM."""
181 with codecs.open(path, 'r', 'utf8') as f:
184 class _WindowsError(exceptions.OSError):
185 """Fake exception for Linux and Mac."""
188 def remove(self, path, osremove=os.remove):
189 """On Windows, if a process was recently killed and it held on to a
190 file, the OS will hold on to the file for a short while. This makes
191 attempts to delete the file fail. To work around that, this method
192 will retry for a few seconds until Windows is done with the file."""
194 exceptions.WindowsError
195 except AttributeError:
196 exceptions.WindowsError = FileSystem._WindowsError
198 retry_timeout_sec = 3.0
204 except exceptions.WindowsError, e:
205 time.sleep(sleep_interval)
206 retry_timeout_sec -= sleep_interval
207 if retry_timeout_sec < 0:
210 def rmtree(self, path):
211 """Delete the directory rooted at path, empty or no."""
212 shutil.rmtree(path, ignore_errors=True)
214 def read_binary_file(self, path):
215 """Return the contents of the file at the given path as a byte string."""
216 with file(path, 'rb') as f:
219 def read_text_file(self, path):
220 """Return the contents of the file at the given path as a Unicode string.
222 The file is read assuming it is a UTF-8 encoded file with no BOM."""
223 with codecs.open(path, 'r', 'utf8') as f:
226 def splitext(self, path):
227 """Return (dirname + os.sep + basename, '.' + ext)"""
228 return os.path.splitext(path)
230 def write_binary_file(self, path, contents):
231 """Write the contents to the file at the given location."""
232 with file(path, 'wb') as f:
235 def write_text_file(self, path, contents):
236 """Write the contents to the file at the given location.
238 The file is written encoded as UTF-8 with no BOM."""
239 with codecs.open(path, 'w', 'utf8') as f: