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