1 #!/usr/bin/env python 2 3 """ 4 User profile management. 5 6 Copyright (C) 2015 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from imiptools.config import PREFERENCES_DIR 23 from imiptools.filesys import fix_permissions, FileBase 24 from os.path import exists, isdir 25 from os import makedirs 26 27 class Preferences(FileBase): 28 29 "A simple preferences file manager." 30 31 def __init__(self, user, store_dir=PREFERENCES_DIR): 32 FileBase.__init__(self, store_dir) 33 self.user = user 34 35 def get(self, name, default=None): 36 try: 37 return self[name] 38 except KeyError: 39 return default 40 41 def __getitem__(self, name): 42 filename = self.get_object_in_store(self.user, name) 43 if not filename or not exists(filename): 44 raise KeyError, name 45 46 f = open(filename) 47 try: 48 return f.read().strip() 49 finally: 50 f.close() 51 52 def __setitem__(self, name, value): 53 filename = self.get_object_in_store(self.user, name) 54 if not filename: 55 return False 56 57 f = open(filename, "w") 58 try: 59 f.write(value) 60 finally: 61 f.close() 62 fix_permissions(filename) 63 64 return True 65 66 # vim: tabstop=4 expandtab shiftwidth=4