meerschaum.config
Meerschaum v5.2.3
1#! /usr/bin/env python 2# -*- coding: utf-8 -*- 3# vim:fenc=utf-8 4 5""" 6Import and update configuration dictionary 7and if interactive, print the welcome message. 8""" 9 10from __future__ import annotations 11 12import os 13import shutil 14import sys 15import copy 16import contextlib 17 18import meerschaum.config.paths as paths 19import types 20from meerschaum.utils.typing import Any, Dict, Optional, Union 21from meerschaum.utils.threading import RLock 22 23from meerschaum.config._version import __version__ 24from meerschaum.config._store import get_store, set_store, reset_store 25from meerschaum.config._edit import edit_config, write_config 26from meerschaum.config._read_config import ( 27 search_and_substitute_config, 28 revert_symlinks_config, 29 get_possible_keys, 30 get_keyfile_path, 31 read_config, 32) 33from meerschaum._internal.static import STATIC_CONFIG 34 35from meerschaum.config._patch import ( 36 apply_patch_to_config, 37) 38from meerschaum import _core 39from meerschaum._internal import team_scope as _team_scope 40_IN_TEAM_PROCESS = _team_scope.in_team_process() 41 42__all__ = ( 43 'get_plugin_config', 44 'write_plugin_config', 45 'get_config', 46 'write_config', 47 'edit_config', 48 'set_config', 49 'replace_config', 50 'search_and_substitute_config', 51 'revert_symlinks_config', 52 'get_possible_keys', 53 'get_keyfile_path', 54 'apply_patch_to_config', 55 'read_config', 56 'environment', 57 'paths', 58 'STATIC_CONFIG', 59) 60__pdoc__ = {'static': False, 'resources': False, 'stack': False, } 61_locks = {'config': RLock()} 62 63### The live config dictionary is `meerschaum.config.config` (see `_store.py`): the config registry 64### owns the object, so it is resolved on access (`from meerschaum.config import config` gives the 65### current dictionary, as v4's module global did), and reloading this module starts it over. 66reset_store() 67_backup_config = None 68_allow_write_missing: bool = True 69 70 71def _config( 72 *keys: str, 73 reload: bool = False, 74 substitute: bool = True, 75 sync_files: bool = True, 76 allow_replaced: bool = True, 77 write_missing: bool = True, 78) -> Dict[str, Any]: 79 """ 80 Read and process the configuration file. 81 """ 82 if reload: 83 with _locks['config']: 84 reset_store() 85 86 config = get_store() 87 if keys and keys[0] not in config: 88 from meerschaum.config._sync import sync_files as _sync_files 89 key_config = read_config( 90 keys = [keys[0]], 91 substitute = substitute, 92 write_missing = write_missing and _allow_write_missing, 93 ) 94 if keys[0] in key_config: 95 config[keys[0]] = key_config[keys[0]] 96 if sync_files and _allow_write_missing: 97 _sync_files(keys=[keys[0] if keys else None]) 98 99 if not allow_replaced: 100 return _backup_config if _backup_config is not None else config 101 102 return config 103 104 105def set_config(cf: Dict[str, Any]) -> Dict[str, Any]: 106 """ 107 Set the configuration dictionary. 108 """ 109 if not isinstance(cf, dict): 110 from meerschaum.utils.warnings import error 111 error(f"Invalid value for config: {cf}") 112 with _locks['config']: 113 set_store(cf) 114 return cf 115 116 117def get_config( 118 *keys: str, 119 patch: bool = True, 120 substitute: bool = True, 121 sync_files: bool = True, 122 write_missing: bool = True, 123 as_tuple: bool = False, 124 warn: bool = True, 125 debug: bool = False 126) -> Any: 127 """ 128 Return the Meerschaum configuration dictionary. 129 If positional arguments are provided, index by the keys. 130 Raises a warning if invalid keys are provided. 131 132 Parameters 133 ---------- 134 keys: str: 135 List of strings to index. 136 137 patch: bool, default True 138 If `True`, patch missing default keys into the config directory. 139 Defaults to `True`. 140 141 sync_files: bool, default True 142 If `True`, sync files if needed. 143 Defaults to `True`. 144 145 write_missing: bool, default True 146 If `True`, write default values when the main config files are missing. 147 Defaults to `True`. 148 149 substitute: bool, default True 150 If `True`, subsitute 'MRSM{}' values. 151 Defaults to `True`. 152 153 as_tuple: bool, default False 154 If `True`, return a tuple of type (success, value). 155 Defaults to `False`. 156 157 Returns 158 ------- 159 The value in the configuration directory, indexed by the provided keys. 160 161 Examples 162 -------- 163 >>> get_config('meerschaum', 'instance') 164 'sql:main' 165 >>> get_config('does', 'not', 'exist') 166 UserWarning: Invalid keys in config: ('does', 'not', 'exist') 167 """ 168 value = _core.get_config( 169 *keys, patch=patch, substitute=substitute, sync_files=sync_files, 170 write_missing=write_missing, as_tuple=as_tuple, warn=warn, debug=debug, 171 ) 172 ### Work the API server runs for an isolated team sees only that team's connectors (5.1). 173 if _team_scope.current() is None: 174 if _IN_TEAM_PROCESS: 175 return _team_scope.filter_process_config(keys, value, as_tuple=as_tuple) 176 return value 177 return _team_scope.filter_config(keys, value, as_tuple=as_tuple) 178 179 180def get_plugin_config( 181 *keys: str, 182 warn: bool = False, 183 **kw: Any 184) -> Optional[Any]: 185 """ 186 This may only be called from within a Meerschaum plugin. 187 See `meerschaum.config.get_config` for arguments. 188 """ 189 from meerschaum.utils.warnings import error 190 from meerschaum.plugins import _get_parent_plugin 191 parent_plugin_name = _get_parent_plugin(2) 192 if parent_plugin_name is None: 193 error( 194 "You may only call `get_plugin_config()` " 195 "from within a Meerschaum plugin." 196 ) 197 198 return _core.get_plugin_config(parent_plugin_name, *keys, warn=warn, **kw) 199 200 201def write_plugin_config( 202 config_dict: Dict[str, Any], 203 **kw: Any 204): 205 """ 206 Write a plugin's configuration dictionary. 207 """ 208 from meerschaum.utils.warnings import error 209 from meerschaum.plugins import _get_parent_plugin 210 parent_plugin_name = _get_parent_plugin(2) 211 if parent_plugin_name is None: 212 error("You may only call `get_plugin_config()` from within a Meerschaum plugin.") 213 return _core.write_plugin_config(parent_plugin_name, config_dict, **kw) 214 215 216@contextlib.contextmanager 217def replace_config(config_: Union[Dict[str, Any], None]): 218 """ 219 Temporarily override the Meerschaum config dictionary. 220 221 Parameters 222 ---------- 223 config_: Dict[str, Any] 224 The new config dictionary to temporarily replace the canonical `config`. 225 """ 226 if config_ is None: 227 yield 228 return 229 230 global _backup_config, _allow_write_missing 231 232 previous_config = _config() 233 previous_backup_config = _backup_config 234 previous_allow_write_missing = _allow_write_missing 235 _backup_config = ( 236 previous_backup_config 237 if previous_backup_config is not None 238 else previous_config 239 ) 240 _allow_write_missing = False 241 set_config(config_) 242 243 try: 244 yield 245 finally: 246 set_config(previous_config) 247 _backup_config = previous_backup_config 248 _allow_write_missing = previous_allow_write_missing 249 250### This need to be below get_config to avoid a circular import. 251from meerschaum.config._read_config import read_config 252 253### If environment variable MRSM_CONFIG or MRSM_PATCH is set, patch config before anything else. 254from meerschaum.config.environment import ( 255 apply_environment_patches as _apply_environment_patches, 256 apply_environment_uris as _apply_environment_uris, 257) 258_apply_environment_uris() 259_apply_environment_patches() 260 261patch_config = None 262if paths.PATCH_DIR_PATH.exists(): 263 from meerschaum.utils.yaml import yaml, _yaml 264 if _yaml is not None: 265 patch_config = read_config(directory=paths.PATCH_DIR_PATH) 266 267permanent_patch_config = None 268if paths.PERMANENT_PATCH_DIR_PATH.exists(): 269 from meerschaum.utils.yaml import yaml, _yaml 270 if _yaml is not None: 271 permanent_patch_config = read_config(directory=paths.PERMANENT_PATCH_DIR_PATH) 272### If patches exist, apply to config. 273if patch_config is not None: 274 set_config(apply_patch_to_config(_config(), patch_config)) 275 if paths.PATCH_DIR_PATH.exists(): 276 shutil.rmtree(paths.PATCH_DIR_PATH) 277 278### if permanent_patch.yaml exists, apply patch to config, write config, and delete patch 279if permanent_patch_config is not None and paths.PERMANENT_PATCH_DIR_PATH.exists(): 280 print( 281 "Found permanent patch configuration. " + 282 "Updating main config and deleting permanent patch..." 283 ) 284 set_config(apply_patch_to_config(_config(), permanent_patch_config)) 285 write_config(_config()) 286 permanent_patch_config = None 287 if paths.PERMANENT_PATCH_DIR_PATH.exists(): 288 shutil.rmtree(paths.PERMANENT_PATCH_DIR_PATH) 289 if paths.DEFAULT_CONFIG_DIR_PATH.exists(): 290 shutil.rmtree(paths.DEFAULT_CONFIG_DIR_PATH) 291 292 293### Make sure readline is available for the portable version. 294environment_runtime = STATIC_CONFIG['environment']['runtime'] 295if environment_runtime in os.environ: 296 if os.environ[environment_runtime] == 'portable': 297 from meerschaum.utils.packages import ensure_readline 298 if not paths.PORTABLE_CHECK_READLINE_PATH.exists(): 299 ensure_readline() 300 paths.PORTABLE_CHECK_READLINE_PATH.touch() 301 302 303### If interactive REPL, print welcome header. 304__doc__ = f"Meerschaum v{__version__}" 305try: 306 interactive = False 307 if sys.ps1: 308 interactive = True 309except AttributeError: 310 interactive = False 311if interactive: 312 msg = __doc__ 313 print(msg, file=sys.stderr) 314 315 316class _ConfigModule(types.ModuleType): 317 """ 318 The `meerschaum.config` module type: `config` is the live dictionary of the registry, so 319 `meerschaum.config.config = {...}` replaces it (as `set_config()` does) instead of creating 320 a second attribute that `get_config()` never sees. 321 """ 322 323 @property 324 def config(self) -> Dict[str, Any]: 325 return get_store() 326 327 @config.setter 328 def config(self, cf: Dict[str, Any]) -> None: 329 set_config(cf) 330 331 332sys.modules[__name__].__class__ = _ConfigModule
181def get_plugin_config( 182 *keys: str, 183 warn: bool = False, 184 **kw: Any 185) -> Optional[Any]: 186 """ 187 This may only be called from within a Meerschaum plugin. 188 See `meerschaum.config.get_config` for arguments. 189 """ 190 from meerschaum.utils.warnings import error 191 from meerschaum.plugins import _get_parent_plugin 192 parent_plugin_name = _get_parent_plugin(2) 193 if parent_plugin_name is None: 194 error( 195 "You may only call `get_plugin_config()` " 196 "from within a Meerschaum plugin." 197 ) 198 199 return _core.get_plugin_config(parent_plugin_name, *keys, warn=warn, **kw)
This may only be called from within a Meerschaum plugin.
See meerschaum.config.get_config for arguments.
202def write_plugin_config( 203 config_dict: Dict[str, Any], 204 **kw: Any 205): 206 """ 207 Write a plugin's configuration dictionary. 208 """ 209 from meerschaum.utils.warnings import error 210 from meerschaum.plugins import _get_parent_plugin 211 parent_plugin_name = _get_parent_plugin(2) 212 if parent_plugin_name is None: 213 error("You may only call `get_plugin_config()` from within a Meerschaum plugin.") 214 return _core.write_plugin_config(parent_plugin_name, config_dict, **kw)
Write a plugin's configuration dictionary.
118def get_config( 119 *keys: str, 120 patch: bool = True, 121 substitute: bool = True, 122 sync_files: bool = True, 123 write_missing: bool = True, 124 as_tuple: bool = False, 125 warn: bool = True, 126 debug: bool = False 127) -> Any: 128 """ 129 Return the Meerschaum configuration dictionary. 130 If positional arguments are provided, index by the keys. 131 Raises a warning if invalid keys are provided. 132 133 Parameters 134 ---------- 135 keys: str: 136 List of strings to index. 137 138 patch: bool, default True 139 If `True`, patch missing default keys into the config directory. 140 Defaults to `True`. 141 142 sync_files: bool, default True 143 If `True`, sync files if needed. 144 Defaults to `True`. 145 146 write_missing: bool, default True 147 If `True`, write default values when the main config files are missing. 148 Defaults to `True`. 149 150 substitute: bool, default True 151 If `True`, subsitute 'MRSM{}' values. 152 Defaults to `True`. 153 154 as_tuple: bool, default False 155 If `True`, return a tuple of type (success, value). 156 Defaults to `False`. 157 158 Returns 159 ------- 160 The value in the configuration directory, indexed by the provided keys. 161 162 Examples 163 -------- 164 >>> get_config('meerschaum', 'instance') 165 'sql:main' 166 >>> get_config('does', 'not', 'exist') 167 UserWarning: Invalid keys in config: ('does', 'not', 'exist') 168 """ 169 value = _core.get_config( 170 *keys, patch=patch, substitute=substitute, sync_files=sync_files, 171 write_missing=write_missing, as_tuple=as_tuple, warn=warn, debug=debug, 172 ) 173 ### Work the API server runs for an isolated team sees only that team's connectors (5.1). 174 if _team_scope.current() is None: 175 if _IN_TEAM_PROCESS: 176 return _team_scope.filter_process_config(keys, value, as_tuple=as_tuple) 177 return value 178 return _team_scope.filter_config(keys, value, as_tuple=as_tuple)
Return the Meerschaum configuration dictionary. If positional arguments are provided, index by the keys. Raises a warning if invalid keys are provided.
Parameters
- keys (str:): List of strings to index.
- patch (bool, default True):
If
True, patch missing default keys into the config directory. Defaults toTrue. - sync_files (bool, default True):
If
True, sync files if needed. Defaults toTrue. - write_missing (bool, default True):
If
True, write default values when the main config files are missing. Defaults toTrue. - substitute (bool, default True):
If
True, subsitute 'MRSM{}' values. Defaults toTrue. - as_tuple (bool, default False):
If
True, return a tuple of type (success, value). Defaults toFalse.
Returns
- The value in the configuration directory, indexed by the provided keys.
Examples
>>> get_config('meerschaum', 'instance')
'sql:main'
>>> get_config('does', 'not', 'exist')
UserWarning: Invalid keys in config: ('does', 'not', 'exist')
101def write_config( 102 config_dict: Optional[Dict[str, Any]] = None, 103 directory: Union[str, pathlib.Path, None] = None, 104 debug: bool = False, 105 **kw: Any 106) -> bool: 107 """Write YAML and JSON files to the configuration directory. 108 109 Parameters 110 ---------- 111 config_dict: Optional[Dict[str, Any]], default None 112 A dictionary of keys to dictionaries of configuration. 113 Each key corresponds to a .yaml or .json config file. 114 Writing config to a directory with different keys 115 does not affect existing keys in that directory. 116 If not provided, use the currently loaded config dictionary. 117 118 directory: Union[str, pathlib.Path, None], default None 119 The directory to which the keys are written. 120 If not provided, use the default config path (`~/.config/meerschaum/config/`). 121 122 Returns 123 ------- 124 A bool indicating success. 125 126 """ 127 _rust = _core.write_config 128 return _rust(config_dict, directory=directory, debug=debug)
Write YAML and JSON files to the configuration directory.
Parameters
- config_dict (Optional[Dict[str, Any]], default None): A dictionary of keys to dictionaries of configuration. Each key corresponds to a .yaml or .json config file. Writing config to a directory with different keys does not affect existing keys in that directory. If not provided, use the currently loaded config dictionary.
- directory (Union[str, pathlib.Path, None], default None):
The directory to which the keys are written.
If not provided, use the default config path (
~/.config/meerschaum/config/).
Returns
- A bool indicating success.
17def edit_config( 18 keys: Optional[List[str]] = None, 19 params: Optional[Dict[str, Any]] = None, 20 debug: bool = False, 21 **kw: Any 22) -> SuccessTuple: 23 """Edit the configuration files.""" 24 import meerschaum.config.paths as paths 25 from meerschaum.config import get_config, _config 26 from meerschaum.config._read_config import get_keyfile_path, read_config, revert_symlinks_config 27 from meerschaum.config._backup import backup_config_key, restore_config_backup 28 from meerschaum._internal.static import STATIC_CONFIG 29 from meerschaum.utils.packages import reload_meerschaum 30 from meerschaum.utils.misc import edit_file 31 from meerschaum.utils.warnings import warn, info 32 from meerschaum.utils.prompt import prompt, yes_no 33 34 if keys is None: 35 keys = [] 36 37 symlinks_key = STATIC_CONFIG['config']['symlinks_key'] 38 def _edit_key(key: str): 39 new_key_config = None 40 ### Snapshot the pristine file before any edits or default-merging so it 41 ### can be rolled back if the edit corrupts it. 42 backup_path = backup_config_key(key, debug=debug) 43 while True: 44 ### If defined in default, create the config file. 45 config = _config() 46 symlinks_key_config = config.get(symlinks_key, {}).get(key, {}) 47 key_config = revert_symlinks_config({ 48 key: config.pop(key, {}), 49 symlinks_key: {key: symlinks_key_config}, 50 }) 51 keyfile_path = get_keyfile_path(key, create_new=True) 52 get_config(key, write_missing=True, warn=False) 53 54 edit_file(get_keyfile_path(key, create_new=True)) 55 56 ### Parse the edited file; offer the backup when it does not parse. 57 try: 58 new_key_config = read_config( 59 paths.CONFIG_DIR_PATH, 60 [key], 61 write_missing=False, 62 raise_parsing_errors=True, 63 ) 64 except Exception: 65 if key_config: 66 _config()[key] = key_config 67 warn(f"Could not parse key '{key}'.", stack=False) 68 if backup_path is not None and yes_no( 69 f"Restore '{key}' from the backup taken before editing?", 70 default='n', 71 ): 72 restore_success, restore_msg = restore_config_backup( 73 key, backup_path=backup_path, reload=False, debug=debug, 74 ) 75 if restore_success: 76 info(restore_msg) 77 new_key_config = read_config( 78 paths.CONFIG_DIR_PATH, 79 [key], 80 write_missing=False, 81 raise_parsing_errors=False, 82 ) 83 break 84 warn(restore_msg, stack=False) 85 _ = prompt(f"Press [Enter] to edit '{keyfile_path}', [CTRL+C] to exit.") 86 continue 87 88 if new_key_config: 89 break 90 91 try: 92 for k in keys: 93 _edit_key(k) 94 except KeyboardInterrupt: 95 return False, "" 96 97 reload_meerschaum(debug=debug) 98 return (True, "Success")
Edit the configuration files.
106def set_config(cf: Dict[str, Any]) -> Dict[str, Any]: 107 """ 108 Set the configuration dictionary. 109 """ 110 if not isinstance(cf, dict): 111 from meerschaum.utils.warnings import error 112 error(f"Invalid value for config: {cf}") 113 with _locks['config']: 114 set_store(cf) 115 return cf
Set the configuration dictionary.
217@contextlib.contextmanager 218def replace_config(config_: Union[Dict[str, Any], None]): 219 """ 220 Temporarily override the Meerschaum config dictionary. 221 222 Parameters 223 ---------- 224 config_: Dict[str, Any] 225 The new config dictionary to temporarily replace the canonical `config`. 226 """ 227 if config_ is None: 228 yield 229 return 230 231 global _backup_config, _allow_write_missing 232 233 previous_config = _config() 234 previous_backup_config = _backup_config 235 previous_allow_write_missing = _allow_write_missing 236 _backup_config = ( 237 previous_backup_config 238 if previous_backup_config is not None 239 else previous_config 240 ) 241 _allow_write_missing = False 242 set_config(config_) 243 244 try: 245 yield 246 finally: 247 set_config(previous_config) 248 _backup_config = previous_backup_config 249 _allow_write_missing = previous_allow_write_missing
Temporarily override the Meerschaum config dictionary.
Parameters
- config_ (Dict[str, Any]):
The new config dictionary to temporarily replace the canonical
config.
65def search_and_substitute_config( 66 config: Dict[str, Any], 67 leading_key: str = "MRSM", 68 delimiter: str = ":", 69 begin_key: str = "{", 70 end_key: str = "}", 71 literal_key: str = '!', 72 keep_symlinks: bool = True, 73) -> Dict[str, Any]: 74 """ 75 Search the config for Meerschaum substitution syntax and substite with value of keys. 76 77 Parameters 78 ---------- 79 config: Dict[str, Any] 80 The Meerschaum configuration dictionary to search through. 81 82 leading_key: str, default 'MRSM' 83 The string with which to start the search. 84 85 begin_key: str, default '{' 86 The string to start the keys list. 87 88 end_key: str, default '}' 89 The string to end the keys list. 90 91 literal_key: str, default '!' 92 The string to force an literal interpretation of a value. 93 When the string is isolated, a literal interpreation is assumed and the surrounding 94 quotes are replaced. 95 96 E.g. Suppose a:b:c produces a dictionary {'d': 1}. 97 - 'MRSM{a:b:c}' => {'d': 1} : isolated 98 - ' MRSM{a:b:c} ' => ' "{\'d\': 1}"' : not isolated 99 - ' MRSM{!a:b:c} ' => ' {"d": 1}' : literal 100 101 keep_symlinks: bool, default True 102 If True, include the symlinks under the top-level key '_symlinks' (never written to a file). 103 Defaults to True. 104 105 Example: 106 107 ``` 108 MRSM{meerschaum:connectors:main:host} => cf['meerschaum']['connectors']['main']['host'] 109 ``` 110 111 Returns 112 ------- 113 The configuration dictionary with `MRSM{}` symlinks replaced with 114 the values from the current configuration. 115 """ 116 _rust = _core.search_and_substitute_config 117 return _rust( 118 config, 119 leading_key=leading_key, 120 delimiter=delimiter, 121 begin_key=begin_key, 122 end_key=end_key, 123 literal_key=literal_key, 124 keep_symlinks=keep_symlinks, 125 )
Search the config for Meerschaum substitution syntax and substite with value of keys.
Parameters
- config (Dict[str, Any]): The Meerschaum configuration dictionary to search through.
- leading_key (str, default 'MRSM'): The string with which to start the search.
- begin_key (str, default '{'): The string to start the keys list.
- end_key (str, default '}'): The string to end the keys list.
literal_key (str, default '!'): The string to force an literal interpretation of a value. When the string is isolated, a literal interpreation is assumed and the surrounding quotes are replaced.
E.g. Suppose a:b:c produces a dictionary {'d': 1}.
- 'MRSM{a:b:c}' => {'d': 1} : isolated
- ' MRSM{a:b:c} ' => ' "{'d': 1}"' : not isolated
- ' MRSM{!a:b:c} ' => ' {"d": 1}' : literal
keep_symlinks (bool, default True): If True, include the symlinks under the top-level key '_symlinks' (never written to a file). Defaults to True.
Example:
MRSM{meerschaum:connectors:main:host} => cf['meerschaum']['connectors']['main']['host']
Returns
- The configuration dictionary with
MRSM{}symlinks replaced with - the values from the current configuration.
128def revert_symlinks_config(config: Dict[str, Any]) -> Dict[str, Any]: 129 """ 130 Given a configuration dictionary, re-apply the values from the 131 accompanying `_symlinks` dictionary. 132 133 Parameters 134 ---------- 135 config: Dict[str, Any] 136 The configuration dictionary containing a `_symlinks` dictionary. 137 138 Returns 139 ------- 140 A configuration dictionary with `_symlinks` re-applied. 141 """ 142 _rust = _core.revert_symlinks_config 143 return _rust(config)
Given a configuration dictionary, re-apply the values from the
accompanying _symlinks dictionary.
Parameters
- config (Dict[str, Any]):
The configuration dictionary containing a
_symlinksdictionary.
Returns
- A configuration dictionary with
_symlinksre-applied.
146def get_possible_keys() -> List[str]: 147 """ 148 Return a list of possible top-level keys. 149 """ 150 import os 151 import meerschaum.config.paths as paths 152 from meerschaum.config._default import default_config 153 keys = set() 154 for key in default_config: 155 keys.add(key) 156 for filename in os.listdir(paths.CONFIG_DIR_PATH): 157 keys.add('.'.join(filename.split('.')[:-1])) 158 return sorted(list(keys))
Return a list of possible top-level keys.
161def get_keyfile_path( 162 key: str, 163 create_new: bool = False, 164 directory: Union[pathlib.Path, str, None] = None, 165) -> Union[pathlib.Path, None]: 166 """Determine a key's file path.""" 167 _rust = _core.get_keyfile_path 168 return _rust(key, create_new=create_new, directory=directory)
Determine a key's file path.
15def apply_patch_to_config( 16 config: Dict[str, Any], 17 patch: Dict[str, Any], 18 warn: bool = False, 19) -> Dict[str, Any]: 20 """Patch the config dict with a new dict (cascade patching).""" 21 if not isinstance(patch, dict) or not patch: 22 return config 23 if not isinstance(config, dict) or not config: 24 return copy.deepcopy(patch) 25 26 base = config.copy() 27 28 for key, value in patch.items(): 29 if isinstance(value, dict) and isinstance(base.get(key), dict): 30 base[key] = apply_patch_to_config(base[key], value, warn=warn) 31 elif isinstance(value, dict): 32 if warn and key in base: 33 _warn(f"Overwriting the value {base[key]} with a dictionary:\n{value}") 34 base[key] = copy.deepcopy(value) 35 else: 36 base[key] = value 37 38 return base
Patch the config dict with a new dict (cascade patching).
17def read_config( 18 directory: Union[pathlib.Path, str, None] = None, 19 keys: Optional[List[str]] = None, 20 write_missing: bool = True, 21 substitute: bool = True, 22 with_filenames: bool = False, 23 raise_parsing_errors: bool = False, 24) -> Union[Dict[str, Any], Tuple[Dict[str, Any], List[str]]]: 25 """ 26 Read the configuration directory. 27 28 Parameters 29 ---------- 30 directory: Union[pathlib.Path, str, None], default None 31 The directory with configuration files (.json and .yaml). 32 33 keys: Optional[List[str]], default None 34 Which configuration files to read. 35 36 write_missing: bool, default True 37 If a keyfile does not exist but is defined in the default configuration, 38 write the file to disk. 39 40 substitute: bool, default True 41 Replace `MRSM{}` syntax with configuration values. 42 43 with_filename: bool, default False 44 If `True`, return a tuple of the configuration dictionary with a list of read filenames. 45 46 raise_parsing_errors: bool, default False 47 If `True`, re-raise parsing exceptions. 48 49 Examples 50 -------- 51 >>> read_config(keys=['meerschaum'], with_filename=True) 52 >>> ({...}, ['meerschaum.yaml']) 53 """ 54 _rust = _core.read_config 55 return _rust( 56 directory=directory, 57 keys=keys, 58 write_missing=write_missing, 59 substitute=substitute, 60 with_filenames=with_filenames, 61 raise_parsing_errors=raise_parsing_errors, 62 )
Read the configuration directory.
Parameters
- directory (Union[pathlib.Path, str, None], default None): The directory with configuration files (.json and .yaml).
- keys (Optional[List[str]], default None): Which configuration files to read.
- write_missing (bool, default True): If a keyfile does not exist but is defined in the default configuration, write the file to disk.
- substitute (bool, default True):
Replace
MRSM{}syntax with configuration values. - with_filename (bool, default False):
If
True, return a tuple of the configuration dictionary with a list of read filenames. - raise_parsing_errors (bool, default False):
If
True, re-raise parsing exceptions.
Examples
>>> read_config(keys=['meerschaum'], with_filename=True)
>>> ({...}, ['meerschaum.yaml'])