|
|
1.1 root 1: #!/usr/bin/env python
2: #
3: # Class and helper functions for handling (Hatari) INI style
4: # configuration files: loading, saving, setting/getting variables,
5: # mapping them to sections, listing changes
6: #
1.1.1.4 ! root 7: # Copyright (C) 2008-2012 by Eero Tamminen
1.1 root 8: #
9: # This program is free software; you can redistribute it and/or modify
10: # it under the terms of the GNU General Public License as published by
11: # the Free Software Foundation; either version 2 of the License, or
12: # (at your option) any later version.
13: #
14: # This program is distributed in the hope that it will be useful,
15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17: # GNU General Public License for more details.
18:
19: import os
1.1.1.4 ! root 20: # mapping from Hatari config variable name to type id (Bool, Int, String)
! 21: from conftypes import conftypes
1.1 root 22:
23: # ------------------------------------------------------
24: # Helper functions for type safe Hatari configuration variable access.
25: # Map booleans, integers and strings to Python types, and back to strings.
26:
27: def value_to_text(key, value):
28: "value_to_text(key, value) -> text, convert Python type to string"
1.1.1.4 ! root 29: assert(key in conftypes)
1.1 root 30: valtype = type(value)
31: if valtype == bool:
1.1.1.4 ! root 32: assert(conftypes[key] == "Bool")
1.1 root 33: if value:
34: text = "TRUE"
35: else:
36: text = "FALSE"
37: elif valtype == int:
1.1.1.4 ! root 38: assert(conftypes[key] == "Int")
1.1 root 39: text = str(value)
40: else:
1.1.1.4 ! root 41: assert(conftypes[key] == "String")
1.1 root 42: if value == None:
43: text = ""
44: else:
45: text = value
46: return text
47:
48: def text_to_value(text):
49: "text_to_value(text) -> value, convert INI file values to real types"
50: # bool?
51: upper = text.upper()
52: if upper == "FALSE":
53: value = False
54: elif upper == "TRUE":
55: value = True
56: else:
57: try:
58: # integer?
59: value = int(text)
60: except ValueError:
61: # string
62: value = text
63: return value
64:
65:
66: # ------------------------------------------------------
67: # Handle INI style configuration files as used by Hatari
68:
69: class ConfigStore:
1.1.1.2 root 70: def __init__(self, userconfdir, defaults = {}, miss_is_error = True):
71: "ConfigStore(userconfdir, fgfile[,defaults,miss_is_error])"
1.1 root 72: self.defaults = defaults
1.1.1.2 root 73: self.userpath = self._get_full_userpath(userconfdir)
1.1 root 74: self.miss_is_error = miss_is_error
1.1.1.2 root 75:
76: def _get_full_userpath(self, leafdir):
77: "get_userpath(leafdir) -> config file default save path from HOME, CWD or their subdir"
78: # user's hatari.cfg can be in home or current work dir,
79: # current dir is used only if $HOME fails
80: for path in (os.getenv("HOME"), os.getenv("HOMEPATH"), os.getcwd()):
81: if path and os.path.exists(path) and os.path.isdir(path):
82: if leafdir:
83: hpath = "%s%c%s" % (path, os.path.sep, leafdir)
84: if os.path.exists(hpath) and os.path.isdir(hpath):
85: return hpath
86: return path
87: return None
88:
89: def get_filepath(self, filename):
90: "get_filepath(filename) -> return correct full path to config file"
91: # user config has preference over system one
92: for path in (self.userpath, os.getenv("HATARI_SYSTEM_CONFDIR")):
93: if path:
94: file = "%s%c%s" % (path, os.path.sep, filename)
95: if os.path.isfile(file):
96: return file
97: # writing needs path name although it's missing for reading
98: return "%s%c%s" % (self.userpath, os.path.sep, filename)
1.1 root 99:
100: def load(self, path):
1.1.1.2 root 101: "load(path) -> load given configuration file"
102: if os.path.isfile(path):
1.1 root 103: sections = self._read(path)
104: if sections:
105: self.sections = sections
106: else:
1.1.1.3 root 107: print("ERROR: configuration file loading failed!")
1.1 root 108: return
109: else:
1.1.1.3 root 110: print("WARNING: configuration file missing!")
1.1.1.2 root 111: if self.defaults:
1.1.1.3 root 112: print("-> using dummy 'defaults'.")
1.1 root 113: self.sections = self.defaults
114: self.path = path
1.1.1.2 root 115: self.cfgfile = os.path.basename(path)
1.1 root 116: self.original = self.get_checkpoint()
117: self.changed = False
118:
119: def is_loaded(self):
120: "is_loaded() -> True if configuration loading succeeded"
121: if self.sections:
122: return True
123: return False
124:
125: def get_path(self):
126: "get_path() -> configuration file path"
127: return self.path
128:
129: def _read(self, path):
130: "_read(path) -> (all keys, section2key mappings)"
1.1.1.3 root 131: print("Reading configuration file '%s'..." % path)
1.1 root 132: config = open(path, "r")
133: if not config:
134: return ({}, {})
135: name = "[_orphans_]"
136: seckeys = {}
137: sections = {}
138: for line in config.readlines():
139: line = line.strip()
140: if not line or line[0] == '#':
141: continue
142: if line[0] == '[':
143: if line in sections:
1.1.1.3 root 144: print("WARNING: section '%s' twice in configuration" % line)
1.1 root 145: if seckeys:
146: sections[name] = seckeys
147: seckeys = {}
148: name = line
149: continue
150: if line.find('=') < 0:
1.1.1.3 root 151: print("WARNING: line without key=value pair:\n%s" % line)
1.1 root 152: continue
153: key, text = [string.strip() for string in line.split('=')]
154: seckeys[key] = text_to_value(text)
155: if seckeys:
156: sections[name] = seckeys
157: return sections
158:
159: def get_checkpoint(self):
160: "get_checkpoint() -> checkpoint, get the state of variables at this point"
161: checkpoint = {}
162: for section in self.sections.keys():
163: checkpoint[section] = self.sections[section].copy()
164: return checkpoint
165:
166: def get_checkpoint_changes(self, checkpoint):
167: "get_checkpoint_changes() -> list of (key, value) pairs for later changes"
168: changed = []
169: if not self.changed:
170: return changed
171: for section in self.sections.keys():
172: if section not in checkpoint:
173: for key, value in self.sections[section].items():
174: changed.append((key, value))
175: continue
176: for key, value in self.sections[section].items():
177: if (key not in checkpoint[section] or
178: value != checkpoint[section][key]):
179: text = value_to_text(key, value)
180: changed.append(("%s.%s" % (section, key), text))
181: return changed
182:
183: def revert_to_checkpoint(self, checkpoint):
184: "revert_to_checkpoint(checkpoint), revert to given checkpoint"
185: self.sections = checkpoint
186:
187: def get(self, section, key):
188: return self.sections[section][key]
189:
190: def set(self, section, key, value):
191: "set(section,key,value), set given key to given section"
192: if section not in self.sections:
193: if self.miss_is_error:
1.1.1.3 root 194: raise AttributeError("no section '%s'" % section)
1.1 root 195: self.sections[section] = {}
196: if key not in self.sections[section]:
197: if self.miss_is_error:
1.1.1.3 root 198: raise AttributeError("key '%s' not in section '%s'" % (key, section))
1.1 root 199: self.sections[section][key] = value
200: self.changed = True
201: elif self.sections[section][key] != value:
202: self.changed = True
203: self.sections[section][key] = value
204:
205: def is_changed(self):
206: "is_changed() -> True if current configuration is changed"
207: return self.changed
208:
209: def get_changes(self):
210: "get_changes(), return (key, value) list for each changed config option"
211: return self.get_checkpoint_changes(self.original)
212:
213: def write(self, fileobj):
214: "write(fileobj), write current configuration to given file object"
1.1.1.3 root 215: sections = list(self.sections.keys())
1.1 root 216: sections.sort()
217: for name in sections:
218: fileobj.write("%s\n" % name)
1.1.1.3 root 219: keys = list(self.sections[name].keys())
1.1 root 220: keys.sort()
221: for key in keys:
222: value = value_to_text(key, self.sections[name][key])
223: fileobj.write("%s = %s\n" % (key, value))
224: fileobj.write("\n")
225:
226: def save(self):
227: "save() -> path, if configuration changed, save it"
228: if not self.changed:
1.1.1.3 root 229: print("No configuration changes to save, skipping")
1.1 root 230: return None
1.1.1.2 root 231: fileobj = None
232: if self.path:
233: try:
234: fileobj = open(self.path, "w")
235: except:
236: pass
237: if not fileobj:
1.1.1.3 root 238: print("WARNING: non-existing/writable configuration file, creating a new one...")
1.1.1.2 root 239: if not os.path.exists(self.userpath):
240: os.makedirs(self.userpath)
241: self.path = "%s%c%s" % (self.userpath, os.path.sep, self.cfgfile)
242: fileobj = open(self.path, "w")
1.1 root 243: if not fileobj:
1.1.1.3 root 244: print("ERROR: opening '%s' for saving failed" % self.path)
1.1 root 245: return None
246: self.write(fileobj)
1.1.1.3 root 247: print("Saved configuration file:", self.path)
1.1 root 248: self.changed = False
1.1.1.2 root 249: return self.path
1.1 root 250:
251: def save_as(self, path):
252: "save_as(path) -> path, save configuration to given file and select it"
253: assert(path)
254: if not os.path.exists(os.path.dirname(path)):
255: os.makedirs(os.path.dirname(path))
256: self.path = path
257: self.changed = True
1.1.1.2 root 258: return self.save()
1.1 root 259:
260: def save_tmp(self, path):
261: "save_tmp(path) -> path, save configuration to given file without selecting it"
262: if not os.path.exists(os.path.dirname(path)):
263: os.makedirs(os.path.dirname(path))
264: fileobj = open(path, "w")
265: if not fileobj:
1.1.1.3 root 266: print("ERROR: opening '%s' for saving failed" % path)
1.1 root 267: return None
268: self.write(fileobj)
1.1.1.3 root 269: print("Saved temporary configuration file:", path)
1.1 root 270: return path
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.