|
49 | 49 | QGIST_CONFIG_FLD,
|
50 | 50 | )
|
51 | 51 | from .error import (
|
| 52 | + QgistConfigFormatError, |
52 | 53 | QgistConfigKeyError,
|
53 | 54 | QgistTypeError,
|
54 | 55 | QgistValueError,
|
@@ -107,7 +108,11 @@ def __init__(self, fn):
|
107 | 108 | if not os.path.isfile(fn):
|
108 | 109 | raise QgistValueError(translate('global', '"fn" must be a file. (config)'))
|
109 | 110 | with open(fn, 'r', encoding = 'utf-8') as f:
|
110 |
| - self._data = json.loads(f.read()) |
| 111 | + data = f.read() |
| 112 | + try: |
| 113 | + self._data = json.loads(data) |
| 114 | + except: |
| 115 | + raise QgistConfigFormatError(translate('global', 'Config does not contain valid JSON. (config)')) |
111 | 116 | if not isinstance(self._data, dict):
|
112 | 117 | raise QgistTypeError(translate('global', 'Configuration data must be a dict. (config)'))
|
113 | 118 |
|
@@ -179,3 +184,38 @@ def _save(self):
|
179 | 184 |
|
180 | 185 | if backup_fn is not None:
|
181 | 186 | os.unlink(backup_fn)
|
| 187 | + |
| 188 | + @staticmethod |
| 189 | + def import_config(fn): |
| 190 | + |
| 191 | + if not isinstance(fn, str): |
| 192 | + raise QgistTypeError(translate('global', '"fn" must be str. (config import)')) |
| 193 | + if not os.path.exists(fn): |
| 194 | + raise QgistValueError(translate('global', '"fn" must exists. (config import)')) |
| 195 | + if not os.path.isfile(fn): |
| 196 | + raise QgistValueError(translate('global', '"fn" must be a file. (config import)')) |
| 197 | + |
| 198 | + with open(fn, 'r', encoding = 'utf-8') as f: |
| 199 | + raw = f.read() |
| 200 | + |
| 201 | + try: |
| 202 | + value = json.loads(raw) |
| 203 | + except: |
| 204 | + raise QgistConfigFormatError(translate('global', '"fn" does not contain valid JSON. (config import)')) |
| 205 | + |
| 206 | + return value |
| 207 | + |
| 208 | + @staticmethod |
| 209 | + def export_config(fn, value): |
| 210 | + |
| 211 | + if not isinstance(fn, str): |
| 212 | + raise QgistTypeError(translate('global', '"fn" must be str. (config export)')) |
| 213 | + if not os.path.exists(os.path.dirname(fn)): |
| 214 | + raise QgistValueError(translate('global', 'Parent of "fn" must exists. (config export)')) |
| 215 | + if not os.path.isdir(os.path.dirname(fn)): |
| 216 | + raise QgistValueError(translate('global', 'Parent of "fn" must be a directory. (config export)')) |
| 217 | + if not config_class._check_value(value): |
| 218 | + raise QgistTypeError(translate('global', '"value" contains not allowed types. (config export)')) |
| 219 | + |
| 220 | + with open(fn, 'w', encoding = 'utf-8') as f: |
| 221 | + f.write(json.dumps(value, indent = 4, sort_keys = True)) |
0 commit comments