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=None): 32 FileBase.__init__(self, store_dir or PREFERENCES_DIR) 33 self.user = user 34 35 def get(self, name, default=None): 36 37 """ 38 Return the value for 'name', with absent entries providing a default of 39 None or any indicated 'default'. 40 """ 41 42 try: 43 return self[name] 44 except KeyError: 45 return default 46 47 def get_all(self, names): 48 49 """ 50 Return a dictionary containing values for entries having the given 51 'names'. Absent entries for names are omitted without error. 52 """ 53 54 d = {} 55 for name in names: 56 value = self.get(name) 57 if value is not None: 58 d[name] = value 59 return d 60 61 def has_key(self, name): 62 63 "Return whether an entry exists for 'name'." 64 65 try: 66 self[name] 67 return True 68 except KeyError: 69 return False 70 71 def __getitem__(self, name): 72 73 "Return the value for 'name', raising a KeyError if absent." 74 75 filename = self.get_object_in_store(self.user, name) 76 if not filename or not exists(filename): 77 raise KeyError, name 78 79 f = open(filename) 80 try: 81 return f.read().strip() 82 finally: 83 f.close() 84 85 def __setitem__(self, name, value): 86 87 "Set for 'name' the given 'value'." 88 89 filename = self.get_object_in_store(self.user, name) 90 if not filename: 91 return False 92 93 f = open(filename, "w") 94 try: 95 f.write(value) 96 finally: 97 f.close() 98 fix_permissions(filename) 99 100 return True 101 102 # vim: tabstop=4 expandtab shiftwidth=4