1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/imiptools/profile.py Mon Jan 12 23:07:33 2015 +0100
1.3 @@ -0,0 +1,66 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +User profile management.
1.8 +
1.9 +Copyright (C) 2015 Paul Boddie <paul@boddie.org.uk>
1.10 +
1.11 +This program is free software; you can redistribute it and/or modify it under
1.12 +the terms of the GNU General Public License as published by the Free Software
1.13 +Foundation; either version 3 of the License, or (at your option) any later
1.14 +version.
1.15 +
1.16 +This program is distributed in the hope that it will be useful, but WITHOUT
1.17 +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1.18 +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
1.19 +details.
1.20 +
1.21 +You should have received a copy of the GNU General Public License along with
1.22 +this program. If not, see <http://www.gnu.org/licenses/>.
1.23 +"""
1.24 +
1.25 +from imiptools.config import PREFERENCES_DIR
1.26 +from imiptools.filesys import fix_permissions, FileBase
1.27 +from os.path import exists, isdir
1.28 +from os import makedirs
1.29 +
1.30 +class Preferences(FileBase):
1.31 +
1.32 + "A simple preferences file manager."
1.33 +
1.34 + def __init__(self, user, store_dir=PREFERENCES_DIR):
1.35 + FileBase.__init__(self, store_dir)
1.36 + self.user = user
1.37 +
1.38 + def get(self, name, default=None):
1.39 + try:
1.40 + return self[name]
1.41 + except KeyError:
1.42 + return default
1.43 +
1.44 + def __getitem__(self, name):
1.45 + filename = self.get_object_in_store(self.user, name)
1.46 + if not filename or not exists(filename):
1.47 + raise KeyError, name
1.48 +
1.49 + f = open(filename)
1.50 + try:
1.51 + return f.read().strip()
1.52 + finally:
1.53 + f.close()
1.54 +
1.55 + def __setitem__(self, name, value):
1.56 + filename = self.get_object_in_store(self.user, name)
1.57 + if not filename:
1.58 + return False
1.59 +
1.60 + f = open(filename, "w")
1.61 + try:
1.62 + f.write(value)
1.63 + finally:
1.64 + f.close()
1.65 + fix_permissions(filename)
1.66 +
1.67 + return True
1.68 +
1.69 +# vim: tabstop=4 expandtab shiftwidth=4