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