Add DictFS, for when the filesystem tree is known in advance
[invirt/packages/python-routefs.git] / routefs / dictfs.py
1 #!/usr/bin/python
2
3 """
4 DictFS allows you to easily create read-only filesystems when the
5 file tree is known in advance.
6
7 To create your own DictFS descendent, simply override the files
8 property, which can be created either using the property
9 decorator, or just a simple assignment.
10
11 A dictionary represents a directory, with keys corresponding to
12 file names and the values corresponding to the file contents.
13 """
14
15 import routefs
16 from routes import Mapper
17 import os
18
19 class DictFS(routefs.RouteFS):
20     @property
21     def files(self):
22         """
23         This property should be overridden in your DictFS descendant
24         """
25         return dict(Hello='World',
26                     Directory=dict(a='a', b='b', c=routefs.Symlink('a')))
27     
28     def make_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 routefs.Directory(tree.keys())
50         else:
51             return tree
52
53 if __name__ == '__main__':
54     routefs.main(DictFS)