]> git.phdru.name Git - m_lib.git/blob - m_lib/flad/fladc.py
Fix exceptions for Py3 compatibility
[m_lib.git] / m_lib / flad / fladc.py
1 """
2    Flat ASCII Database to implement VERY simple config files.
3 """
4
5
6 from m_lib.flad import flad, fladm
7
8
9 from .flad import checking_error
10 class error(checking_error):
11     # Too many records
12     pass
13
14
15 class Flad_Conf(dict):
16    """
17       FLAD config is just FLAD Database with exactly ONE record.
18       Flad_Conf objects are just UserDicts.
19    """
20    def __init__(self, must_keys = None, other_keys = None):
21       dict.__init__(self)
22
23       self.must_keys = must_keys
24       self.other_keys = other_keys
25
26
27    def __make_db(self):
28       if self.must_keys:
29          db = fladm.Flad_WithMustKeys(check_record, self.must_keys, self.other_keys)
30       else:
31          db = flad.Flad()
32
33       return db
34
35
36    def load_file(self, f):
37       db = self.__make_db()
38       db.load_file(f)
39
40       if len(db) != 1:
41          raise error("incorrect number of records in config file `%s'; expected 1, got %d" % (str(f), len(db)))
42
43       self.data = db[0]
44
45
46    def load_from_file(self, f):
47       db = self.__make_db()
48       db.load_from_file(f)
49
50       if len(db) != 1:
51          raise error("incorrect number of records in config file `%s'; expected 1, got %d" % (str(f), len(db)))
52
53       self.data = db[0]
54
55
56    def store_to_file(self, f):
57       db = self.__make_db()
58       db.append(self.data)
59       db.store_to_file(f)
60
61
62 def check_record(data, record): # Only allow append 1 record
63    return len(data) == 0
64
65
66 def load_file(f, must_keys = None, other_keys = None):
67    """
68       Create a database object and load it from file
69    """
70
71    db = Flad_Conf(must_keys, other_keys)
72    db.load_file(f)
73
74    return db
75
76
77 def load_from_file(f, must_keys = None, other_keys = None):
78    """
79       Create a database object and load it from file
80    """
81
82    db = Flad_Conf(must_keys, other_keys)
83    db.load_from_file(f)
84
85    return db