hatch-xclam 0.7.0__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 (93) hide show
  1. hatch/__init__.py +21 -0
  2. hatch/cli_hatch.py +2748 -0
  3. hatch/environment_manager.py +1375 -0
  4. hatch/installers/__init__.py +25 -0
  5. hatch/installers/dependency_installation_orchestrator.py +636 -0
  6. hatch/installers/docker_installer.py +545 -0
  7. hatch/installers/hatch_installer.py +198 -0
  8. hatch/installers/installation_context.py +109 -0
  9. hatch/installers/installer_base.py +195 -0
  10. hatch/installers/python_installer.py +342 -0
  11. hatch/installers/registry.py +179 -0
  12. hatch/installers/system_installer.py +588 -0
  13. hatch/mcp_host_config/__init__.py +38 -0
  14. hatch/mcp_host_config/backup.py +458 -0
  15. hatch/mcp_host_config/host_management.py +572 -0
  16. hatch/mcp_host_config/models.py +602 -0
  17. hatch/mcp_host_config/reporting.py +181 -0
  18. hatch/mcp_host_config/strategies.py +513 -0
  19. hatch/package_loader.py +263 -0
  20. hatch/python_environment_manager.py +734 -0
  21. hatch/registry_explorer.py +171 -0
  22. hatch/registry_retriever.py +335 -0
  23. hatch/template_generator.py +179 -0
  24. hatch_xclam-0.7.0.dist-info/METADATA +150 -0
  25. hatch_xclam-0.7.0.dist-info/RECORD +93 -0
  26. hatch_xclam-0.7.0.dist-info/WHEEL +5 -0
  27. hatch_xclam-0.7.0.dist-info/entry_points.txt +2 -0
  28. hatch_xclam-0.7.0.dist-info/licenses/LICENSE +661 -0
  29. hatch_xclam-0.7.0.dist-info/top_level.txt +2 -0
  30. tests/__init__.py +1 -0
  31. tests/run_environment_tests.py +124 -0
  32. tests/test_cli_version.py +122 -0
  33. tests/test_data/packages/basic/base_pkg/hatch_mcp_server.py +18 -0
  34. tests/test_data/packages/basic/base_pkg/mcp_server.py +21 -0
  35. tests/test_data/packages/basic/base_pkg_v2/hatch_mcp_server.py +18 -0
  36. tests/test_data/packages/basic/base_pkg_v2/mcp_server.py +21 -0
  37. tests/test_data/packages/basic/utility_pkg/hatch_mcp_server.py +18 -0
  38. tests/test_data/packages/basic/utility_pkg/mcp_server.py +21 -0
  39. tests/test_data/packages/dependencies/complex_dep_pkg/hatch_mcp_server.py +18 -0
  40. tests/test_data/packages/dependencies/complex_dep_pkg/mcp_server.py +21 -0
  41. tests/test_data/packages/dependencies/docker_dep_pkg/hatch_mcp_server.py +18 -0
  42. tests/test_data/packages/dependencies/docker_dep_pkg/mcp_server.py +21 -0
  43. tests/test_data/packages/dependencies/mixed_dep_pkg/hatch_mcp_server.py +18 -0
  44. tests/test_data/packages/dependencies/mixed_dep_pkg/mcp_server.py +21 -0
  45. tests/test_data/packages/dependencies/python_dep_pkg/hatch_mcp_server.py +18 -0
  46. tests/test_data/packages/dependencies/python_dep_pkg/mcp_server.py +21 -0
  47. tests/test_data/packages/dependencies/simple_dep_pkg/hatch_mcp_server.py +18 -0
  48. tests/test_data/packages/dependencies/simple_dep_pkg/mcp_server.py +21 -0
  49. tests/test_data/packages/dependencies/system_dep_pkg/hatch_mcp_server.py +18 -0
  50. tests/test_data/packages/dependencies/system_dep_pkg/mcp_server.py +21 -0
  51. tests/test_data/packages/error_scenarios/circular_dep_pkg/hatch_mcp_server.py +18 -0
  52. tests/test_data/packages/error_scenarios/circular_dep_pkg/mcp_server.py +21 -0
  53. tests/test_data/packages/error_scenarios/circular_dep_pkg_b/hatch_mcp_server.py +18 -0
  54. tests/test_data/packages/error_scenarios/circular_dep_pkg_b/mcp_server.py +21 -0
  55. tests/test_data/packages/error_scenarios/invalid_dep_pkg/hatch_mcp_server.py +18 -0
  56. tests/test_data/packages/error_scenarios/invalid_dep_pkg/mcp_server.py +21 -0
  57. tests/test_data/packages/error_scenarios/version_conflict_pkg/hatch_mcp_server.py +18 -0
  58. tests/test_data/packages/error_scenarios/version_conflict_pkg/mcp_server.py +21 -0
  59. tests/test_data/packages/schema_versions/schema_v1_1_0_pkg/main.py +11 -0
  60. tests/test_data/packages/schema_versions/schema_v1_2_0_pkg/main.py +11 -0
  61. tests/test_data/packages/schema_versions/schema_v1_2_1_pkg/hatch_mcp_server.py +18 -0
  62. tests/test_data/packages/schema_versions/schema_v1_2_1_pkg/mcp_server.py +21 -0
  63. tests/test_data_utils.py +472 -0
  64. tests/test_dependency_orchestrator_consent.py +266 -0
  65. tests/test_docker_installer.py +524 -0
  66. tests/test_env_manip.py +991 -0
  67. tests/test_hatch_installer.py +179 -0
  68. tests/test_installer_base.py +221 -0
  69. tests/test_mcp_atomic_operations.py +276 -0
  70. tests/test_mcp_backup_integration.py +308 -0
  71. tests/test_mcp_cli_all_host_specific_args.py +303 -0
  72. tests/test_mcp_cli_backup_management.py +295 -0
  73. tests/test_mcp_cli_direct_management.py +453 -0
  74. tests/test_mcp_cli_discovery_listing.py +582 -0
  75. tests/test_mcp_cli_host_config_integration.py +823 -0
  76. tests/test_mcp_cli_package_management.py +360 -0
  77. tests/test_mcp_cli_partial_updates.py +859 -0
  78. tests/test_mcp_environment_integration.py +520 -0
  79. tests/test_mcp_host_config_backup.py +257 -0
  80. tests/test_mcp_host_configuration_manager.py +331 -0
  81. tests/test_mcp_host_registry_decorator.py +348 -0
  82. tests/test_mcp_pydantic_architecture_v4.py +603 -0
  83. tests/test_mcp_server_config_models.py +242 -0
  84. tests/test_mcp_server_config_type_field.py +221 -0
  85. tests/test_mcp_sync_functionality.py +316 -0
  86. tests/test_mcp_user_feedback_reporting.py +359 -0
  87. tests/test_non_tty_integration.py +281 -0
  88. tests/test_online_package_loader.py +202 -0
  89. tests/test_python_environment_manager.py +882 -0
  90. tests/test_python_installer.py +327 -0
  91. tests/test_registry.py +51 -0
  92. tests/test_registry_retriever.py +250 -0
  93. tests/test_system_installer.py +733 -0
@@ -0,0 +1,171 @@
1
+ """Utilities for exploring a Hatch package registry.
2
+
3
+ This module provides functions to search and extract information from
4
+ a Hatch registry data structure (see hatch_all_pkg_metadata_schema.json).
5
+ """
6
+ from typing import Any, Dict, List, Optional, Tuple
7
+ from packaging.version import Version, InvalidVersion
8
+ from packaging.specifiers import SpecifierSet, InvalidSpecifier
9
+
10
+ def find_repository(registry: Dict[str, Any], repo_name: str) -> Optional[Dict[str, Any]]:
11
+ """Find a repository by name.
12
+
13
+ Args:
14
+ registry (Dict[str, Any]): The registry data.
15
+ repo_name (str): Name of the repository to find.
16
+
17
+ Returns:
18
+ Optional[Dict[str, Any]]: Repository data if found, None otherwise.
19
+ """
20
+ for repo in registry.get("repositories", []):
21
+ if repo.get("name") == repo_name:
22
+ return repo
23
+ return None
24
+
25
+ def list_repositories(registry: Dict[str, Any]) -> List[str]:
26
+ """List all repository names in the registry.
27
+
28
+ Args:
29
+ registry (Dict[str, Any]): The registry data.
30
+
31
+ Returns:
32
+ List[str]: List of repository names.
33
+ """
34
+ return [repo.get("name") for repo in registry.get("repositories", [])]
35
+
36
+ def find_package(registry: Dict[str, Any], package_name: str, repo_name: Optional[str] = None) -> Optional[Dict[str, Any]]:
37
+ """Find a package by name, optionally within a specific repository.
38
+
39
+ Args:
40
+ registry (Dict[str, Any]): The registry data.
41
+ package_name (str): Name of the package to find.
42
+ repo_name (str, optional): Name of the repository to search in. Defaults to None.
43
+
44
+ Returns:
45
+ Optional[Dict[str, Any]]: Package data if found, None otherwise.
46
+ """
47
+ repos = registry.get("repositories", [])
48
+ if repo_name:
49
+ repos = [r for r in repos if r.get("name") == repo_name]
50
+ for repo in repos:
51
+ for pkg in repo.get("packages", []):
52
+ if pkg.get("name") == package_name:
53
+ return pkg
54
+ return None
55
+
56
+ def list_packages(registry: Dict[str, Any], repo_name: Optional[str] = None) -> List[str]:
57
+ """List all package names, optionally within a specific repository.
58
+
59
+ Args:
60
+ registry (Dict[str, Any]): The registry data.
61
+ repo_name (str, optional): Name of the repository to list packages from. Defaults to None.
62
+
63
+ Returns:
64
+ List[str]: List of package names.
65
+ """
66
+ packages = []
67
+ repos = registry.get("repositories", [])
68
+ if repo_name:
69
+ repos = [r for r in repos if r.get("name") == repo_name]
70
+ for repo in repos:
71
+ for pkg in repo.get("packages", []):
72
+ packages.append(pkg.get("name"))
73
+ return packages
74
+
75
+ def get_latest_version(pkg: Dict[str, Any]) -> Optional[str]:
76
+ """Get the latest version string for a package dict.
77
+
78
+ Args:
79
+ pkg (Dict[str, Any]): The package dictionary.
80
+
81
+ Returns:
82
+ Optional[str]: Latest version string if available, None otherwise.
83
+ """
84
+ return pkg.get("latest_version")
85
+
86
+ def _match_version_constraint(version: str, constraint: str) -> bool:
87
+ """Check if a version string matches a constraint.
88
+
89
+ Uses the 'packaging' library for robust version comparison.
90
+ If a simple version like "1.0.0" is passed as constraint, it's treated as "==1.0.0".
91
+
92
+ Args:
93
+ version (str): Version string to check.
94
+ constraint (str): Version constraint (e.g., '>=1.2.0').
95
+
96
+ Returns:
97
+ bool: True if version matches constraint, False otherwise.
98
+ """
99
+ try:
100
+ v = Version(version)
101
+
102
+ # Convert the constraint to a proper SpecifierSet if it doesn't have an operator
103
+ if constraint and not any(constraint.startswith(op) for op in ['==', '!=', '<=', '>=', '<', '>']):
104
+ constraint = f"=={constraint}"
105
+
106
+ # Accept constraints like '==1.2.3', '>=1.0.0', etc.
107
+ spec = SpecifierSet(constraint)
108
+ return v in spec
109
+ except (InvalidVersion, InvalidSpecifier):
110
+ # If we can't parse versions, fall back to string comparison
111
+ return version == constraint
112
+
113
+ def find_package_version(pkg: Dict[str, Any], version_constraint: Optional[str] = None) -> Optional[Dict[str, Any]]:
114
+ """Find a version dict for a package, optionally matching a version constraint.
115
+
116
+ This function uses a multi-step approach to find the appropriate version:
117
+ 1. If no constraint is given, it returns the latest version
118
+ 2. If that's not found, it falls back to the highest version number
119
+ 3. For specific constraints, it sorts versions and checks compatibility
120
+
121
+ Args:
122
+ pkg (Dict[str, Any]): The package dictionary.
123
+ version_constraint (str, optional): A version constraint string (e.g., '>=1.2.0'). Defaults to None.
124
+
125
+ Returns:
126
+ Optional[Dict[str, Any]]: The version dict matching the constraint or latest version.
127
+ """
128
+ versions = pkg.get("versions", [])
129
+ if not versions:
130
+ return None
131
+ if not version_constraint:
132
+ # Return the version dict matching latest_version
133
+ latest = pkg.get("latest_version")
134
+ for v in versions:
135
+ if v.get("version") == latest:
136
+ return v
137
+ # fallback: return the highest version
138
+ try:
139
+ return max(versions, key=lambda x: Version(x.get("version", "0")))
140
+ except Exception:
141
+ return versions[-1] # Try to find a version matching the constraint
142
+ try:
143
+ sorted_versions = sorted(versions, key=lambda x: Version(x.get("version", "0")), reverse=True)
144
+ except Exception:
145
+ sorted_versions = versions
146
+
147
+ # If no exact match, try parsing as a constraint
148
+ for v in sorted_versions:
149
+ if _match_version_constraint(v.get("version", ""), version_constraint):
150
+ return v
151
+ return None
152
+
153
+ def get_package_release_url(pkg: Dict[str, Any], version_constraint: Optional[str] = None) -> Tuple[Optional[str], Optional[str]]:
154
+ """Get the release URI for a package version matching the constraint (or latest).
155
+
156
+ Args:
157
+ pkg (Dict[str, Any]): The package dictionary.
158
+ version_constraint (str, optional): A version constraint string (e.g., '>=1.2.0'). Defaults to None.
159
+
160
+ Returns:
161
+ Tuple[Optional[str], Optional[str]]: A tuple containing:
162
+ - str: The release URI satisfying the constraint (or None)
163
+ - str: The matching version string (or None)
164
+ """
165
+ if pkg is None:
166
+ return None, None
167
+
168
+ vdict = find_package_version(pkg, version_constraint)
169
+ if vdict:
170
+ return vdict.get("release_uri"), vdict.get("version")
171
+ return None, None
@@ -0,0 +1,335 @@
1
+ """Registry retriever for Hatch package management.
2
+
3
+ This module provides functionality to retrieve and manage the Hatch package registry,
4
+ supporting both online and simulation modes with caching at file system and in-memory levels.
5
+ """
6
+
7
+ import os
8
+ import json
9
+ import logging
10
+ import requests
11
+ import hashlib
12
+ import time
13
+ import datetime
14
+ from pathlib import Path
15
+ from typing import Dict, Any, Optional, Tuple, Union
16
+ from urllib.parse import urlparse
17
+
18
+ class RegistryRetriever:
19
+ """Manages the retrieval and caching of the Hatch package registry.
20
+
21
+ Provides caching at file system level and in-memory level with persistent
22
+ timestamp tracking for cache freshness across CLI invocations.
23
+ Works in both local simulation and online GitHub environments.
24
+ Handles registry timing issues with fallback to previous day's registry.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ cache_ttl: int = 86400, # Default TTL is 24 hours
30
+ local_cache_dir: Optional[Path] = None,
31
+ simulation_mode: bool = False, # Set to True when running in local simulation mode
32
+ local_registry_cache_path: Optional[Path] = None
33
+ ):
34
+ """Initialize the registry retriever.
35
+
36
+ Args:
37
+ cache_ttl (int): Time-to-live for cache in seconds. Defaults to 86400 (24 hours).
38
+ local_cache_dir (Path, optional): Directory to store local cache files. Defaults to ~/.hatch.
39
+ simulation_mode (bool): Whether to operate in local simulation mode. Defaults to False.
40
+ local_registry_cache_path (Path, optional): Path to local registry file. Defaults to None.
41
+ """
42
+ self.logger = logging.getLogger('hatch.registry_retriever')
43
+ self.logger.setLevel(logging.INFO)
44
+
45
+ self.cache_ttl = cache_ttl
46
+ self.simulation_mode = simulation_mode
47
+ self.is_delayed = False # Flag to indicate if using a previous day's registry
48
+
49
+ # Initialize cache directory
50
+ self.cache_dir = local_cache_dir or Path.home() / ".hatch"
51
+
52
+ # Create cache directory if it doesn't exist
53
+ self.cache_dir.mkdir(parents=True, exist_ok=True) # Set up registry source based on mode
54
+ if simulation_mode:
55
+ # Local simulation mode - use local registry file
56
+ self.registry_cache_path = local_registry_cache_path or self.cache_dir / "registry" / "hatch_packages_registry.json"
57
+
58
+ # Use file:// URL format for local files
59
+ self.registry_url = f"file://{str(self.registry_cache_path.absolute())}"
60
+ self.logger.info(f"Operating in simulation mode with registry at: {self.registry_cache_path}")
61
+ else:
62
+ # Online mode - set today's date as the default target
63
+ self.today_date = datetime.datetime.now(datetime.timezone.utc).date()
64
+ self.today_str = self.today_date.strftime('%Y-%m-%d')
65
+
66
+ # We'll set the initial URL to today, but might fall back to yesterday
67
+ self.registry_url = f"https://github.com/CrackingShells/Hatch-Registry/releases/download/{self.today_str}/hatch_packages_registry.json"
68
+ self.logger.info(f"Operating in online mode with registry at: {self.registry_url}")
69
+
70
+ # Generate cache filename - same regardless of which day's registry we end up using
71
+ self.registry_cache_path = self.cache_dir / "registry" / "hatch_packages_registry.json"
72
+
73
+ # In-memory cache
74
+ self._registry_cache = None
75
+ self._last_fetch_time = 0
76
+
77
+ # Set up persistent timestamp file path
78
+ self._last_fetch_time_path = self.cache_dir / "registry" / ".last_fetch_time"
79
+
80
+ # Load persistent timestamp on initialization
81
+ self._load_last_fetch_time()
82
+
83
+ def _load_last_fetch_time(self) -> None:
84
+ """Load the last fetch timestamp from persistent storage.
85
+
86
+ Reads the timestamp from the .last_fetch_time file and sets
87
+ self._last_fetch_time accordingly. If the file is missing or
88
+ corrupt, treats the cache as outdated.
89
+ """
90
+ try:
91
+ if self._last_fetch_time_path.exists():
92
+ with open(self._last_fetch_time_path, 'r', encoding='utf-8') as f:
93
+ timestamp_str = f.read().strip()
94
+ # Parse ISO8601 timestamp
95
+ timestamp_dt = datetime.datetime.fromisoformat(timestamp_str.replace('Z', '+00:00'))
96
+ self._last_fetch_time = timestamp_dt.timestamp()
97
+ self.logger.debug(f"Loaded last fetch time from disk: {timestamp_str}")
98
+ else:
99
+ self.logger.debug("No persistent timestamp file found, treating cache as outdated")
100
+ except Exception as e:
101
+ self.logger.warning(f"Failed to read persistent timestamp: {e}, treating cache as outdated")
102
+ self._last_fetch_time = 0
103
+
104
+ def _save_last_fetch_time(self) -> None:
105
+ """Save the current fetch timestamp to persistent storage.
106
+
107
+ Writes the current UTC timestamp to the .last_fetch_time file
108
+ in ISO8601 format for persistence across CLI invocations.
109
+ """
110
+ try:
111
+ # Ensure directory exists
112
+ self._last_fetch_time_path.parent.mkdir(parents=True, exist_ok=True)
113
+
114
+ # Write current UTC time in ISO8601 format
115
+ current_time = datetime.datetime.now(datetime.timezone.utc)
116
+ timestamp_str = current_time.isoformat().replace('+00:00', 'Z')
117
+
118
+ with open(self._last_fetch_time_path, 'w', encoding='utf-8') as f:
119
+ f.write(timestamp_str)
120
+
121
+ self.logger.debug(f"Saved last fetch time to disk: {timestamp_str}")
122
+ except Exception as e:
123
+ self.logger.warning(f"Failed to save persistent timestamp: {e}")
124
+
125
+ def _read_local_cache(self) -> Dict[str, Any]:
126
+ """Read the registry from local cache file.
127
+
128
+ Returns:
129
+ Dict[str, Any]: Registry data from cache.
130
+
131
+ Raises:
132
+ Exception: If reading the cache file fails.
133
+ """
134
+ try:
135
+ with open(self.registry_cache_path, 'r') as f:
136
+ return json.load(f)
137
+ except Exception as e:
138
+ self.logger.error(f"Failed to read local registry file: {e}")
139
+ raise e
140
+
141
+ def _write_local_cache(self, registry_data: Dict[str, Any]) -> None:
142
+ """Write the registry data to local cache file.
143
+
144
+ Args:
145
+ registry_data (Dict[str, Any]): Registry data to cache.
146
+ """
147
+ try:
148
+ with open(self.registry_cache_path, 'w') as f:
149
+ json.dump(registry_data, f, indent=2)
150
+ except Exception as e:
151
+ self.logger.error(f"Failed to write local cache: {e}")
152
+
153
+ def _fetch_remote_registry(self) -> Dict[str, Any]:
154
+ """Fetch registry data from remote URL with fallback to previous day.
155
+
156
+ Attempts to fetch today's registry first, falling back to previous day if necessary.
157
+ Updates the is_delayed flag based on which registry was successfully retrieved.
158
+
159
+ Returns:
160
+ Dict[str, Any]: Registry data from remote source.
161
+
162
+ Raises:
163
+ Exception: If fetching both today's and yesterday's registry fails.
164
+ """
165
+ if self.simulation_mode:
166
+ try:
167
+ self.logger.info(f"Fetching registry from {self.registry_url}")
168
+ with open(self.registry_cache_path, 'r') as f:
169
+ return json.load(f)
170
+ except Exception as e:
171
+ self.logger.error(f"Failed to fetch registry in simulation mode: {e}")
172
+ raise e
173
+
174
+ # Online mode - try today's registry first
175
+ date = self.today_date.strftime('%Y-%m-%d')
176
+ if self._registry_exists(date):
177
+ self.registry_url = f"https://github.com/CrackingShells/Hatch-Registry/releases/download/{date}/hatch_packages_registry.json"
178
+ self.is_delayed = False # Reset delayed flag for today's registry
179
+ else:
180
+ self.logger.info(f"Today's registry ({date}) not found, falling back to yesterday's")
181
+ # Fall back to yesterday's registry
182
+ yesterday = self.today_date - datetime.timedelta(days=1)
183
+ date = yesterday.strftime('%Y-%m-%d')
184
+
185
+ if not self._registry_exists(date):
186
+ self.logger.error(f"Yesterday's registry ({date}) also not found, cannot proceed")
187
+ raise Exception("No valid registry found for today or yesterday")
188
+
189
+ # Use yesterday's registry URL
190
+ self.registry_url = f"https://github.com/CrackingShells/Hatch-Registry/releases/download/{date}/hatch_packages_registry.json"
191
+ self.is_delayed = True # Set delayed flag for yesterday's registry
192
+
193
+ try:
194
+ self.logger.info(f"Fetching registry from {self.registry_url}")
195
+ response = requests.get(self.registry_url, timeout=30)
196
+ response.raise_for_status()
197
+ return response.json()
198
+
199
+ except Exception as e:
200
+ self.logger.error(f"Failed to fetch registry from {self.registry_url}: {e}")
201
+ raise e
202
+
203
+ def _registry_exists(self, date_str: str) -> bool:
204
+ """Check if registry for the given date exists.
205
+
206
+ Makes a HEAD request to check if the release page for the given date exists.
207
+
208
+ Args:
209
+ date_str (str): Date string in YYYY-MM-DD format.
210
+
211
+ Returns:
212
+ bool: True if registry exists, False otherwise.
213
+ """
214
+ if self.simulation_mode:
215
+ return self.registry_cache_path.exists()
216
+
217
+
218
+ url = f"https://github.com/CrackingShells/Hatch-Registry/releases/tag/{date_str}"
219
+ try:
220
+ response = requests.head(url, timeout=10)
221
+ return response.status_code == 200
222
+ except Exception:
223
+ return False
224
+
225
+ def get_registry(self, force_refresh: bool = False) -> Dict[str, Any]:
226
+ """Fetch the registry file.
227
+
228
+ This method implements a multi-level caching strategy:
229
+ 1. First checks the in-memory cache
230
+ 2. Then checks the local file cache
231
+ 3. Finally fetches from the source (local file or remote URL)
232
+
233
+ The fetched data is stored in both the in-memory and file caches.
234
+
235
+ Args:
236
+ force_refresh (bool, optional): Force refresh the registry even if cache is valid. Defaults to False.
237
+
238
+ Returns:
239
+ Dict[str, Any]: Registry data.
240
+
241
+ Raises:
242
+ Exception: If fetching the registry fails.
243
+ """
244
+ current_time = datetime.datetime.now(datetime.timezone.utc).timestamp()
245
+
246
+ # Check if in-memory cache is valid
247
+ if (not force_refresh and
248
+ self._registry_cache is not None and
249
+ current_time - self._last_fetch_time < self.cache_ttl):
250
+ self.logger.debug("Using in-memory cache")
251
+ return self._registry_cache
252
+
253
+ # Ensure registry cache directory exists
254
+ self.registry_cache_path.parent.mkdir(parents=True, exist_ok=True)
255
+
256
+ # Check if local cache is not outdated
257
+ if not force_refresh and not self.is_cache_outdated():
258
+ try:
259
+ self.logger.debug("Using local cache file")
260
+ registry_data = self._read_local_cache()
261
+ # Update in-memory cache
262
+ self._registry_cache = registry_data
263
+ self._last_fetch_time = current_time
264
+
265
+ return registry_data
266
+ except Exception as e:
267
+ self.logger.warning(f"Error reading local cache: {e}, will fetch from source instead")
268
+ # If reading cache fails, continue to fetch from source
269
+
270
+ # Fetch from source based on mode
271
+ try:
272
+ if self.simulation_mode:
273
+ # In simulation mode, we must have a local registry file
274
+ registry_data = self._read_local_cache()
275
+ else:
276
+ # In online mode, fetch from remote URL
277
+ registry_data = self._fetch_remote_registry()
278
+
279
+ # Update local cache
280
+ # Note that in case of simulation mode AND default cache path,
281
+ # we are rewriting the same file with the same content
282
+ self._write_local_cache(registry_data)
283
+
284
+ # Update in-memory cache
285
+ self._registry_cache = registry_data
286
+ self._last_fetch_time = current_time
287
+
288
+ # Update persistent timestamp
289
+ self._save_last_fetch_time()
290
+
291
+ return registry_data
292
+
293
+ except Exception as e:
294
+ self.logger.error(f"Failed to fetch registry: {e}")
295
+ raise e
296
+
297
+ def is_cache_outdated(self) -> bool:
298
+ """Check if the cached registry is outdated.
299
+
300
+ Determines if the cached registry is outdated based on the persistent
301
+ timestamp and cache TTL. Falls back to file mtime for backward compatibility
302
+ if no persistent timestamp is available.
303
+
304
+ Returns:
305
+ bool: True if cache is outdated, False if cache is current.
306
+ """
307
+ if not self.registry_cache_path.exists():
308
+ return True # If file doesn't exist, consider it outdated
309
+
310
+ now = datetime.datetime.now(datetime.timezone.utc)
311
+
312
+ # Use persistent timestamp if available (primary method)
313
+ if self._last_fetch_time > 0:
314
+ time_since_fetch = now.timestamp() - self._last_fetch_time
315
+ if time_since_fetch > self.cache_ttl:
316
+ return True
317
+
318
+ # Also check if cache is not from today (existing logic)
319
+ last_fetch_dt = datetime.datetime.fromtimestamp(
320
+ self._last_fetch_time, tz=datetime.timezone.utc
321
+ )
322
+ if last_fetch_dt.date() < now.date():
323
+ return True
324
+
325
+ return False
326
+
327
+ return False
328
+
329
+ # Example usage
330
+ if __name__ == "__main__":
331
+ logging.basicConfig(level=logging.INFO)
332
+ retriever = RegistryRetriever()
333
+ registry = retriever.get_registry()
334
+ print(f"Found {len(registry.get('repositories', []))} repositories")
335
+ print(f"Registry last updated: {registry.get('last_updated')}")
@@ -0,0 +1,179 @@
1
+ """
2
+ Template Generator for Hatch packages.
3
+
4
+ This module contains functions to generate template files for Hatch MCP server packages.
5
+ Each function generates a specific file for the package template.
6
+ """
7
+
8
+ import json
9
+ import logging
10
+ from pathlib import Path
11
+
12
+ logger = logging.getLogger("hatch.template_generator")
13
+
14
+
15
+ def generate_init_py() -> str:
16
+ """Generate the __init__.py file content for a template package.
17
+
18
+ Returns:
19
+ str: Content for __init__.py file.
20
+ """
21
+ return "# Hatch package initialization\n"
22
+
23
+
24
+ def generate_mcp_server_py(package_name: str) -> str:
25
+ """Generate the mcp_server.py file content for a template package.
26
+
27
+ Args:
28
+ package_name (str): Name of the package.
29
+
30
+ Returns:
31
+ str: Content for mcp_server.py file.
32
+ """
33
+ return f"""from mcp.server.fastmcp import FastMCP
34
+
35
+ mcp = FastMCP(\"{package_name}\", log_level=\"WARNING\")
36
+
37
+ @mcp.tool()
38
+ def example_tool(param: str) -> str:
39
+ \"\"\"Example tool function.
40
+
41
+ Args:
42
+ param (str): Example parameter.
43
+
44
+ Returns:
45
+ str: Example result.
46
+ \"\"\"
47
+ return f\"Processed: {{param}}\"
48
+
49
+ if __name__ == \"__main__\":
50
+ mcp.run()
51
+ """
52
+
53
+
54
+ def generate_hatch_mcp_server_entry_py(package_name: str) -> str:
55
+ """Generate the hatch_mcp_server_entry.py file content for a template package.
56
+
57
+ Args:
58
+ package_name (str): Name of the package.
59
+
60
+ Returns:
61
+ str: Content for hatch_mcp_server_entry.py file.
62
+ """
63
+ return f"""from hatch_mcp_server import HatchMCP
64
+ from mcp_server import mcp
65
+
66
+ hatch_mcp = HatchMCP(\"{package_name}\",
67
+ fast_mcp=mcp,
68
+ origin_citation=\"Origin citation for {package_name}\",
69
+ mcp_citation=\"MCP citation for {package_name}\")
70
+
71
+ if __name__ == \"__main__\":
72
+ hatch_mcp.server.run()
73
+ """
74
+
75
+
76
+ def generate_metadata_json(package_name: str, description: str = ""):
77
+ """Generate the metadata JSON content for a template package.
78
+
79
+ Args:
80
+ package_name (str): Name of the package.
81
+ description (str, optional): Package description. Defaults to empty string.
82
+
83
+ Returns:
84
+ dict: Metadata dictionary.
85
+ """
86
+ return {
87
+ "package_schema_version": "1.2.1",
88
+ "name": package_name,
89
+ "version": "0.1.0",
90
+ "description": description or f"A Hatch package for {package_name}",
91
+ "tags": [],
92
+ "author": {"name": "Hatch User", "email": ""},
93
+ "license": {"name": "MIT"},
94
+ "entry_point": {
95
+ "mcp_server": "mcp_server.py",
96
+ "hatch_mcp_server": "hatch_mcp_server_entry.py",
97
+ },
98
+ "tools": [{"name": "example_tool", "description": "Example tool function"}],
99
+ "citations": {
100
+ "origin": f"Origin citation for {package_name}",
101
+ "mcp": f"MCP citation for {package_name}",
102
+ },
103
+ }
104
+
105
+
106
+ def generate_readme_md(package_name: str, description: str = "") -> str:
107
+ """Generate the README.md file content for a template package.
108
+
109
+ Args:
110
+ package_name (str): Name of the package.
111
+ description (str, optional): Package description. Defaults to empty string.
112
+
113
+ Returns:
114
+ str: Content for README.md file.
115
+ """
116
+ return f"""# {package_name}
117
+
118
+ {description}
119
+
120
+ ## Tools
121
+
122
+ - **example_tool**: Example tool function
123
+ """
124
+
125
+
126
+ def create_package_template(
127
+ target_dir: Path, package_name: str, description: str = ""
128
+ ) -> Path:
129
+ """Create a package template directory with all necessary files.
130
+
131
+ This function orchestrates the generation of a complete package structure by:
132
+ 1. Creating the package directory
133
+ 2. Generating and writing the __init__.py file
134
+ 3. Generating and writing the mcp_server.py file with example tools
135
+ 4. Generating and writing the hatch_mcp_server_entry.py file that wraps the MCP server
136
+ 5. Creating the hatch_metadata.json with package information
137
+ 6. Generating a README.md with basic documentation
138
+
139
+ Args:
140
+ target_dir (Path): Directory where the package should be created.
141
+ package_name (str): Name of the package.
142
+ description (str, optional): Package description. Defaults to empty string.
143
+
144
+ Returns:
145
+ Path: Path to the created package directory.
146
+ """
147
+ logger.info(f"Creating package template for {package_name} in {target_dir}")
148
+
149
+ # Create package directory
150
+ package_dir = target_dir / package_name
151
+ package_dir.mkdir(parents=True, exist_ok=True)
152
+
153
+ # Create __init__.py
154
+ init_content = generate_init_py()
155
+ with open(package_dir / "__init__.py", "w") as f:
156
+ f.write(init_content)
157
+
158
+ # Create mcp_server.py
159
+ mcp_server_content = generate_mcp_server_py(package_name)
160
+ with open(package_dir / "mcp_server.py", "w") as f:
161
+ f.write(mcp_server_content)
162
+
163
+ # Create hatch_mcp_server_entry.py
164
+ hatch_mcp_server_entry_content = generate_hatch_mcp_server_entry_py(package_name)
165
+ with open(package_dir / "hatch_mcp_server_entry.py", "w") as f:
166
+ f.write(hatch_mcp_server_entry_content)
167
+
168
+ # Create metadata.json
169
+ metadata = generate_metadata_json(package_name, description)
170
+ with open(package_dir / "hatch_metadata.json", "w") as f:
171
+ json.dump(metadata, f, indent=2)
172
+
173
+ # Create README.md
174
+ readme_content = generate_readme_md(package_name, description)
175
+ with open(package_dir / "README.md", "w") as f:
176
+ f.write(readme_content)
177
+
178
+ logger.info(f"Package template created successfully at {package_dir}")
179
+ return package_dir