| OLD | NEW |
| 1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. | 1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be | 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. | 3 # found in the LICENSE file. |
| 4 | 4 |
| 5 import os | 5 import os |
| 6 | 6 |
| 7 class LocalFetcher(object): | 7 class LocalFetcher(object): |
| 8 """Class to fetch resources from local filesystem. | 8 """Class to fetch resources from local filesystem. |
| 9 """ | 9 """ |
| 10 def __init__(self, base_path): | 10 def __init__(self, base_path): |
| 11 self._base_path = self._ConvertToFilepath(base_path) | 11 self._base_path = self._ConvertToFilepath(base_path) |
| 12 | 12 |
| 13 def _ConvertToFilepath(self, path): | 13 def _ConvertToFilepath(self, path): |
| 14 return path.replace('/', os.sep) | 14 return path.replace('/', os.sep) |
| 15 | 15 |
| 16 class _Response(object): | 16 class _Response(object): |
| 17 """Response object matching what is returned from urlfetch. | 17 """Response object matching what is returned from urlfetch. |
| 18 """ | 18 """ |
| 19 def __init__(self, content): | 19 def __init__(self, content): |
| 20 self.content = content | 20 self.content = content |
| 21 self.headers = {} | 21 self.headers = {} |
| 22 | 22 |
| 23 def _ReadFile(self, filename): | 23 def _ReadFile(self, filename): |
| 24 path = os.path.join(self._base_path, filename) | 24 path = os.path.join(self._base_path, filename) |
| 25 with open(path, 'r') as f: | 25 with open(path, 'r') as f: |
| 26 return f.read() | 26 return f.read() |
| 27 | 27 |
| 28 def ListDirectory(self, directory, recursive=False): |
| 29 """Returns a list of files in the directory with |_base_path| removed. |
| 30 """ |
| 31 all_files = [] |
| 32 if recursive: |
| 33 for path, subdirs, files in os.walk( |
| 34 os.path.join(self._base_path, self._ConvertToFilepath(directory))): |
| 35 for filename in files: |
| 36 full_path = os.path.join(path, filename) |
| 37 if os.path.isdir(full_path): |
| 38 all_files.append(full_path + '/') |
| 39 else: |
| 40 all_files.append(full_path) |
| 41 else: |
| 42 all_files.extend(os.listdir(os.path.join(self._base_path, directory))) |
| 43 return self._Response( |
| 44 [x.replace(self._base_path + os.sep, '') for x in all_files]) |
| 45 |
| 28 def FetchResource(self, path): | 46 def FetchResource(self, path): |
| 29 # A response object is returned to match the behavior of urlfetch. | 47 # A response object is returned to match the behavior of urlfetch. |
| 30 # See: developers.google.com/appengine/docs/python/urlfetch/responseobjects | 48 # See: developers.google.com/appengine/docs/python/urlfetch/responseobjects |
| 31 return self._Response(self._ReadFile(self._ConvertToFilepath(path))) | 49 return self._Response(self._ReadFile(self._ConvertToFilepath(path))) |
| OLD | NEW |