|
| 1 | +import inspect |
| 2 | +from functools import wraps |
| 3 | + |
| 4 | + |
| 5 | +def merge(section: str | None = None): |
| 6 | + """ |
| 7 | + Decorator to merge the func call arguments/options of Typer with config defaults provided via TOML tables. |
| 8 | + The precedence is as follows: |
| 9 | + - Explicit CLI Arguments: (i.e. surge <cmd> -<option-flag> --<option-name>) |
| 10 | +
|
| 11 | + - Configuration Data for a given section ( |
| 12 | + found in TOML table under table, i.e.: |
| 13 | + [table-name] |
| 14 | + <option> = <value> |
| 15 | +
|
| 16 | + # Provided as a KWArg for Python in config.py |
| 17 | + ) |
| 18 | +
|
| 19 | + - Typer function default signature ( |
| 20 | + i.e. |
| 21 | + def name(option: typer.Option('-x', '--flag') = <value>, ...): |
| 22 | + ) |
| 23 | + """ |
| 24 | + |
| 25 | + def decorator(func): |
| 26 | + orig_sig = inspect.signature(func) |
| 27 | + declared_defaults = { |
| 28 | + name: param.default |
| 29 | + for name, param in orig_sig.parameters.items() |
| 30 | + if param.default is not inspect._empty |
| 31 | + } |
| 32 | + |
| 33 | + # Modded signature with defaults set to None for Typer to see as optional; leaves *args, **kwargs, and positional-only params default |
| 34 | + new_params = [] |
| 35 | + for param in orig_sig.parameters.values(): |
| 36 | + if param.kind in ( |
| 37 | + inspect.Parameter.VAR_POSITIONAL, |
| 38 | + inspect.Parameter.VAR_KEYWORD, |
| 39 | + inspect.Parameter.POSITIONAL_ONLY, |
| 40 | + ): |
| 41 | + new_params.append(param) |
| 42 | + else: |
| 43 | + new_params.append(param.replace(default=None)) |
| 44 | + new_sig = orig_sig.replace(parameters=new_params) |
| 45 | + |
| 46 | + # Actual wrapper lets go |
| 47 | + @wraps(func) |
| 48 | + def wrapper(*args, **kwargs): |
| 49 | + config_data = func.__globals__.get("config_data", {}) |
| 50 | + |
| 51 | + section_key = section or func.__name__ |
| 52 | + config_section = ( |
| 53 | + config_data.get(section_key, {}) |
| 54 | + if isinstance(config_data, dict) |
| 55 | + else {} |
| 56 | + ) |
| 57 | + |
| 58 | + bound = orig_sig.bind_partial(*args, **kwargs) |
| 59 | + final_args = {} |
| 60 | + |
| 61 | + for name in orig_sig.parameters: |
| 62 | + val = bound.arguments.get(name, None) |
| 63 | + |
| 64 | + if val is not None: # Explicit cli option |
| 65 | + final_args[name] = val |
| 66 | + continue |
| 67 | + |
| 68 | + if name in config_section: # Config option |
| 69 | + final_args[name] = config_section[name] |
| 70 | + continue |
| 71 | + |
| 72 | + if name in declared_defaults: # Default fallback |
| 73 | + final_args[name] = declared_defaults[name] |
| 74 | + else: |
| 75 | + final_args[name] = None |
| 76 | + |
| 77 | + return func(**final_args) |
| 78 | + |
| 79 | + wrapper.__signature__ = new_sig |
| 80 | + return wrapper |
| 81 | + |
| 82 | + return decorator |
0 commit comments