Coverage for tatlin/conf/config.py: 100%
37 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-03-20 05:56 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-03-20 05:56 +0000
1from configparser import ConfigParser, NoSectionError, NoOptionError
4class Config(object):
5 """
6 Read and write Tatlin configuration.
7 """
9 def __init__(self, fname):
10 self.defaults = {
11 # makerbot thing-o-matic platform size
12 "machine.platform_w": 120,
13 "machine.platform_d": 100,
14 "machine.platform_offset_x": None,
15 "machine.platform_offset_y": None,
16 "machine.platform_offset_z": None,
17 "ui.recent_files": None,
18 "ui.window_w": 640,
19 "ui.window_h": 700,
20 "ui.gcode_2d": False,
21 }
23 self.fname = fname
24 self.config = ConfigParser()
25 self.config.read(self.fname)
27 def read(self, key, conv=None):
28 val = self._read_file(key, conv)
29 if val is None:
30 val = self.defaults[key]
32 return val
34 def _read_file(self, key, conv):
35 section, option = self._parse_specifier(key)
36 try:
37 if conv:
38 val = conv(self.config.get(section, option))
39 else:
40 val = self.config.get(section, option)
41 except (NoSectionError, NoOptionError, ValueError):
42 val = None
43 return val
45 def write(self, key, val):
46 section, option = self._parse_specifier(key)
47 if not self.config.has_section(section):
48 self.config.add_section(section)
49 if isinstance(val, int):
50 val = str(val)
51 self.config.set(section, option, val)
53 def commit(self):
54 with open(self.fname, "w") as conf_file:
55 self.config.write(conf_file)
57 def _parse_specifier(self, spec):
58 parts = spec.split(".", 1)
59 if len(parts) < 2:
60 section, option = "general", parts[0]
61 else:
62 section, option = parts
63 return (section, option)