|
3 | 3 | import copy |
4 | 4 | import io |
5 | 5 | import logging |
| 6 | +import os |
6 | 7 | import re |
7 | 8 | import sys |
8 | 9 | import types |
9 | 10 |
|
| 11 | +# Duplicate here for convenience |
| 12 | +from .. import DEFAULT_CONFIG_PATH |
| 13 | + |
10 | 14 | logger = logging.Logger(__name__) |
11 | 15 |
|
12 | 16 | class iRODSConfiguration(object): |
13 | 17 | __slots__ = () |
14 | 18 |
|
15 | 19 | def getter(category, setting): |
| 20 | + """A programmatic way of allowing the current value of the specified setting to be |
| 21 | + given indirectly (through an extra call indirection) as the default value of a parameter. |
| 22 | +
|
| 23 | + Returns a lambda that, when called, will yield the setting's value. In the closure of |
| 24 | + that lambda, the Python builtin function globals() is used to access (in a read-only |
| 25 | + capacity) the namespace dict of the irods.client_configuration module. |
| 26 | +
|
| 27 | + See the irods.manager.data_object_manager.DataObjectManager.open(...) method signature |
| 28 | + for a usage example. |
| 29 | + """ |
16 | 30 | return lambda:getattr(globals()[category], setting) |
17 | 31 |
|
18 | 32 | # ############################################################################# |
@@ -48,3 +62,162 @@ def __init__(self): |
48 | 62 | # listed in the __slots__ member of the category class. |
49 | 63 |
|
50 | 64 | data_objects = DataObjects() |
| 65 | + |
| 66 | +def _var_items(root): |
| 67 | + if isinstance(root,types.ModuleType): |
| 68 | + return [(i,v) for i,v in vars(root).items() |
| 69 | + if isinstance(v,iRODSConfiguration)] |
| 70 | + if isinstance(root,iRODSConfiguration): |
| 71 | + return [(i, getattr(root,i)) for i in root.__slots__] |
| 72 | + return [] |
| 73 | + |
| 74 | +def save(root = None, string='', file = ''): |
| 75 | + """Save the current configuration. |
| 76 | +
|
| 77 | + When called simply as save(), this function simply writes all client settings into |
| 78 | + a configuration file. |
| 79 | +
|
| 80 | + The 'root' and 'string' parameters are not likely to be overridden when called from an |
| 81 | + application. They should usually only vary from the defaults when save() recurses into itself. |
| 82 | + However, for due explanation's sake: 'root' specifies at which subtree node to start writing, |
| 83 | + None denoting the top level; and 'string' specifies a prefix for the dotted prefix name, |
| 84 | + which should be empty for an invocation that references the settings' top level namespace. |
| 85 | + Both of these defaults are in effect when calling save() without explicit parameters. |
| 86 | +
|
| 87 | + The configuration file path will normally be the value of DEFAULT_CONFIG_PATH, |
| 88 | + but this can be overridden by supplying a non-empty string in the 'file' parameter. |
| 89 | + """ |
| 90 | + _file = None |
| 91 | + auto_close_settings = False |
| 92 | + try: |
| 93 | + if not file: |
| 94 | + from .. import get_settings_path |
| 95 | + file = get_settings_path() |
| 96 | + if isinstance(file,str): |
| 97 | + _file = open(file,'w') |
| 98 | + auto_close_settings = True |
| 99 | + else: |
| 100 | + _file = file # assume file-like object if not a string |
| 101 | + if root is None: |
| 102 | + root = sys.modules[__name__] |
| 103 | + for k,v in _var_items(root): |
| 104 | + dotted_string = string + ("." if string else "") + k |
| 105 | + if isinstance(v,iRODSConfiguration): |
| 106 | + save(root = v, string = dotted_string, file = _file) |
| 107 | + else: |
| 108 | + print(dotted_string, repr(v), sep='\t\t', file = _file) |
| 109 | + return file |
| 110 | + finally: |
| 111 | + if _file and auto_close_settings: |
| 112 | + _file.close() |
| 113 | + |
| 114 | +def _load_config_line(root, setting, value): |
| 115 | + arr = [_.strip() for _ in setting.split('.')] |
| 116 | + # Compute the object referred to by the dotted name. |
| 117 | + attr = '' |
| 118 | + for i in filter(None,arr): |
| 119 | + if attr: |
| 120 | + root = getattr(root,attr) |
| 121 | + attr = i |
| 122 | + # Assign into the current setting of the dotted name (effectively <root>.<attr>) |
| 123 | + # using the loaded value. |
| 124 | + if attr: |
| 125 | + return setattr(root, attr, ast.literal_eval(value)) |
| 126 | + error_message = 'Bad setting: root = {root!r}, setting = {setting!r}, value = {value!r}'.format(**locals()) |
| 127 | + raise RuntimeError (error_message) |
| 128 | + |
| 129 | +# The following regular expression is used to match a configuration file line of the form: |
| 130 | +# --------------------------------------------------------------- |
| 131 | +# <optional whitespace> |
| 132 | +# key: <dotted-name specification> |
| 133 | +# <whitespace of length 1 or more> |
| 134 | +# value: <A Python value which can be given to ast.literal_eval(); e.g. 5, True, or 'some_string'> |
| 135 | +# <optional whitespace> |
| 136 | + |
| 137 | +_key_value_pattern = re.compile(r'\s*(?P<key>\w+(\.\w+)+)\s+(?P<value>\S.*?)\s*$') |
| 138 | + |
| 139 | +class _ConfigLoadError: |
| 140 | + """ |
| 141 | + Exceptions that subclass this type can be thrown by the load() function if |
| 142 | + their classes are listed in the failure_modes parameter of that function. |
| 143 | + """ |
| 144 | + |
| 145 | +class NoConfigError(Exception, _ConfigLoadError): pass |
| 146 | +class BadConfigError(Exception, _ConfigLoadError): pass |
| 147 | + |
| 148 | +def load(root = None, file = '', failure_modes = (), logging_level = logging.WARNING): |
| 149 | + """Load the current configuration. |
| 150 | +
|
| 151 | + An example of a valid line in a configuration file is this: |
| 152 | +
|
| 153 | + data_objects.auto_close True |
| 154 | +
|
| 155 | + When this function is called without parameters, it reads all client settings from |
| 156 | + a configuration file (the path given by DEFAULT_CONFIG_PATH, since file = '' in such |
| 157 | + an invocation) and assigns the repr()-style Python value given into the dotted-string |
| 158 | + configuration entry given. |
| 159 | +
|
| 160 | + The 'file' parameter, when set to a non-empty string, provides an override for |
| 161 | + the config-file path default. |
| 162 | +
|
| 163 | + As with save(), 'root' refers to the starting location in the settings tree, with |
| 164 | + a value of None denoting the top tree node (ie the namespace containing *all* settings). |
| 165 | + There are as yet no imagined use-cases for an application developer to pass in an |
| 166 | + explicit 'root' override. |
| 167 | +
|
| 168 | + 'failure_modes' is an iterable containing desired exception types to be thrown if, |
| 169 | + for example, the configuration file is missing (NoConfigError) or contains an improperly |
| 170 | + formatted line (BadConfigError). |
| 171 | +
|
| 172 | + 'logging_level' governs the internally logged messages and can be used to e.g. quiet the |
| 173 | + call's logging output. |
| 174 | + """ |
| 175 | + def _existing_config(path): |
| 176 | + if os.path.isfile(path): |
| 177 | + return open(path,'r') |
| 178 | + message = 'Config file not available at %r' % (path,) |
| 179 | + logging.getLogger(__name__).log(logging_level, message) |
| 180 | + if NoConfigError in failure_modes: |
| 181 | + raise NoConfigError(message) |
| 182 | + return io.StringIO() |
| 183 | + |
| 184 | + _file = None |
| 185 | + try: |
| 186 | + if not file: |
| 187 | + from .. import get_settings_path |
| 188 | + file = get_settings_path() |
| 189 | + |
| 190 | + _file = _existing_config(file) |
| 191 | + |
| 192 | + if root is None: |
| 193 | + root = sys.modules[__name__] |
| 194 | + |
| 195 | + for line_number, line in enumerate(_file.readlines()): |
| 196 | + line = line.strip() |
| 197 | + match = _key_value_pattern.match(line) |
| 198 | + if not match: |
| 199 | + if line != '': |
| 200 | + # Log only the invalid lines that contain non-whitespace characters. |
| 201 | + message = 'Invalid configuration format at line %d: %r' % (line_number+1, line) |
| 202 | + logging.getLogger(__name__).log(logging_level, message) |
| 203 | + if BadConfigError in failure_modes: |
| 204 | + raise BadConfigError(message) |
| 205 | + continue |
| 206 | + _load_config_line(root, match.group('key'), match.group('value')) |
| 207 | + finally: |
| 208 | + if _file: |
| 209 | + _file.close() |
| 210 | + |
| 211 | +default_config_dict = {} |
| 212 | + |
| 213 | +def preserve_defaults(): |
| 214 | + default_config_dict.update((k,copy.deepcopy(v)) for k,v in globals().items() if isinstance(v,iRODSConfiguration)) |
| 215 | + |
| 216 | +def autoload(_file_to_load): |
| 217 | + if _file_to_load is not None: |
| 218 | + load(file = _file_to_load) |
| 219 | + |
| 220 | +def new_default_config(): |
| 221 | + module = types.ModuleType('_') |
| 222 | + module.__dict__.update(default_config_dict) |
| 223 | + return module |
0 commit comments