Ready for mentors
[cgmail.git] / cGmail / lib / filedicthelper.py
blob3e28a252ed5f99cb8c4ec51f991be023ba07b97c
2 # Copyright (C) 2007 Marco Ferragina <marco.ferragina@gmail.com>
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 import os
20 from ConfigParser import MissingSectionHeaderError
22 from dicthelper import DictHelper, CannotSaveError, CorruptedConfiguration
23 from storagehandler import StorageHandler
25 class FileHandler(StorageHandler):
26 def __init__(self):
27 self.__file_path = os.path.expanduser("~/.config/cgmail/accounts.ini")
28 if not os.path.exists(self.__file_path):
29 try:
30 os.makedirs(os.path.expanduser("~/.config/cgmail"))
31 except OSError:
32 pass
33 try:
34 self.__data = open(self.__file_path).read()
35 self.__lines = self.__data.split('\n')
36 except IOError:
37 self.__lines = []
38 self.__count = 0
40 def readline(self):
41 if self.__count < len(self.__lines):
42 line = self.__lines[self.__count]
43 self.__count += 1
44 if not line:
45 return "\n"
46 return line
47 else:
48 return None
50 def write(self, data):
51 self.__f.write(data)
52 #f.close()
54 def get_new_writer(self):
55 self.__f = open(self.__file_path, "w")
56 os.chmod(self.__file_path, 0600)
57 return self
59 def close(self):
60 self.__f.close()
63 class FileDictHelper(DictHelper):
64 def __init__(self):
65 fh = FileHandler()
66 try:
67 DictHelper.__init__(self, fh)
68 except MissingSectionHeaderError:
69 fh = fh.get_new_writer()
70 fh.close()
71 raise CorruptedConfiguration
76 if __name__ == "__main__":
77 f = FileDictHelper()
78 print f.get_dicts()
79 f.add_dict({"user": "prova"})
80 print f.get_dicts()