exonware-xwlazy 0.1.0.10__py3-none-any.whl → 0.1.0.19__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. exonware/__init__.py +22 -0
  2. exonware/xwlazy/__init__.py +0 -0
  3. exonware/xwlazy/common/__init__.py +47 -0
  4. exonware/xwlazy/common/base.py +58 -0
  5. exonware/xwlazy/common/cache.py +506 -0
  6. exonware/xwlazy/common/logger.py +268 -0
  7. exonware/xwlazy/common/services/__init__.py +72 -0
  8. exonware/xwlazy/common/services/dependency_mapper.py +234 -0
  9. exonware/xwlazy/common/services/install_async_utils.py +169 -0
  10. exonware/xwlazy/common/services/install_cache_utils.py +257 -0
  11. exonware/xwlazy/common/services/keyword_detection.py +292 -0
  12. exonware/xwlazy/common/services/spec_cache.py +173 -0
  13. exonware/xwlazy/common/services/state_manager.py +86 -0
  14. exonware/xwlazy/common/strategies/__init__.py +28 -0
  15. exonware/xwlazy/common/strategies/caching_dict.py +45 -0
  16. exonware/xwlazy/common/strategies/caching_installation.py +89 -0
  17. exonware/xwlazy/common/strategies/caching_lfu.py +67 -0
  18. exonware/xwlazy/common/strategies/caching_lru.py +64 -0
  19. exonware/xwlazy/common/strategies/caching_multitier.py +60 -0
  20. exonware/xwlazy/common/strategies/caching_ttl.py +60 -0
  21. exonware/xwlazy/config.py +195 -0
  22. exonware/xwlazy/contracts.py +1410 -0
  23. exonware/xwlazy/defs.py +397 -0
  24. exonware/xwlazy/errors.py +284 -0
  25. exonware/xwlazy/facade.py +1049 -0
  26. exonware/xwlazy/module/__init__.py +18 -0
  27. exonware/xwlazy/module/base.py +569 -0
  28. exonware/xwlazy/module/data.py +17 -0
  29. exonware/xwlazy/module/facade.py +247 -0
  30. exonware/xwlazy/module/importer_engine.py +2161 -0
  31. exonware/xwlazy/module/strategies/__init__.py +22 -0
  32. exonware/xwlazy/module/strategies/module_helper_lazy.py +94 -0
  33. exonware/xwlazy/module/strategies/module_helper_simple.py +66 -0
  34. exonware/xwlazy/module/strategies/module_manager_advanced.py +112 -0
  35. exonware/xwlazy/module/strategies/module_manager_simple.py +96 -0
  36. exonware/xwlazy/package/__init__.py +18 -0
  37. exonware/xwlazy/package/base.py +807 -0
  38. exonware/xwlazy/package/conf.py +331 -0
  39. exonware/xwlazy/package/data.py +17 -0
  40. exonware/xwlazy/package/facade.py +481 -0
  41. exonware/xwlazy/package/services/__init__.py +84 -0
  42. exonware/xwlazy/package/services/async_install_handle.py +89 -0
  43. exonware/xwlazy/package/services/config_manager.py +246 -0
  44. exonware/xwlazy/package/services/discovery.py +374 -0
  45. exonware/xwlazy/package/services/host_packages.py +149 -0
  46. exonware/xwlazy/package/services/install_async.py +278 -0
  47. exonware/xwlazy/package/services/install_cache.py +146 -0
  48. exonware/xwlazy/package/services/install_interactive.py +60 -0
  49. exonware/xwlazy/package/services/install_policy.py +158 -0
  50. exonware/xwlazy/package/services/install_registry.py +56 -0
  51. exonware/xwlazy/package/services/install_result.py +17 -0
  52. exonware/xwlazy/package/services/install_sbom.py +154 -0
  53. exonware/xwlazy/package/services/install_utils.py +83 -0
  54. exonware/xwlazy/package/services/installer_engine.py +408 -0
  55. exonware/xwlazy/package/services/lazy_installer.py +720 -0
  56. exonware/xwlazy/package/services/manifest.py +506 -0
  57. exonware/xwlazy/package/services/strategy_registry.py +188 -0
  58. exonware/xwlazy/package/strategies/__init__.py +57 -0
  59. exonware/xwlazy/package/strategies/package_discovery_file.py +130 -0
  60. exonware/xwlazy/package/strategies/package_discovery_hybrid.py +85 -0
  61. exonware/xwlazy/package/strategies/package_discovery_manifest.py +102 -0
  62. exonware/xwlazy/package/strategies/package_execution_async.py +114 -0
  63. exonware/xwlazy/package/strategies/package_execution_cached.py +91 -0
  64. exonware/xwlazy/package/strategies/package_execution_pip.py +100 -0
  65. exonware/xwlazy/package/strategies/package_execution_wheel.py +107 -0
  66. exonware/xwlazy/package/strategies/package_mapping_discovery_first.py +101 -0
  67. exonware/xwlazy/package/strategies/package_mapping_hybrid.py +106 -0
  68. exonware/xwlazy/package/strategies/package_mapping_manifest_first.py +101 -0
  69. exonware/xwlazy/package/strategies/package_policy_allow_list.py +58 -0
  70. exonware/xwlazy/package/strategies/package_policy_deny_list.py +58 -0
  71. exonware/xwlazy/package/strategies/package_policy_permissive.py +47 -0
  72. exonware/xwlazy/package/strategies/package_timing_clean.py +68 -0
  73. exonware/xwlazy/package/strategies/package_timing_full.py +67 -0
  74. exonware/xwlazy/package/strategies/package_timing_smart.py +69 -0
  75. exonware/xwlazy/package/strategies/package_timing_temporary.py +67 -0
  76. exonware/xwlazy/runtime/__init__.py +18 -0
  77. exonware/xwlazy/runtime/adaptive_learner.py +131 -0
  78. exonware/xwlazy/runtime/base.py +276 -0
  79. exonware/xwlazy/runtime/facade.py +95 -0
  80. exonware/xwlazy/runtime/intelligent_selector.py +173 -0
  81. exonware/xwlazy/runtime/metrics.py +64 -0
  82. exonware/xwlazy/runtime/performance.py +39 -0
  83. exonware/xwlazy/version.py +2 -2
  84. exonware_xwlazy-0.1.0.19.dist-info/METADATA +456 -0
  85. exonware_xwlazy-0.1.0.19.dist-info/RECORD +87 -0
  86. exonware_xwlazy-0.1.0.10.dist-info/METADATA +0 -0
  87. exonware_xwlazy-0.1.0.10.dist-info/RECORD +0 -6
  88. {exonware_xwlazy-0.1.0.10.dist-info → exonware_xwlazy-0.1.0.19.dist-info}/WHEEL +0 -0
  89. {exonware_xwlazy-0.1.0.10.dist-info → exonware_xwlazy-0.1.0.19.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,246 @@
1
+ """
2
+ Configuration management for lazy loading system.
3
+
4
+ This module contains LazyInstallConfig which manages per-package lazy installation
5
+ configuration. Extracted from lazy_core.py Section 5.
6
+ """
7
+
8
+ from typing import Dict, Optional
9
+ from ...common.services import LazyStateManager
10
+ from ...defs import LazyLoadMode, LazyInstallMode, LazyModeConfig
11
+ from ...defs import get_preset_mode
12
+
13
+ # Lazy import to avoid circular dependency
14
+ def _get_logger():
15
+ """Get logger (lazy import to avoid circular dependency)."""
16
+ from ...common.logger import get_logger
17
+ return get_logger("xwlazy.config")
18
+
19
+ def _get_log_event():
20
+ """Get log_event function (lazy import to avoid circular dependency)."""
21
+ from ...common.logger import log_event
22
+ return log_event
23
+
24
+ logger = None # Will be initialized on first use
25
+ _log = None # Will be initialized on first use
26
+
27
+ # Mode enum mapping - extracted from lazy_core.py
28
+ _MODE_ENUM_MAP = {
29
+ # Core v1.0 modes
30
+ "none": LazyInstallMode.NONE,
31
+ "smart": LazyInstallMode.SMART,
32
+ "full": LazyInstallMode.FULL,
33
+ "clean": LazyInstallMode.CLEAN,
34
+ "temporary": LazyInstallMode.TEMPORARY,
35
+ "size_aware": LazyInstallMode.SIZE_AWARE,
36
+ # Special purpose modes
37
+ "interactive": LazyInstallMode.INTERACTIVE,
38
+ "warn": LazyInstallMode.WARN,
39
+ "disabled": LazyInstallMode.DISABLED,
40
+ "dry_run": LazyInstallMode.DRY_RUN,
41
+ # Legacy aliases
42
+ "auto": LazyInstallMode.SMART,
43
+ "on_demand": LazyInstallMode.SMART,
44
+ "on-demand": LazyInstallMode.SMART,
45
+ "lazy": LazyInstallMode.SMART,
46
+ }
47
+
48
+
49
+ class LazyInstallConfig:
50
+ """Global configuration for lazy installation per package."""
51
+ _configs: Dict[str, bool] = {}
52
+ _modes: Dict[str, str] = {}
53
+ _load_modes: Dict[str, LazyLoadMode] = {}
54
+ _install_modes: Dict[str, LazyInstallMode] = {}
55
+ _mode_configs: Dict[str, LazyModeConfig] = {}
56
+ _initialized: Dict[str, bool] = {}
57
+ _manual_overrides: Dict[str, bool] = {}
58
+
59
+ @classmethod
60
+ def set(
61
+ cls,
62
+ package_name: str,
63
+ enabled: bool,
64
+ mode: str = "auto",
65
+ install_hook: bool = True,
66
+ manual: bool = False,
67
+ load_mode: Optional[LazyLoadMode] = None,
68
+ install_mode: Optional[LazyInstallMode] = None,
69
+ mode_config: Optional[LazyModeConfig] = None,
70
+ ) -> None:
71
+ """Enable or disable lazy installation for a specific package."""
72
+ package_key = package_name.lower()
73
+ state_manager = LazyStateManager(package_name)
74
+
75
+ if manual:
76
+ cls._manual_overrides[package_key] = True
77
+ state_manager.set_manual_state(enabled)
78
+ elif cls._manual_overrides.get(package_key):
79
+ global logger
80
+ if logger is None:
81
+ logger = _get_logger()
82
+ logger.debug(
83
+ f"Lazy install config for {package_key} already overridden manually; skipping auto configuration."
84
+ )
85
+ return
86
+ else:
87
+ state_manager.set_manual_state(None)
88
+
89
+ cls._configs[package_key] = enabled
90
+ cls._modes[package_key] = mode
91
+
92
+ # Handle two-dimensional mode configuration
93
+ if mode_config:
94
+ cls._mode_configs[package_key] = mode_config
95
+ cls._load_modes[package_key] = mode_config.load_mode
96
+ cls._install_modes[package_key] = mode_config.install_mode
97
+ elif load_mode is not None or install_mode is not None:
98
+ # Explicit mode specification
99
+ if load_mode is None:
100
+ load_mode = LazyLoadMode.AUTO # Default
101
+ if install_mode is None:
102
+ install_mode = _MODE_ENUM_MAP.get(mode.lower(), LazyInstallMode.SMART)
103
+ cls._load_modes[package_key] = load_mode
104
+ cls._install_modes[package_key] = install_mode
105
+ cls._mode_configs[package_key] = LazyModeConfig(
106
+ load_mode=load_mode,
107
+ install_mode=install_mode
108
+ )
109
+ else:
110
+ # Legacy mode string - try to resolve to preset or default
111
+ preset = get_preset_mode(mode)
112
+ if preset:
113
+ cls._mode_configs[package_key] = preset
114
+ cls._load_modes[package_key] = preset.load_mode
115
+ cls._install_modes[package_key] = preset.install_mode
116
+ else:
117
+ # Fallback to legacy behavior
118
+ install_mode_enum = _MODE_ENUM_MAP.get(mode.lower(), LazyInstallMode.SMART)
119
+ cls._load_modes[package_key] = LazyLoadMode.AUTO
120
+ cls._install_modes[package_key] = install_mode_enum
121
+ cls._mode_configs[package_key] = LazyModeConfig(
122
+ load_mode=LazyLoadMode.AUTO,
123
+ install_mode=install_mode_enum
124
+ )
125
+
126
+ cls._initialize_package(package_key, enabled, mode, install_hook=install_hook)
127
+
128
+ @classmethod
129
+ def _initialize_package(cls, package_key: str, enabled: bool, mode: str, install_hook: bool = True) -> None:
130
+ """Initialize lazy installation for a specific package."""
131
+ global logger, _log
132
+ if logger is None:
133
+ logger = _get_logger()
134
+ if _log is None:
135
+ _log = _get_log_event()
136
+
137
+ # Deferred imports to avoid circular dependency
138
+ from .install_registry import LazyInstallerRegistry
139
+ from ...facade import (
140
+ enable_lazy_install,
141
+ disable_lazy_install,
142
+ set_lazy_install_mode,
143
+ enable_lazy_imports,
144
+ install_import_hook,
145
+ uninstall_import_hook,
146
+ is_import_hook_installed,
147
+ sync_manifest_configuration,
148
+ )
149
+ import asyncio
150
+
151
+ if enabled:
152
+ try:
153
+ # Don't call enable_lazy_install() here - it would create infinite recursion
154
+ # The config is already set by LazyInstallConfig.set() above
155
+
156
+ # Use explicitly set install_mode from config, or derive from mode string
157
+ # Check if install_mode was explicitly set by checking if package_key exists in _install_modes
158
+ if package_key in cls._install_modes:
159
+ # install_mode was explicitly set in set() method, don't override it
160
+ mode_enum = cls._install_modes[package_key]
161
+ else:
162
+ # Not explicitly set, derive from mode string
163
+ mode_enum = _MODE_ENUM_MAP.get(mode.lower(), LazyInstallMode.SMART)
164
+ set_lazy_install_mode(package_key, mode_enum)
165
+
166
+ # Get load mode from config
167
+ load_mode = cls.get_load_mode(package_key)
168
+
169
+ # Enable lazy imports with appropriate load mode (skip if NONE mode)
170
+ if load_mode != LazyLoadMode.NONE:
171
+ enable_lazy_imports(load_mode, package_name=package_key)
172
+
173
+ # Enable async for modes that support it
174
+ installer = LazyInstallerRegistry.get_instance(package_key)
175
+ if installer and mode_enum in (LazyInstallMode.SMART, LazyInstallMode.FULL, LazyInstallMode.CLEAN, LazyInstallMode.TEMPORARY):
176
+ installer._async_enabled = True
177
+ installer._ensure_async_loop()
178
+
179
+ # For FULL mode, install all dependencies on start
180
+ if mode_enum == LazyInstallMode.FULL:
181
+ loop = installer._async_loop
182
+ if loop:
183
+ asyncio.run_coroutine_threadsafe(installer.install_all_dependencies(), loop)
184
+
185
+ if install_hook:
186
+ if not is_import_hook_installed(package_key):
187
+ install_import_hook(package_key)
188
+ _log("config", logger.info, f"✅ Lazy installation initialized for {package_key} (install_mode: {mode}, load_mode: {load_mode.value}, hook: installed)")
189
+ else:
190
+ uninstall_import_hook(package_key)
191
+ _log("config", logger.info, f"✅ Lazy installation initialized for {package_key} (install_mode: {mode}, load_mode: {load_mode.value}, hook: disabled)")
192
+
193
+ cls._initialized[package_key] = True
194
+ sync_manifest_configuration(package_key)
195
+ except ImportError as e:
196
+ if logger is None:
197
+ logger = _get_logger()
198
+ logger.warning(f"⚠️ Could not enable lazy install for {package_key}: {e}")
199
+ else:
200
+ try:
201
+ disable_lazy_install(package_key)
202
+ except ImportError:
203
+ pass
204
+ uninstall_import_hook(package_key)
205
+ cls._initialized[package_key] = False
206
+ _log("config", logger.info, f"❌ Lazy installation disabled for {package_key}")
207
+ sync_manifest_configuration(package_key)
208
+
209
+ @classmethod
210
+ def is_enabled(cls, package_name: str) -> bool:
211
+ """Check if lazy installation is enabled for a package."""
212
+ return cls._configs.get(package_name.lower(), False)
213
+
214
+ @classmethod
215
+ def get_mode(cls, package_name: str) -> str:
216
+ """Get the lazy installation mode for a package."""
217
+ return cls._modes.get(package_name.lower(), "auto")
218
+
219
+ @classmethod
220
+ def get_mode_config(cls, package_name: str) -> Optional[LazyModeConfig]:
221
+ """Get the full mode configuration for a package."""
222
+ return cls._mode_configs.get(package_name.lower())
223
+
224
+ @classmethod
225
+ def get_load_mode(cls, package_name: str) -> LazyLoadMode:
226
+ """Get the load mode for a package."""
227
+ return cls._load_modes.get(package_name.lower(), LazyLoadMode.NONE)
228
+
229
+ @classmethod
230
+ def get_install_mode(cls, package_name: str) -> LazyInstallMode:
231
+ """Get the install mode for a package."""
232
+ return cls._install_modes.get(package_name.lower(), LazyInstallMode.NONE)
233
+
234
+ @classmethod
235
+ def set_install_mode(cls, package_name: str, mode: LazyInstallMode) -> None:
236
+ """Set the install mode for a package."""
237
+ package_key = package_name.lower()
238
+ cls._install_modes[package_key] = mode
239
+ # Update mode config if it exists
240
+ if package_key in cls._mode_configs:
241
+ mode_config = cls._mode_configs[package_key]
242
+ cls._mode_configs[package_key] = LazyModeConfig(
243
+ load_mode=mode_config.load_mode,
244
+ install_mode=mode
245
+ )
246
+
@@ -0,0 +1,374 @@
1
+ """
2
+ #exonware/xwlazy/src/exonware/xwlazy/discovery/discovery.py
3
+
4
+ Package discovery implementation.
5
+
6
+ Company: eXonware.com
7
+ Author: Eng. Muhammad AlShehri
8
+ Email: connect@exonware.com
9
+ Version: 0.1.0.19
10
+ Generation Date: 10-Oct-2025
11
+
12
+ This module provides LazyDiscovery class that discovers dependencies from
13
+ project configuration sources with caching support.
14
+ """
15
+
16
+ import json
17
+ import re
18
+ import subprocess
19
+ import sys
20
+ import threading
21
+ from pathlib import Path
22
+ from typing import Dict, List, Optional
23
+
24
+ from ..base import APackageHelper
25
+ from ...defs import DependencyInfo
26
+ from ...common.logger import get_logger, log_event as _log
27
+
28
+ logger = get_logger("xwlazy.discovery")
29
+
30
+
31
+ class LazyDiscovery(APackageHelper):
32
+ """
33
+ Discovers dependencies from project configuration sources.
34
+ Implements caching with file modification time checks.
35
+ """
36
+
37
+ # System/built-in modules that should NEVER be auto-installed
38
+ SYSTEM_MODULES_BLACKLIST = {
39
+ 'pwd', 'grp', 'spwd', 'crypt', 'nis', 'syslog', 'termios', 'tty', 'pty',
40
+ 'fcntl', 'resource', 'msvcrt', 'winreg', 'winsound', '_winapi',
41
+ 'rpython', 'rply', 'rnc2rng', '_dbm',
42
+ 'sys', 'os', 'io', 'time', 'datetime', 'json', 'csv', 'math',
43
+ 'random', 're', 'collections', 'itertools', 'functools', 'operator',
44
+ 'pathlib', 'shutil', 'glob', 'tempfile', 'pickle', 'copy', 'types',
45
+ 'typing', 'abc', 'enum', 'dataclasses', 'contextlib', 'warnings',
46
+ 'logging', 'threading', 'multiprocessing', 'subprocess', 'queue',
47
+ 'socket', 'select', 'signal', 'asyncio', 'concurrent', 'email',
48
+ 'http', 'urllib', 'xml', 'html', 'sqlite3', 'base64', 'hashlib',
49
+ 'hmac', 'secrets', 'ssl', 'binascii', 'struct', 'array', 'weakref',
50
+ 'gc', 'inspect', 'traceback', 'atexit', 'codecs', 'locale', 'gettext',
51
+ 'argparse', 'optparse', 'configparser', 'fileinput', 'stat', 'platform',
52
+ 'unittest', 'doctest', 'pdb', 'profile', 'cProfile', 'timeit', 'trace',
53
+ # Internal / optional modules that must never trigger auto-install
54
+ 'compression', 'socks', 'wimlib',
55
+ }
56
+
57
+ # Common import name to package name mappings
58
+ COMMON_MAPPINGS = {
59
+ 'cv2': 'opencv-python',
60
+ 'PIL': 'Pillow',
61
+ 'Pillow': 'Pillow',
62
+ 'yaml': 'PyYAML',
63
+ 'sklearn': 'scikit-learn',
64
+ 'bs4': 'beautifulsoup4',
65
+ 'dateutil': 'python-dateutil',
66
+ 'requests_oauthlib': 'requests-oauthlib',
67
+ 'google': 'google-api-python-client',
68
+ 'jwt': 'PyJWT',
69
+ 'crypto': 'pycrypto',
70
+ 'Crypto': 'pycrypto',
71
+ 'MySQLdb': 'mysqlclient',
72
+ 'psycopg2': 'psycopg2-binary',
73
+ 'bson': 'pymongo',
74
+ 'lxml': 'lxml',
75
+ 'numpy': 'numpy',
76
+ 'pandas': 'pandas',
77
+ 'matplotlib': 'matplotlib',
78
+ 'seaborn': 'seaborn',
79
+ 'plotly': 'plotly',
80
+ 'django': 'Django',
81
+ 'flask': 'Flask',
82
+ 'fastapi': 'fastapi',
83
+ 'uvicorn': 'uvicorn',
84
+ 'pytest': 'pytest',
85
+ 'black': 'black',
86
+ 'isort': 'isort',
87
+ 'mypy': 'mypy',
88
+ 'psutil': 'psutil',
89
+ 'colorama': 'colorama',
90
+ 'pytz': 'pytz',
91
+ 'aiofiles': 'aiofiles',
92
+ 'watchdog': 'watchdog',
93
+ 'wand': 'Wand',
94
+ 'exifread': 'ExifRead',
95
+ 'piexif': 'piexif',
96
+ 'rawpy': 'rawpy',
97
+ 'imageio': 'imageio',
98
+ 'scipy': 'scipy',
99
+ 'scikit-image': 'scikit-image',
100
+ 'opencv-python': 'opencv-python',
101
+ 'opencv-contrib-python': 'opencv-contrib-python',
102
+ 'opentelemetry': 'opentelemetry-api',
103
+ 'opentelemetry.trace': 'opentelemetry-api',
104
+ 'opentelemetry.sdk': 'opentelemetry-sdk',
105
+ }
106
+
107
+ def _discover_from_sources(self) -> None:
108
+ """Discover dependencies from all sources."""
109
+ self._discover_from_pyproject_toml()
110
+ self._discover_from_requirements_txt()
111
+ self._discover_from_setup_py()
112
+ self._discover_from_custom_config()
113
+ self._add_common_mappings() # Add well-known mappings (bson->pymongo, cv2->opencv-python, etc.)
114
+
115
+ def _is_cache_valid(self) -> bool:
116
+ """Check if cached dependencies are still valid."""
117
+ if not self._cache_valid or not self._cached_dependencies:
118
+ return False
119
+
120
+ config_files = [
121
+ self.project_root / 'pyproject.toml',
122
+ self.project_root / 'requirements.txt',
123
+ self.project_root / 'setup.py',
124
+ ]
125
+
126
+ for config_file in config_files:
127
+ if config_file.exists():
128
+ try:
129
+ current_mtime = config_file.stat().st_mtime
130
+ cached_mtime = self._file_mtimes.get(str(config_file), 0)
131
+ if current_mtime > cached_mtime:
132
+ return False
133
+ except Exception:
134
+ return False
135
+
136
+ return True
137
+
138
+ def _update_file_mtimes(self) -> None:
139
+ """Update file modification times for cache validation."""
140
+ config_files = [
141
+ self.project_root / 'pyproject.toml',
142
+ self.project_root / 'requirements.txt',
143
+ self.project_root / 'setup.py',
144
+ ]
145
+ for config_file in config_files:
146
+ if config_file.exists():
147
+ try:
148
+ self._file_mtimes[str(config_file)] = config_file.stat().st_mtime
149
+ except Exception:
150
+ pass
151
+
152
+ def _discover_from_pyproject_toml(self) -> None:
153
+ """Discover dependencies from pyproject.toml."""
154
+ pyproject_path = self.project_root / 'pyproject.toml'
155
+ if not pyproject_path.exists():
156
+ return
157
+
158
+ try:
159
+ try:
160
+ import tomllib # Python 3.11+
161
+ toml_parser = tomllib # type: ignore[assignment]
162
+ except ImportError:
163
+ try:
164
+ import tomli as tomllib # type: ignore[assignment]
165
+ toml_parser = tomllib
166
+ except ImportError:
167
+ _log(
168
+ "discovery",
169
+ "TOML parser not available; attempting to lazy-install 'tomli'...",
170
+ )
171
+ try:
172
+ subprocess.run(
173
+ [sys.executable, "-m", "pip", "install", "tomli"],
174
+ check=False,
175
+ capture_output=True,
176
+ )
177
+ import tomli as tomllib # type: ignore[assignment]
178
+ toml_parser = tomllib
179
+ except Exception as install_exc:
180
+ logger.warning(
181
+ "tomli installation failed; skipping pyproject.toml discovery "
182
+ f"({install_exc})"
183
+ )
184
+ return
185
+
186
+ with open(pyproject_path, 'rb') as f:
187
+ data = toml_parser.load(f)
188
+
189
+ dependencies = []
190
+ if 'project' in data and 'dependencies' in data['project']:
191
+ dependencies.extend(data['project']['dependencies'])
192
+
193
+ if 'project' in data and 'optional-dependencies' in data['project']:
194
+ for group_name, group_deps in data['project']['optional-dependencies'].items():
195
+ dependencies.extend(group_deps)
196
+
197
+ if 'build-system' in data and 'requires' in data['build-system']:
198
+ dependencies.extend(data['build-system']['requires'])
199
+
200
+ for dep in dependencies:
201
+ self._parse_dependency_string(dep, 'pyproject.toml')
202
+
203
+ self._discovery_sources.append('pyproject.toml')
204
+ except Exception as e:
205
+ logger.warning(f"Could not parse pyproject.toml: {e}")
206
+
207
+ def _discover_from_requirements_txt(self) -> None:
208
+ """Discover dependencies from requirements.txt."""
209
+ requirements_path = self.project_root / 'requirements.txt'
210
+ if not requirements_path.exists():
211
+ return
212
+
213
+ try:
214
+ with open(requirements_path, 'r', encoding='utf-8') as f:
215
+ for line in f:
216
+ line = line.strip()
217
+ if line and not line.startswith('#'):
218
+ self._parse_dependency_string(line, 'requirements.txt')
219
+
220
+ self._discovery_sources.append('requirements.txt')
221
+ except Exception as e:
222
+ logger.warning(f"Could not parse requirements.txt: {e}")
223
+
224
+ def _discover_from_setup_py(self) -> None:
225
+ """Discover dependencies from setup.py."""
226
+ setup_path = self.project_root / 'setup.py'
227
+ if not setup_path.exists():
228
+ return
229
+
230
+ try:
231
+ with open(setup_path, 'r', encoding='utf-8') as f:
232
+ content = f.read()
233
+
234
+ install_requires_match = re.search(
235
+ r'install_requires\s*=\s*\[(.*?)\]',
236
+ content,
237
+ re.DOTALL
238
+ )
239
+ if install_requires_match:
240
+ deps_str = install_requires_match.group(1)
241
+ deps = re.findall(r'["\']([^"\']+)["\']', deps_str)
242
+ for dep in deps:
243
+ self._parse_dependency_string(dep, 'setup.py')
244
+
245
+ self._discovery_sources.append('setup.py')
246
+ except Exception as e:
247
+ logger.warning(f"Could not parse setup.py: {e}")
248
+
249
+ def _discover_from_custom_config(self) -> None:
250
+ """Discover dependencies from custom configuration files."""
251
+ config_files = [
252
+ 'dependency-mappings.json',
253
+ 'lazy-dependencies.json',
254
+ 'dependencies.json'
255
+ ]
256
+
257
+ for config_file in config_files:
258
+ config_path = self.project_root / config_file
259
+ if config_path.exists():
260
+ try:
261
+ with open(config_path, 'r', encoding='utf-8') as f:
262
+ data = json.load(f)
263
+
264
+ if isinstance(data, dict):
265
+ for import_name, package_name in data.items():
266
+ self.discovered_dependencies[import_name] = DependencyInfo(
267
+ import_name=import_name,
268
+ package_name=package_name,
269
+ source=config_file,
270
+ category='custom'
271
+ )
272
+
273
+ self._discovery_sources.append(config_file)
274
+ except Exception as e:
275
+ logger.warning(f"Could not parse {config_file}: {e}")
276
+
277
+ def _parse_dependency_string(self, dep_str: str, source: str) -> None:
278
+ """Parse a dependency string and extract dependency information."""
279
+ dep_str = re.sub(r'[>=<!=~]+.*', '', dep_str)
280
+ dep_str = re.sub(r'\[.*\]', '', dep_str)
281
+ dep_str = dep_str.strip()
282
+
283
+ if not dep_str:
284
+ return
285
+
286
+ import_name = dep_str
287
+ package_name = dep_str
288
+
289
+ if dep_str in self.COMMON_MAPPINGS:
290
+ package_name = self.COMMON_MAPPINGS[dep_str]
291
+ elif dep_str in self.COMMON_MAPPINGS.values():
292
+ for imp_name, pkg_name in self.COMMON_MAPPINGS.items():
293
+ if pkg_name == dep_str:
294
+ import_name = imp_name
295
+ break
296
+
297
+ self.discovered_dependencies[import_name] = DependencyInfo(
298
+ import_name=import_name,
299
+ package_name=package_name,
300
+ source=source,
301
+ category='discovered'
302
+ )
303
+
304
+ def _add_common_mappings(self) -> None:
305
+ """Add common mappings that might not be in dependency files."""
306
+ for import_name, package_name in self.COMMON_MAPPINGS.items():
307
+ if import_name not in self.discovered_dependencies:
308
+ self.discovered_dependencies[import_name] = DependencyInfo(
309
+ import_name=import_name,
310
+ package_name=package_name,
311
+ source='common_mappings',
312
+ category='common'
313
+ )
314
+
315
+ def get_package_for_import(self, import_name: str) -> Optional[str]:
316
+ """Get package name for a given import name."""
317
+ mapping = self.discover_all_dependencies()
318
+ return mapping.get(import_name)
319
+
320
+ def get_imports_for_package(self, package_name: str) -> List[str]:
321
+ """Get all possible import names for a package."""
322
+ mapping = self.get_package_import_mapping()
323
+ return mapping.get(package_name, [package_name])
324
+
325
+ def get_package_import_mapping(self) -> Dict[str, List[str]]:
326
+ """Get mapping of package names to their possible import names."""
327
+ self.discover_all_dependencies()
328
+
329
+ package_to_imports = {}
330
+ for import_name, dep_info in self.discovered_dependencies.items():
331
+ package_name = dep_info.package_name
332
+
333
+ if package_name not in package_to_imports:
334
+ package_to_imports[package_name] = [package_name]
335
+
336
+ if import_name != package_name:
337
+ if import_name not in package_to_imports[package_name]:
338
+ package_to_imports[package_name].append(import_name)
339
+
340
+ return package_to_imports
341
+
342
+ def get_import_package_mapping(self) -> Dict[str, str]:
343
+ """Get mapping of import names to package names."""
344
+ self.discover_all_dependencies()
345
+ return {import_name: dep_info.package_name for import_name, dep_info in self.discovered_dependencies.items()}
346
+
347
+ def export_to_json(self, file_path: str) -> None:
348
+ """Export discovered dependencies to JSON file."""
349
+ data = {
350
+ 'dependencies': {name: info.package_name for name, info in self.discovered_dependencies.items()},
351
+ 'sources': self.get_discovery_sources(),
352
+ 'total_count': len(self.discovered_dependencies)
353
+ }
354
+
355
+ with open(file_path, 'w', encoding='utf-8') as f:
356
+ json.dump(data, f, indent=2, ensure_ascii=False)
357
+
358
+
359
+ # Global discovery instance
360
+ _discovery: Optional[LazyDiscovery] = None
361
+ _discovery_lock = threading.RLock()
362
+
363
+
364
+ def get_lazy_discovery(project_root: Optional[str] = None) -> LazyDiscovery:
365
+ """Get or create global discovery instance."""
366
+ global _discovery
367
+ with _discovery_lock:
368
+ if _discovery is None:
369
+ _discovery = LazyDiscovery(project_root)
370
+ return _discovery
371
+
372
+
373
+ __all__ = ['LazyDiscovery', 'get_lazy_discovery']
374
+