|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import fnmatch |
| 4 | +from copy import deepcopy |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +from attrs import define, field |
| 8 | +from loguru import logger |
| 9 | + |
| 10 | +from lsp_client.utils.uri import from_local_uri |
| 11 | + |
| 12 | + |
| 13 | +def deep_merge(base: dict[str, Any], update: dict[str, Any]) -> dict[str, Any]: |
| 14 | + """ |
| 15 | + Recursively merge two dictionaries. |
| 16 | + """ |
| 17 | + result = deepcopy(base) |
| 18 | + for key, value in update.items(): |
| 19 | + if key in result and isinstance(result[key], dict) and isinstance(value, dict): |
| 20 | + result[key] = deep_merge(result[key], value) |
| 21 | + else: |
| 22 | + result[key] = deepcopy(value) |
| 23 | + return result |
| 24 | + |
| 25 | + |
| 26 | +@define |
| 27 | +class ConfigurationMap: |
| 28 | + """ |
| 29 | + A helper class to manage LSP configuration. |
| 30 | + Supports global configuration and scope-specific overrides. |
| 31 | + """ |
| 32 | + |
| 33 | + _global_config: dict[str, Any] = field(factory=dict) |
| 34 | + _scoped_configs: list[tuple[str, dict[str, Any]]] = field(factory=list) |
| 35 | + |
| 36 | + def add_scope(self, pattern: str, config: dict[str, Any]) -> None: |
| 37 | + """ |
| 38 | + Add a configuration override for a specific file pattern. |
| 39 | +
|
| 40 | + :param pattern: Glob pattern (e.g. "**/tests/**", "*.py") |
| 41 | + :param config: The configuration dict to merge for this scope |
| 42 | + """ |
| 43 | + self._scoped_configs.append((pattern, config)) |
| 44 | + |
| 45 | + def _get_section(self, config: Any, section: str | None) -> Any: |
| 46 | + if not section: |
| 47 | + return config |
| 48 | + |
| 49 | + # Traverse the config dictionary using the section path (e.g. "python.analysis") |
| 50 | + current = config |
| 51 | + for part in section.split("."): |
| 52 | + if isinstance(current, dict) and part in current: |
| 53 | + current = current[part] |
| 54 | + else: |
| 55 | + return None |
| 56 | + return current |
| 57 | + |
| 58 | + def get(self, scope_uri: str | None, section: str | None) -> Any: |
| 59 | + # Start with global config |
| 60 | + final_config = self._global_config |
| 61 | + |
| 62 | + # If we have a scope, merge matching scoped configs |
| 63 | + if scope_uri: |
| 64 | + try: |
| 65 | + path_str = str(from_local_uri(scope_uri)) |
| 66 | + for pattern, scoped_config in self._scoped_configs: |
| 67 | + if fnmatch.fnmatch(path_str, pattern): |
| 68 | + final_config = deep_merge(final_config, scoped_config) |
| 69 | + except Exception: |
| 70 | + logger.warning(f"Failed to parse scope URI: {scope_uri}") |
| 71 | + |
| 72 | + return self._get_section(final_config, section) |
0 commit comments