| 1 |
import os.path |
| 2 |
import copy as copyModule |
| 3 |
try: |
| 4 |
from ConfigParser import ConfigParser |
| 5 |
except ImportError: |
| 6 |
from configparser import ConfigParser |
| 7 |
import re |
| 8 |
from tokenize import Number |
| 9 |
import types |
| 10 |
try: |
| 11 |
from StringIO import StringIO |
| 12 |
except ImportError: |
| 13 |
from io import StringIO |
| 14 |
from .compat import PY2 |
| 15 |
|
| 16 |
|
| 17 |
numberRE = re.compile(Number) |
| 18 |
complexNumberRE = re.compile( |
| 19 |
r'[\(]*' + Number + r'[ \t]*\+[ \t]*' + Number + r'[\)]*') |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
def mergeNestedDictionaries(dict1, dict2, copy=False, deepcopy=False): |
| 26 |
"""Recursively merge the values of dict2 into dict1. |
| 27 |
|
| 28 |
This little function is very handy for selectively overriding settings in a |
| 29 |
settings dictionary that has a nested structure. |
| 30 |
""" |
| 31 |
|
| 32 |
if copy: |
| 33 |
dict1 = copyModule.copy(dict1) |
| 34 |
elif deepcopy: |
| 35 |
dict1 = copyModule.deepcopy(dict1) |
| 36 |
|
| 37 |
for key, val in dict2.items(): |
| 38 |
if key in dict1 and isinstance(val, dict) \ |
| 39 |
and isinstance(dict1[key], dict): |
| 40 |
dict1[key] = mergeNestedDictionaries(dict1[key], val) |
| 41 |
else: |
| 42 |
dict1[key] = val |
| 43 |
return dict1 |
| 44 |
|
| 45 |
|
| 46 |
def stringIsNumber(S): |
| 47 |
"""Return True if theString represents a Python number, False otherwise. |
| 48 |
This also works for complex numbers and numbers with +/- in front.""" |
| 49 |
|
| 50 |
S = S.strip() |
| 51 |
|
| 52 |
if S[0] in '-+' and len(S) > 1: |
| 53 |
S = S[1:].strip() |
| 54 |
|
| 55 |
match = complexNumberRE.match(S) |
| 56 |
if not match: |
| 57 |
match = numberRE.match(S) |
| 58 |
if not match or (match.end() != len(S)): |
| 59 |
return False |
| 60 |
else: |
| 61 |
return True |
| 62 |
|
| 63 |
|
| 64 |
def convStringToNum(theString): |
| 65 |
""" |
| 66 |
Convert a string representation of a Python number to the Python version |
| 67 |
""" |
| 68 |
if not stringIsNumber(theString): |
| 69 |
raise Error(theString + ' cannot be converted to a Python number') |
| 70 |
return eval(theString, {}, {}) |
| 71 |
|
| 72 |
|
| 73 |
class Error(Exception): |
| 74 |
pass |
| 75 |
|
| 76 |
|
| 77 |
class NoDefault(object): |
| 78 |
pass |
| 79 |
|
| 80 |
|
| 81 |
class ConfigParserCaseSensitive(ConfigParser): |
| 82 |
"""A case sensitive version of the standard Python ConfigParser.""" |
| 83 |
|
| 84 |
def optionxform(self, optionstr): |
| 85 |
"""Don't change the case as is done in the default implemenation.""" |
| 86 |
return optionstr |
| 87 |
|
| 88 |
|
| 89 |
class _SettingsCollector(object): |
| 90 |
"""An abstract base class that provides the methods SettingsManager uses to |
| 91 |
collect settings from config files and strings. |
| 92 |
|
| 93 |
This class only collects settings, it doesn't modify |
| 94 |
the _settings dictionary of SettingsManager instances in any way. |
| 95 |
""" |
| 96 |
_ConfigParserClass = ConfigParserCaseSensitive |
| 97 |
|
| 98 |
def readSettingsFromModule(self, mod, ignoreUnderscored=True): |
| 99 |
"""Returns all settings from a Python module. |
| 100 |
""" |
| 101 |
S = {} |
| 102 |
attrs = vars(mod) |
| 103 |
for k, v in attrs.items(): |
| 104 |
if (ignoreUnderscored and k.startswith('_')): |
| 105 |
continue |
| 106 |
else: |
| 107 |
S[k] = v |
| 108 |
return S |
| 109 |
|
| 110 |
def readSettingsFromPySrcStr(self, theString): |
| 111 |
"""Return a dictionary of the settings in a Python src string.""" |
| 112 |
|
| 113 |
globalsDict = {'True': (1 == 1), |
| 114 |
'False': (0 == 1), |
| 115 |
} |
| 116 |
newSettings = {'self': self} |
| 117 |
exec((theString + os.linesep), globalsDict, newSettings) |
| 118 |
del newSettings['self'] |
| 119 |
module = types.ModuleType('temp_settings_module') |
| 120 |
module.__dict__.update(newSettings) |
| 121 |
return self.readSettingsFromModule(module) |
| 122 |
|
| 123 |
def readSettingsFromConfigFileObj(self, inFile, convert=True): |
| 124 |
""" |
| 125 |
Return the settings from a config file that uses the syntax accepted by |
| 126 |
Python's standard ConfigParser module (like Windows .ini files). |
| 127 |
|
| 128 |
NOTE: |
| 129 |
this method maintains case unlike the ConfigParser module, unless this |
| 130 |
class was initialized with the 'caseSensitive' keyword set to False. |
| 131 |
|
| 132 |
All setting values are initially parsed as strings. However, If the |
| 133 |
'convert' arg is True this method will do the following value |
| 134 |
conversions: |
| 135 |
|
| 136 |
* all Python numeric literals will be coverted from string to number |
| 137 |
|
| 138 |
* The string 'None' will be converted to the Python value None |
| 139 |
|
| 140 |
* The string 'True' will be converted to a Python truth value |
| 141 |
|
| 142 |
* The string 'False' will be converted to a Python false value |
| 143 |
|
| 144 |
* Any string starting with 'python:' will be treated |
| 145 |
as a Python literal or expression that needs to be eval'd. |
| 146 |
This approach is useful for declaring lists and dictionaries. |
| 147 |
|
| 148 |
If a config section titled 'Globals' is present the options defined |
| 149 |
under it will be treated as top-level settings. |
| 150 |
""" |
| 151 |
|
| 152 |
p = self._ConfigParserClass() |
| 153 |
if PY2: |
| 154 |
p.readfp(inFile) |
| 155 |
else: |
| 156 |
p.read_file(inFile) |
| 157 |
sects = p.sections() |
| 158 |
newSettings = {} |
| 159 |
|
| 160 |
sects = p.sections() |
| 161 |
newSettings = {} |
| 162 |
|
| 163 |
for s in sects: |
| 164 |
newSettings[s] = {} |
| 165 |
for o in p.options(s): |
| 166 |
if o != '__name__': |
| 167 |
newSettings[s][o] = p.get(s, o) |
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
for sect, subDict in list(newSettings.items()): |
| 173 |
for key, val in list(subDict.items()): |
| 174 |
if convert: |
| 175 |
if val.lower().startswith('python:'): |
| 176 |
subDict[key] = eval(val[7:], {}, {}) |
| 177 |
if val.lower() == 'none': |
| 178 |
subDict[key] = None |
| 179 |
if val.lower() == 'true': |
| 180 |
subDict[key] = True |
| 181 |
if val.lower() == 'false': |
| 182 |
subDict[key] = False |
| 183 |
if stringIsNumber(val): |
| 184 |
subDict[key] = convStringToNum(val) |
| 185 |
|
| 186 |
|
| 187 |
if key.lower() == 'importsettings': |
| 188 |
if val.find(';') < 0: |
| 189 |
importedSettings = self.readSettingsFromPySrcFile(val) |
| 190 |
else: |
| 191 |
path = val.split(';')[0] |
| 192 |
rest = ''.join(val.split(';')[1:]).strip() |
| 193 |
parentDict = self.readSettingsFromPySrcFile(path) |
| 194 |
importedSettings = eval('parentDict["' + rest + '"]') |
| 195 |
|
| 196 |
subDict.update(mergeNestedDictionaries(subDict, |
| 197 |
importedSettings)) |
| 198 |
|
| 199 |
if sect.lower() == 'globals': |
| 200 |
newSettings.update(newSettings[sect]) |
| 201 |
del newSettings[sect] |
| 202 |
|
| 203 |
return newSettings |
| 204 |
|
| 205 |
|
| 206 |
class SettingsManager(_SettingsCollector): |
| 207 |
""" |
| 208 |
A mixin class that provides facilities for managing application settings. |
| 209 |
|
| 210 |
SettingsManager is designed to work well with nested settings dictionaries |
| 211 |
of any depth. |
| 212 |
""" |
| 213 |
|
| 214 |
def __init__(self): |
| 215 |
super(SettingsManager, self).__init__() |
| 216 |
self._settings = {} |
| 217 |
self._initializeSettings() |
| 218 |
|
| 219 |
def _defaultSettings(self): |
| 220 |
return {} |
| 221 |
|
| 222 |
def _initializeSettings(self): |
| 223 |
"""A hook that allows for complex setting initialization sequences |
| 224 |
that involve references to 'self' or other settings. For example: |
| 225 |
self._settings['myCalcVal'] = self._settings['someVal'] * 15 |
| 226 |
This method should be called by the class' __init__() method |
| 227 |
when needed. |
| 228 |
The dummy implementation should be reimplemented by subclasses. |
| 229 |
""" |
| 230 |
pass |
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
def setting(self, name, default=NoDefault): |
| 235 |
""" |
| 236 |
Get a setting from self._settings, with or without a default value |
| 237 |
""" |
| 238 |
|
| 239 |
if default is NoDefault: |
| 240 |
return self._settings[name] |
| 241 |
else: |
| 242 |
return self._settings.get(name, default) |
| 243 |
|
| 244 |
def hasSetting(self, key): |
| 245 |
"""True/False""" |
| 246 |
return key in self._settings |
| 247 |
|
| 248 |
def setSetting(self, name, value): |
| 249 |
"""Set a setting in self._settings.""" |
| 250 |
self._settings[name] = value |
| 251 |
|
| 252 |
def settings(self): |
| 253 |
"""Return a reference to the settings dictionary""" |
| 254 |
return self._settings |
| 255 |
|
| 256 |
def copySettings(self): |
| 257 |
"""Returns a shallow copy of the settings dictionary""" |
| 258 |
return copyModule.copy(self._settings) |
| 259 |
|
| 260 |
def deepcopySettings(self): |
| 261 |
"""Returns a deep copy of the settings dictionary""" |
| 262 |
return copyModule.deepcopy(self._settings) |
| 263 |
|
| 264 |
def updateSettings(self, newSettings, merge=True): |
| 265 |
""" |
| 266 |
Update the settings with a selective merge or a complete overwrite |
| 267 |
""" |
| 268 |
if merge: |
| 269 |
mergeNestedDictionaries(self._settings, newSettings) |
| 270 |
else: |
| 271 |
self._settings.update(newSettings) |
| 272 |
|
| 273 |
|
| 274 |
|
| 275 |
def updateSettingsFromPySrcStr(self, theString, merge=True): |
| 276 |
"""Update the settings from a code in a Python src string.""" |
| 277 |
|
| 278 |
newSettings = self.readSettingsFromPySrcStr(theString) |
| 279 |
self.updateSettings(newSettings, |
| 280 |
merge=newSettings.get('mergeSettings', merge)) |
| 281 |
|
| 282 |
def updateSettingsFromConfigFileObj(self, inFile, |
| 283 |
convert=True, merge=True): |
| 284 |
"""See the docstring for .updateSettingsFromConfigFile() |
| 285 |
|
| 286 |
The caller of this method is responsible for closing the inFile file |
| 287 |
object.""" |
| 288 |
|
| 289 |
newSettings = self.readSettingsFromConfigFileObj(inFile, |
| 290 |
convert=convert) |
| 291 |
self.updateSettings(newSettings, |
| 292 |
merge=newSettings.get('mergeSettings', merge)) |
| 293 |
|
| 294 |
def updateSettingsFromConfigStr(self, configStr, convert=True, merge=True): |
| 295 |
"""See the docstring for .updateSettingsFromConfigFile() |
| 296 |
""" |
| 297 |
|
| 298 |
configStr = '[globals]\n' + configStr |
| 299 |
inFile = StringIO(configStr) |
| 300 |
newSettings = self.readSettingsFromConfigFileObj(inFile, |
| 301 |
convert=convert) |
| 302 |
self.updateSettings(newSettings, |
| 303 |
merge=newSettings.get('mergeSettings', merge)) |