9b8848545e2823a639a3765eb670989a6351402a
[invirt/packages/python-routefs.git] / routefs / dictfs.py
1 """
2 DictFS allows you to easily create read-only filesystems when the
3 file tree is known in advance.
4
5 To create your own DictFS descendent, simply override the files
6 property, which can be created either using the property
7 decorator, or just a simple assignment.
8
9 A dictionary represents a directory, with keys corresponding to
10 file names and the values corresponding to the file contents.
11 """
12
13 import routefs
14 from routes import Mapper
15 import os
16
17 class DictFS(routefs.RouteFS):
18     controllers = ['handler']
19     
20     @property
21     def files(self):
22         """
23         This property should be overridden in your DictFS descendant
24         """
25         return dict()
26     
27     @property
28     def map(self):
29         m = Mapper()
30         
31         m.connect('*path', controller='handler')
32         
33         return m
34     
35     def handler(self, path, **kwargs):
36         if path != '':
37             elements = path.split(os.path.sep)
38         else:
39             elements = []
40         
41         try:
42             tree = self.files
43             for elt in elements:
44                 tree = tree[elt]
45         except KeyError:
46             return
47         
48         if type(tree) is dict:
49             return tree.keys()
50         else:
51             return tree