]> git.donarmstrong.com Git - neurodebian.git/blob - sphinx/sphinxext/feed/fsdict.py
few more tags, moved Christian up into "institutions" due to his VP position ;-)
[neurodebian.git] / sphinx / sphinxext / feed / fsdict.py
1 # −*− coding: UTF−8 −*−
2 from path import path
3 import os
4 import pickle
5 """
6 A class providing dictionary access to a folder.
7 cribbed from http://bitbucket.org/howthebodyworks/fsdict
8 """
9
10 def get_tmp_dir():
11     import tempfile
12     return tempfile.mkdtemp()
13     
14 class FSDict(dict):
15     """
16     provide dictionary access to a temp dir. I don't know why i didn't just use
17     shelve. I think I forgot it existed.
18     
19     N.B. the keys ordering here is FS-dependent and thus unlike to be the same as
20     with a real dict. beware.
21     """
22     
23     unclean_dirs = []
24     
25     def __init__(self, initval=[], work_dir=None, *args, **kwargs):
26         if work_dir is None:
27             work_dir = get_tmp_dir()
28         self.work_dir = path(work_dir)
29         if not self.work_dir.exists():
30             self.work_dir.mkdir()
31         for key, val in getattr(initval, 'iteritems', initval.__iter__)():
32             self[key] = val
33         self.unclean_dirs.append(self.work_dir)
34         super(FSDict, self).__init__(*args, **kwargs)
35     
36     def __setitem__(self, key, val, *args, **kwargs):
37         pickle.dump(val, open(self.work_dir/key, 'w'))
38     
39     def __getitem__(self, key, *args, **kwargs):
40         return pickle.load(open(self.work_dir/key, 'r'))
41     
42     def __repr__(self):
43         """
44         a hardline list of everything in the dict. may be long.
45         """
46         return repr(dict([(k, v) for k, v in self.iteritems()]))
47         
48     def __str__(self):
49         """
50         str is truncated somewhat.
51         """
52         if len(self.keys()):
53             return '{' + repr(self.keys()[0]) + ':' + repr(self[self.keys()[0]]) + ', ...'
54         else:
55             return super(FSDict, self).__str__()
56     
57     def keys(self, *args, **kwargs):
58         return [key for key in self.iterkeys()]
59     
60     def iterkeys(self, *args, **kwargs):
61         for f in self.work_dir.files():
62             yield str(self.work_dir.relpathto(f))
63         
64     def iteritems(self):
65         for key in self.iterkeys():
66             yield key, self[key]
67             
68     def itervalues(self):
69         for key in self.iterkeys():
70             yield self[key]
71             
72     def __delitem__(self, key, *args, **kwargs):
73         (self.work_dir/key).unlink()
74     
75     def values(self, *args, **kwargs):
76         return [self[key] for key in self.keys()]
77         
78     def cleanup(self):
79         self.work_dir.rmtree()
80     
81     @classmethod
82     def cleanup_all(cls):
83         for fsd in cls.unclean_dirs:
84             try:
85                 fsd.rmtree()
86             except OSError:
87                 pass
88     
89     def move(self, new_dir):
90         
91         try:
92             self.work_dir.move(new_dir)
93         except Exception, e:
94             raise
95         else:
96             self.work_dir = new_dir
97     
98     def __eq__(self, other):
99         """
100         when compared to a dict, equate equal if all keys and vals are equal
101         note, this is potentially expensive.
102         """
103         #duck type our way to sanity:
104         if not hasattr(other, 'keys'): return False
105         #OK, it's a dict-ish thing
106         try:
107             return all([self[key]==other[key] for key in other]) and \
108               len(self.keys())==len(other.keys())
109         except KeyError:
110             return False