Coverage for /Users/les/Projects/crackerjack/crackerjack/managers/publish_manager.py: 0%

284 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-03 15:39 -0700

1import subprocess 

2import typing as t 

3from contextlib import suppress 

4from pathlib import Path 

5 

6from rich.console import Console 

7 

8from crackerjack.services.filesystem import FileSystemService 

9from crackerjack.services.security import SecurityService 

10 

11 

12class PublishManagerImpl: 

13 def __init__(self, console: Console, pkg_path: Path, dry_run: bool = False) -> None: 

14 self.console = console 

15 self.pkg_path = pkg_path 

16 self.dry_run = dry_run 

17 self.filesystem = FileSystemService() 

18 self.security = SecurityService() 

19 

20 def _run_command( 

21 self, 

22 cmd: list[str], 

23 timeout: int = 300, 

24 ) -> subprocess.CompletedProcess[str]: 

25 secure_env = self.security.create_secure_command_env() 

26 

27 result = subprocess.run( 

28 cmd, 

29 check=False, 

30 cwd=self.pkg_path, 

31 capture_output=True, 

32 text=True, 

33 timeout=timeout, 

34 env=secure_env, 

35 ) 

36 

37 if result.stdout: 

38 result.stdout = self.security.mask_tokens(result.stdout) 

39 if result.stderr: 

40 result.stderr = self.security.mask_tokens(result.stderr) 

41 

42 return result 

43 

44 def _get_current_version(self) -> str | None: 

45 pyproject_path = self.pkg_path / "pyproject.toml" 

46 if not pyproject_path.exists(): 

47 return None 

48 try: 

49 from tomllib import loads 

50 

51 content = self.filesystem.read_file(pyproject_path) 

52 data = loads(content) 

53 return data.get("project", {}).get("version") 

54 except Exception as e: 

55 self.console.print(f"[yellow]⚠️[/ yellow] Error reading version: {e}") 

56 return None 

57 

58 def _update_version_in_file(self, new_version: str) -> bool: 

59 pyproject_path = self.pkg_path / "pyproject.toml" 

60 try: 

61 content = self.filesystem.read_file(pyproject_path) 

62 import re 

63 

64 pattern = r'^(version\s * =\s *["\'])([^"\']+)(["\'])$' 

65 replacement = f"\\g < 1 >{new_version}\\g < 3 >" 

66 new_content = re.sub(pattern, replacement, content, flags=re.MULTILINE) 

67 if content != new_content: 

68 if not self.dry_run: 

69 self.filesystem.write_file(pyproject_path, new_content) 

70 self.console.print( 

71 f"[green]✅[/ green] Updated version to {new_version}", 

72 ) 

73 return True 

74 self.console.print( 

75 "[yellow]⚠️[/ yellow] Version pattern not found in pyproject.toml", 

76 ) 

77 return False 

78 except Exception as e: 

79 self.console.print(f"[red]❌[/ red] Error updating version: {e}") 

80 return False 

81 

82 def _calculate_next_version(self, current: str, bump_type: str) -> str: 

83 try: 

84 parts = current.split(".") 

85 if len(parts) != 3: 

86 msg = f"Invalid version format: {current}" 

87 raise ValueError(msg) 

88 major, minor, patch = map(int, parts) 

89 if bump_type == "major": 

90 return f"{major + 1}.0.0" 

91 if bump_type == "minor": 

92 return f"{major}.{minor + 1}.0" 

93 if bump_type == "patch": 

94 return f"{major}.{minor}.{patch + 1}" 

95 msg = f"Invalid bump type: {bump_type}" 

96 raise ValueError(msg) 

97 except Exception as e: 

98 self.console.print(f"[red]❌[/ red] Error calculating version: {e}") 

99 raise 

100 

101 def bump_version(self, version_type: str) -> str: 

102 current_version = self._get_current_version() 

103 if not current_version: 

104 self.console.print("[red]❌[/ red] Could not determine current version") 

105 msg = "Cannot determine current version" 

106 raise ValueError(msg) 

107 self.console.print(f"[cyan]📦[/ cyan] Current version: {current_version}") 

108 

109 if version_type == "interactive": 

110 version_type = self._prompt_for_version_type() 

111 

112 try: 

113 new_version = self._calculate_next_version(current_version, version_type) 

114 if self.dry_run: 

115 self.console.print( 

116 f"[yellow]🔍[/ yellow] Would bump {version_type} version: {current_version} → {new_version}", 

117 ) 

118 elif self._update_version_in_file(new_version): 

119 self.console.print( 

120 f"[green]🚀[/ green] Bumped {version_type} version: {current_version} → {new_version}", 

121 ) 

122 else: 

123 msg = "Failed to update version in file" 

124 raise ValueError(msg) 

125 

126 return new_version 

127 except Exception as e: 

128 self.console.print(f"[red]❌[/ red] Version bump failed: {e}") 

129 raise 

130 

131 def _prompt_for_version_type(self) -> str: 

132 try: 

133 from rich.prompt import Prompt 

134 

135 return Prompt.ask( 

136 "[cyan]📦[/ cyan] Select version bump type", 

137 choices=["patch", "minor", "major"], 

138 default="patch", 

139 ) 

140 except ImportError: 

141 self.console.print( 

142 "[yellow]⚠️[/ yellow] Rich prompt not available, defaulting to patch" 

143 ) 

144 return "patch" 

145 

146 def validate_auth(self) -> bool: 

147 auth_methods = self._collect_auth_methods() 

148 return self._report_auth_status(auth_methods) 

149 

150 def _collect_auth_methods(self) -> list[str]: 

151 auth_methods: list[str] = [] 

152 

153 env_auth = self._check_env_token_auth() 

154 if env_auth: 

155 auth_methods.append(env_auth) 

156 

157 keyring_auth = self._check_keyring_auth() 

158 if keyring_auth: 

159 auth_methods.append(keyring_auth) 

160 

161 return auth_methods 

162 

163 def _check_env_token_auth(self) -> str | None: 

164 import os 

165 

166 token = os.getenv("UV_PUBLISH_TOKEN") 

167 if not token: 

168 return None 

169 

170 if self.security.validate_token_format(token, "pypi"): 

171 masked_token = self.security.mask_tokens(token) 

172 self.console.print(f"[dim]Token format: {masked_token}[/ dim]", style="dim") 

173 return "Environment variable (UV_PUBLISH_TOKEN)" 

174 self.console.print( 

175 "[yellow]⚠️[/ yellow] UV_PUBLISH_TOKEN format appears invalid", 

176 ) 

177 return None 

178 

179 def _check_keyring_auth(self) -> str | None: 

180 try: 

181 result = self._run_command( 

182 [ 

183 "keyring", 

184 "get", 

185 "https: / / upload.pypi.org / legacy /", 

186 "__token__", 

187 ], 

188 ) 

189 if result.returncode == 0 and result.stdout.strip(): 

190 keyring_token = result.stdout.strip() 

191 if self.security.validate_token_format(keyring_token, "pypi"): 

192 return "Keyring storage" 

193 self.console.print( 

194 "[yellow]⚠️[/ yellow] Keyring token format appears invalid", 

195 ) 

196 except (subprocess.SubprocessError, OSError, FileNotFoundError): 

197 pass 

198 return None 

199 

200 def _report_auth_status(self, auth_methods: list[str]) -> bool: 

201 if auth_methods: 

202 self.console.print("[green]✅[/ green] PyPI authentication available: ") 

203 for method in auth_methods: 

204 self.console.print(f"-{method}") 

205 return True 

206 self._display_auth_setup_instructions() 

207 return False 

208 

209 def _display_auth_setup_instructions(self) -> None: 

210 self.console.print("[red]❌[/ red] No valid PyPI authentication found") 

211 self.console.print("\n[yellow]💡[/ yellow] Setup options: ") 

212 self.console.print( 

213 " 1. Set environment variable: export UV_PUBLISH_TOKEN=< your - pypi-token >", 

214 ) 

215 self.console.print( 

216 " 2. Use keyring: keyring set https: / / upload.pypi.org / legacy / __token__", 

217 ) 

218 self.console.print( 

219 " 3. Ensure token starts with 'pypi -' and is properly formatted", 

220 ) 

221 

222 def build_package(self) -> bool: 

223 try: 

224 self.console.print("[yellow]🔨[/ yellow] Building package...") 

225 

226 if self.dry_run: 

227 return self._handle_dry_run_build() 

228 

229 return self._execute_build() 

230 except Exception as e: 

231 self.console.print(f"[red]❌[/ red] Build error: {e}") 

232 return False 

233 

234 def _handle_dry_run_build(self) -> bool: 

235 self.console.print("[yellow]🔍[/ yellow] Would build package") 

236 return True 

237 

238 def _clean_dist_directory(self) -> None: 

239 dist_dir = self.pkg_path / "dist" 

240 if not dist_dir.exists(): 

241 return 

242 

243 try: 

244 import shutil 

245 

246 shutil.rmtree(dist_dir) 

247 dist_dir.mkdir(exist_ok=True) 

248 self.console.print( 

249 "[cyan]🧹[/ cyan] Cleaned dist directory for fresh build" 

250 ) 

251 except Exception as e: 

252 self.console.print( 

253 f"[yellow]⚠️[/ yellow] Warning: Could not clean dist directory: {e}" 

254 ) 

255 

256 def _execute_build(self) -> bool: 

257 self._clean_dist_directory() 

258 

259 result = self._run_command(["uv", "build"]) 

260 

261 if result.returncode != 0: 

262 self.console.print(f"[red]❌[/ red] Build failed: {result.stderr}") 

263 return False 

264 

265 self.console.print("[green]✅[/ green] Package built successfully") 

266 self._display_build_artifacts() 

267 return True 

268 

269 def _display_build_artifacts(self) -> None: 

270 dist_dir = self.pkg_path / "dist" 

271 if not dist_dir.exists(): 

272 return 

273 

274 artifacts = list(dist_dir.glob("*")) 

275 self.console.print(f"[cyan]📦[/ cyan] Build artifacts ({len(artifacts)}): ") 

276 

277 for artifact in artifacts[-5:]: 

278 size_str = self._format_file_size(artifact.stat().st_size) 

279 self.console.print(f"-{artifact.name} ({size_str})") 

280 

281 def _format_file_size(self, size: int) -> str: 

282 if size < 1024 * 1024: 

283 return f"{size / 1024: .1f}KB" 

284 return f"{size / (1024 * 1024): .1f}MB" 

285 

286 def publish_package(self) -> bool: 

287 if not self._validate_prerequisites(): 

288 return False 

289 

290 try: 

291 self.console.print("[yellow]🚀[/ yellow] Publishing to PyPI...") 

292 return self._perform_publish_workflow() 

293 except Exception as e: 

294 self.console.print(f"[red]❌[/ red] Publish error: {e}") 

295 return False 

296 

297 def _validate_prerequisites(self) -> bool: 

298 return self.validate_auth() 

299 

300 def _perform_publish_workflow(self) -> bool: 

301 if self.dry_run: 

302 return self._handle_dry_run_publish() 

303 

304 if not self.build_package(): 

305 return False 

306 

307 return self._execute_publish() 

308 

309 def _handle_dry_run_publish(self) -> bool: 

310 self.console.print("[yellow]🔍[/ yellow] Would publish package to PyPI") 

311 return True 

312 

313 def _execute_publish(self) -> bool: 

314 result = self._run_command(["uv", "publish"]) 

315 

316 if result.returncode != 0: 

317 self._handle_publish_failure(result.stderr) 

318 return False 

319 

320 self._handle_publish_success() 

321 return True 

322 

323 def _handle_publish_failure(self, error_msg: str) -> None: 

324 self.console.print(f"[red]❌[/ red] Publish failed: {error_msg}") 

325 

326 def _handle_publish_success(self) -> None: 

327 self.console.print("[green]🎉[/ green] Package published successfully !") 

328 self._display_package_url() 

329 

330 def _display_package_url(self) -> None: 

331 current_version = self._get_current_version() 

332 package_name = self._get_package_name() 

333 

334 if package_name and current_version: 

335 url = f"https: / / pypi.org / project /{package_name}/{current_version}/" 

336 self.console.print(f"[cyan]🔗[/ cyan] Package URL: {url}") 

337 

338 def _get_package_name(self) -> str | None: 

339 pyproject_path = self.pkg_path / "pyproject.toml" 

340 

341 with suppress(Exception): 

342 from tomllib import loads 

343 

344 content = self.filesystem.read_file(pyproject_path) 

345 data = loads(content) 

346 return data.get("project", {}).get("name", "") 

347 

348 return None 

349 

350 def cleanup_old_releases(self, keep_releases: int = 10) -> bool: 

351 try: 

352 self.console.print( 

353 f"[yellow]🧹[/ yellow] Cleaning up old releases (keeping {keep_releases})...", 

354 ) 

355 if self.dry_run: 

356 self.console.print( 

357 "[yellow]🔍[/ yellow] Would clean up old PyPI releases", 

358 ) 

359 return True 

360 pyproject_path = self.pkg_path / "pyproject.toml" 

361 from tomllib import loads 

362 

363 content = self.filesystem.read_file(pyproject_path) 

364 data = loads(content) 

365 package_name = data.get("project", {}).get("name", "") 

366 if not package_name: 

367 self.console.print( 

368 "[yellow]⚠️[/ yellow] Could not determine package name", 

369 ) 

370 return False 

371 self.console.print( 

372 f"[cyan]📦[/ cyan] Would analyze releases for {package_name}", 

373 ) 

374 self.console.print( 

375 f"[cyan]🔧[/ cyan] Would keep {keep_releases} most recent releases", 

376 ) 

377 

378 return True 

379 except Exception as e: 

380 self.console.print(f"[red]❌[/ red] Cleanup error: {e}") 

381 return False 

382 

383 def create_git_tag(self, version: str) -> bool: 

384 try: 

385 if self.dry_run: 

386 self.console.print( 

387 f"[yellow]🔍[/ yellow] Would create git tag: v{version}", 

388 ) 

389 return True 

390 result = self._run_command(["git", "tag", f"v{version}"]) 

391 if result.returncode == 0: 

392 self.console.print(f"[green]🏷️[/ green] Created git tag: v{version}") 

393 push_result = self._run_command( 

394 ["git", "push", "origin", f"v{version}"], 

395 ) 

396 if push_result.returncode == 0: 

397 self.console.print("[green]📤[/ green] Pushed tag to remote") 

398 else: 

399 self.console.print( 

400 f"[yellow]⚠️[/ yellow] Tag created but push failed: {push_result.stderr}", 

401 ) 

402 

403 return True 

404 self.console.print( 

405 f"[red]❌[/ red] Failed to create tag: {result.stderr}", 

406 ) 

407 return False 

408 except Exception as e: 

409 self.console.print(f"[red]❌[/ red] Tag creation error: {e}") 

410 return False 

411 

412 def get_package_info(self) -> dict[str, t.Any]: 

413 pyproject_path = self.pkg_path / "pyproject.toml" 

414 if not pyproject_path.exists(): 

415 return {} 

416 try: 

417 from tomllib import loads 

418 

419 content = self.filesystem.read_file(pyproject_path) 

420 data = loads(content) 

421 project = data.get("project", {}) 

422 

423 return { 

424 "name": project.get("name", ""), 

425 "version": project.get("version", ""), 

426 "description": project.get("description", ""), 

427 "authors": project.get("authors", []), 

428 "dependencies": project.get("dependencies", []), 

429 "python_requires": project.get("requires-python", ""), 

430 } 

431 except Exception as e: 

432 self.console.print(f"[yellow]⚠️[/ yellow] Error reading package info: {e}") 

433 return {}