16 |
# along with this program; if not, write to the Free Software |
# along with this program; if not, write to the Free Software |
17 |
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA |
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA |
18 |
""" Wrap a filesystem directory as an object """ |
""" Wrap a filesystem directory as an object """ |
19 |
|
|
20 |
|
from pax.backwards_compatibility import * |
21 |
|
from path import _base as Path_base, path as Path |
22 |
|
from TAL_File import TAL_File |
23 |
|
from Py_File import Py_File |
24 |
|
import os |
25 |
|
|
26 |
|
extensions = ( |
27 |
|
('.tal', TAL_File), |
28 |
|
('.py', Py_File), |
29 |
|
('.pyc', Py_File), |
30 |
|
) |
31 |
|
|
32 |
|
class Directory(object): |
33 |
|
""" Wrap a filesystem directory as an object """ |
34 |
|
def __init__(self, path=None): |
35 |
|
if path is None: |
36 |
|
path = os.getcwd() |
37 |
|
if not isinstance(path, Path): |
38 |
|
path = Path(path) |
39 |
|
self.__path = path |
40 |
|
self.__cache = {} |
41 |
|
|
42 |
|
def __getattr__(self, name): |
43 |
|
if not self.__cache.has_key(name): |
44 |
|
path = self.__path / name |
45 |
|
if path.isdir(): |
46 |
|
o = Directory(path) |
47 |
|
elif path.isfile(): |
48 |
|
for ext, reader in extensions: |
49 |
|
if path.endswith(ext): |
50 |
|
o = reader(name, path, self) |
51 |
|
break |
52 |
|
else: |
53 |
|
o = path.text() |
54 |
|
else: |
55 |
|
for ext, reader in extensions: |
56 |
|
epath = path + ext |
57 |
|
if epath.isfile(): |
58 |
|
o = reader(name, epath, self) |
59 |
|
break |
60 |
|
else: |
61 |
|
# file *REALLY* does not exist. Perhaps it is a listing mask? |
62 |
|
l = self.__path.listdir(name) |
63 |
|
if l: |
64 |
|
return [getattr(self, p.name) for p in l] |
65 |
|
raise AttributeError, name |
66 |
|
self.__cache[name] = o |
67 |
|
return self.__cache[name] |
68 |
|
|
69 |
|
def _ls(self, pattern): |
70 |
|
return [getattr(self, p.name) for p in self.__path.listdir(pattern)] |
71 |
|
|
72 |
|
def __repr__(self): |
73 |
|
return 'Directory(%s)' % Path_base.__repr__(self.__path) |