Home | History | Annotate | Download | only in system
      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 
     31 import codecs
     32 import errno
     33 import exceptions
     34 import glob
     35 import hashlib
     36 import os
     37 import shutil
     38 import sys
     39 import tempfile
     40 import time
     41 
     42 class FileSystem(object):
     43     """FileSystem interface for webkitpy.
     44 
     45     Unless otherwise noted, all paths are allowed to be either absolute
     46     or relative."""
     47     sep = os.sep
     48     pardir = os.pardir
     49 
     50     def abspath(self, path):
     51         return os.path.abspath(path)
     52 
     53     def realpath(self, path):
     54         return os.path.realpath(path)
     55 
     56     def path_to_module(self, module_name):
     57         """A wrapper for all calls to __file__ to allow easy unit testing."""
     58         # FIXME: This is the only use of sys in this file. It's possible this function should move elsewhere.
     59         return sys.modules[module_name].__file__  # __file__ is always an absolute path.
     60 
     61     def expanduser(self, path):
     62         return os.path.expanduser(path)
     63 
     64     def basename(self, path):
     65         return os.path.basename(path)
     66 
     67     def chdir(self, path):
     68         return os.chdir(path)
     69 
     70     def copyfile(self, source, destination):
     71         shutil.copyfile(source, destination)
     72 
     73     def dirname(self, path):
     74         return os.path.dirname(path)
     75 
     76     def exists(self, path):
     77         return os.path.exists(path)
     78 
     79     def files_under(self, path, dirs_to_skip=[], file_filter=None):
     80         """Return the list of all files under the given path in topdown order.
     81 
     82         Args:
     83             dirs_to_skip: a list of directories to skip over during the
     84                 traversal (e.g., .svn, resources, etc.)
     85             file_filter: if not None, the filter will be invoked
     86                 with the filesystem object and the dirname and basename of
     87                 each file found. The file is included in the result if the
     88                 callback returns True.
     89         """
     90         def filter_all(fs, dirpath, basename):
     91             return True
     92 
     93         file_filter = file_filter or filter_all
     94         files = []
     95         if self.isfile(path):
     96             if file_filter(self, self.dirname(path), self.basename(path)):
     97                 files.append(path)
     98             return files
     99 
    100         if self.basename(path) in dirs_to_skip:
    101             return []
    102 
    103         for (dirpath, dirnames, filenames) in os.walk(path):
    104             for d in dirs_to_skip:
    105                 if d in dirnames:
    106                     dirnames.remove(d)
    107 
    108             for filename in filenames:
    109                 if file_filter(self, dirpath, filename):
    110                     files.append(self.join(dirpath, filename))
    111         return files
    112 
    113     def getcwd(self):
    114         return os.getcwd()
    115 
    116     def glob(self, path):
    117         return glob.glob(path)
    118 
    119     def isabs(self, path):
    120         return os.path.isabs(path)
    121 
    122     def isfile(self, path):
    123         return os.path.isfile(path)
    124 
    125     def isdir(self, path):
    126         return os.path.isdir(path)
    127 
    128     def join(self, *comps):
    129         return os.path.join(*comps)
    130 
    131     def listdir(self, path):
    132         return os.listdir(path)
    133 
    134     def mkdtemp(self, **kwargs):
    135         """Create and return a uniquely named directory.
    136 
    137         This is like tempfile.mkdtemp, but if used in a with statement
    138         the directory will self-delete at the end of the block (if the
    139         directory is empty; non-empty directories raise errors). The
    140         directory can be safely deleted inside the block as well, if so
    141         desired.
    142 
    143         Note that the object returned is not a string and does not support all of the string
    144         methods. If you need a string, coerce the object to a string and go from there.
    145         """
    146         class TemporaryDirectory(object):
    147             def __init__(self, **kwargs):
    148                 self._kwargs = kwargs
    149                 self._directory_path = tempfile.mkdtemp(**self._kwargs)
    150 
    151             def __str__(self):
    152                 return self._directory_path
    153 
    154             def __enter__(self):
    155                 return self._directory_path
    156 
    157             def __exit__(self, type, value, traceback):
    158                 # Only self-delete if necessary.
    159 
    160                 # FIXME: Should we delete non-empty directories?
    161                 if os.path.exists(self._directory_path):
    162                     os.rmdir(self._directory_path)
    163 
    164         return TemporaryDirectory(**kwargs)
    165 
    166     def maybe_make_directory(self, *path):
    167         """Create the specified directory if it doesn't already exist."""
    168         try:
    169             os.makedirs(self.join(*path))
    170         except OSError, e:
    171             if e.errno != errno.EEXIST:
    172                 raise
    173 
    174     def move(self, source, destination):
    175         shutil.move(source, destination)
    176 
    177     def mtime(self, path):
    178         return os.stat(path).st_mtime
    179 
    180     def normpath(self, path):
    181         return os.path.normpath(path)
    182 
    183     def open_binary_tempfile(self, suffix):
    184         """Create, open, and return a binary temp file. Returns a tuple of the file and the name."""
    185         temp_fd, temp_name = tempfile.mkstemp(suffix)
    186         f = os.fdopen(temp_fd, 'wb')
    187         return f, temp_name
    188 
    189     def open_binary_file_for_reading(self, path):
    190         return codecs.open(path, 'rb')
    191 
    192     def read_binary_file(self, path):
    193         """Return the contents of the file at the given path as a byte string."""
    194         with file(path, 'rb') as f:
    195             return f.read()
    196 
    197     def write_binary_file(self, path, contents):
    198         with file(path, 'wb') as f:
    199             f.write(contents)
    200 
    201     def open_text_file_for_reading(self, path):
    202         # Note: There appears to be an issue with the returned file objects
    203         # not being seekable. See http://stackoverflow.com/questions/1510188/can-seek-and-tell-work-with-utf-8-encoded-documents-in-python .
    204         return codecs.open(path, 'r', 'utf8')
    205 
    206     def open_text_file_for_writing(self, path):
    207         return codecs.open(path, 'w', 'utf8')
    208 
    209     def read_text_file(self, path):
    210         """Return the contents of the file at the given path as a Unicode string.
    211 
    212         The file is read assuming it is a UTF-8 encoded file with no BOM."""
    213         with codecs.open(path, 'r', 'utf8') as f:
    214             return f.read()
    215 
    216     def write_text_file(self, path, contents):
    217         """Write the contents to the file at the given location.
    218 
    219         The file is written encoded as UTF-8 with no BOM."""
    220         with codecs.open(path, 'w', 'utf8') as f:
    221             f.write(contents)
    222 
    223     def sha1(self, path):
    224         contents = self.read_binary_file(path)
    225         return hashlib.sha1(contents).hexdigest()
    226 
    227     def relpath(self, path, start='.'):
    228         return os.path.relpath(path, start)
    229 
    230     class _WindowsError(exceptions.OSError):
    231         """Fake exception for Linux and Mac."""
    232         pass
    233 
    234     def remove(self, path, osremove=os.remove):
    235         """On Windows, if a process was recently killed and it held on to a
    236         file, the OS will hold on to the file for a short while.  This makes
    237         attempts to delete the file fail.  To work around that, this method
    238         will retry for a few seconds until Windows is done with the file."""
    239         try:
    240             exceptions.WindowsError
    241         except AttributeError:
    242             exceptions.WindowsError = FileSystem._WindowsError
    243 
    244         retry_timeout_sec = 3.0
    245         sleep_interval = 0.1
    246         while True:
    247             try:
    248                 osremove(path)
    249                 return True
    250             except exceptions.WindowsError, e:
    251                 time.sleep(sleep_interval)
    252                 retry_timeout_sec -= sleep_interval
    253                 if retry_timeout_sec < 0:
    254                     raise e
    255 
    256     def rmtree(self, path):
    257         """Delete the directory rooted at path, whether empty or not."""
    258         shutil.rmtree(path, ignore_errors=True)
    259 
    260     def copytree(self, source, destination):
    261         shutil.copytree(source, destination)
    262 
    263     def split(self, path):
    264         """Return (dirname, basename + '.' + ext)"""
    265         return os.path.split(path)
    266 
    267     def splitext(self, path):
    268         """Return (dirname + os.sep + basename, '.' + ext)"""
    269         return os.path.splitext(path)
    270