Coverage for /Users/les/Projects/crackerjack/crackerjack/services/initialization.py: 0%

353 statements  

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

1import json 

2import subprocess 

3import typing as t 

4from pathlib import Path 

5 

6import tomli 

7import tomli_w 

8import yaml 

9from rich.console import Console 

10 

11from .filesystem import FileSystemService 

12from .git import GitService 

13from .input_validator import get_input_validator, validate_and_sanitize_path 

14 

15 

16class InitializationService: 

17 def __init__( 

18 self, 

19 console: Console, 

20 filesystem: FileSystemService, 

21 git_service: GitService, 

22 pkg_path: Path, 

23 ) -> None: 

24 self.console = console 

25 self.filesystem = filesystem 

26 self.git_service = git_service 

27 self.pkg_path = pkg_path 

28 

29 def initialize_project( 

30 self, 

31 target_path: Path | None = None, 

32 force: bool = False, 

33 ) -> dict[str, t.Any]: 

34 if target_path is None: 

35 target_path = Path.cwd() 

36 

37 # Validate target path for security 

38 try: 

39 target_path = validate_and_sanitize_path(target_path, allow_absolute=True) 

40 except Exception as e: 

41 return { 

42 "target_path": str(target_path), 

43 "files_copied": [], 

44 "files_skipped": [], 

45 "errors": [f"Invalid target path: {e}"], 

46 "success": False, 

47 } 

48 

49 results = self._create_results_dict(target_path) 

50 

51 try: 

52 config_files = self._get_config_files() 

53 project_name = target_path.name 

54 

55 # Validate project name 

56 validator = get_input_validator() 

57 name_result = validator.validate_project_name(project_name) 

58 if not name_result.valid: 

59 results["errors"].append( 

60 f"Invalid project name: {name_result.error_message}" 

61 ) 

62 results["success"] = False 

63 return results 

64 

65 # Use sanitized project name 

66 sanitized_project_name = name_result.sanitized_value 

67 

68 for file_name, merge_strategy in config_files.items(): 

69 self._process_config_file( 

70 file_name, 

71 merge_strategy, 

72 sanitized_project_name, 

73 target_path, 

74 force, 

75 results, 

76 ) 

77 

78 self._print_summary(results) 

79 

80 except Exception as e: 

81 self._handle_initialization_error(results, e) 

82 

83 return results 

84 

85 def _create_results_dict(self, target_path: Path) -> dict[str, t.Any]: 

86 return { 

87 "target_path": str(target_path), 

88 "files_copied": [], 

89 "files_skipped": [], 

90 "errors": [], 

91 "success": True, 

92 } 

93 

94 def _get_config_files(self) -> dict[str, str]: 

95 return { 

96 ".pre-commit-config.yaml": "smart_merge", 

97 "pyproject.toml": "smart_merge", 

98 "CLAUDE.md": "smart_append", 

99 "RULES.md": "replace_if_missing", 

100 "example.mcp.json": "special", 

101 } 

102 

103 def _process_config_file( 

104 self, 

105 file_name: str, 

106 merge_strategy: str, 

107 project_name: str, 

108 target_path: Path, 

109 force: bool, 

110 results: dict[str, t.Any], 

111 ) -> None: 

112 if file_name == "example.mcp.json": 

113 self._process_mcp_config(target_path, force, results) 

114 return 

115 

116 source_file = self.pkg_path.parent / file_name 

117 target_file = target_path / file_name 

118 

119 if not source_file.exists(): 

120 self._handle_missing_source_file(file_name, results) 

121 return 

122 

123 try: 

124 if merge_strategy == "smart_merge": 

125 self._smart_merge_config( 

126 source_file, 

127 target_file, 

128 file_name, 

129 project_name, 

130 force, 

131 results, 

132 ) 

133 elif merge_strategy == "smart_append": 

134 self._smart_append_config( 

135 source_file, 

136 target_file, 

137 file_name, 

138 project_name, 

139 force, 

140 results, 

141 ) 

142 elif merge_strategy == "replace_if_missing": 

143 if not target_file.exists() or force: 

144 content = self._read_and_process_content( 

145 source_file, 

146 True, 

147 project_name, 

148 ) 

149 self._write_file_and_track(target_file, content, file_name, results) 

150 else: 

151 self._skip_existing_file(file_name, results) 

152 else: 

153 if not self._should_copy_file(target_file, force, file_name, results): 

154 return 

155 content = self._read_and_process_content( 

156 source_file, 

157 True, 

158 project_name, 

159 ) 

160 self._write_file_and_track(target_file, content, file_name, results) 

161 

162 except Exception as e: 

163 self._handle_file_processing_error(file_name, e, results) 

164 

165 def _should_copy_file( 

166 self, 

167 target_file: Path, 

168 force: bool, 

169 file_name: str, 

170 results: dict[str, t.Any], 

171 ) -> bool: 

172 if target_file.exists() and not force: 

173 t.cast("list[str]", results["files_skipped"]).append(file_name) 

174 self.console.print( 

175 f"[yellow]⚠️[/ yellow] Skipped {file_name} (already exists)", 

176 ) 

177 return False 

178 return True 

179 

180 def _read_and_process_content( 

181 self, 

182 source_file: Path, 

183 should_replace: bool, 

184 project_name: str, 

185 ) -> str: 

186 content = source_file.read_text() 

187 

188 if should_replace and project_name != "crackerjack": 

189 content = content.replace("crackerjack", project_name) 

190 

191 return content 

192 

193 def _write_file_and_track( 

194 self, 

195 target_file: Path, 

196 content: str, 

197 file_name: str, 

198 results: dict[str, t.Any], 

199 ) -> None: 

200 target_file.write_text(content) 

201 t.cast("list[str]", results["files_copied"]).append(file_name) 

202 

203 try: 

204 self.git_service.add_files([str(target_file)]) 

205 except Exception as e: 

206 self.console.print( 

207 f"[yellow]⚠️[/ yellow] Could not git add {file_name}: {e}" 

208 ) 

209 

210 self.console.print(f"[green]✅[/ green] Copied {file_name}") 

211 

212 def _skip_existing_file(self, file_name: str, results: dict[str, t.Any]) -> None: 

213 t.cast("list[str]", results["files_skipped"]).append(file_name) 

214 self.console.print(f"[yellow]⚠️[/ yellow] Skipped {file_name} (already exists)") 

215 

216 def _handle_missing_source_file( 

217 self, 

218 file_name: str, 

219 results: dict[str, t.Any], 

220 ) -> None: 

221 error_msg = f"Source file not found: {file_name}" 

222 t.cast("list[str]", results["errors"]).append(error_msg) 

223 self.console.print(f"[yellow]⚠️[/ yellow] {error_msg}") 

224 

225 def _handle_file_processing_error( 

226 self, 

227 file_name: str, 

228 error: Exception, 

229 results: dict[str, t.Any], 

230 ) -> None: 

231 error_msg = f"Failed to copy {file_name}: {error}" 

232 t.cast("list[str]", results["errors"]).append(error_msg) 

233 results["success"] = False 

234 self.console.print(f"[red]❌[/ red] {error_msg}") 

235 

236 def _print_summary(self, results: dict[str, t.Any]) -> None: 

237 if results["success"]: 

238 self.console.print( 

239 f"[green]🎉 Project initialized successfully ! [/ green] " 

240 f"Copied {len(t.cast('list[str]', results['files_copied']))} files", 

241 ) 

242 else: 

243 self.console.print( 

244 "[red]❌ Project initialization completed with errors[/ red]", 

245 ) 

246 

247 def _handle_initialization_error( 

248 self, 

249 results: dict[str, t.Any], 

250 error: Exception, 

251 ) -> None: 

252 results["success"] = False 

253 t.cast("list[str]", results["errors"]).append(f"Initialization failed: {error}") 

254 self.console.print(f"[red]❌[/ red] Initialization failed: {error}") 

255 

256 def check_uv_installed(self) -> bool: 

257 try: 

258 result = subprocess.run( 

259 ["uv", "--version"], 

260 capture_output=True, 

261 text=True, 

262 timeout=10, 

263 check=False, 

264 ) 

265 return result.returncode == 0 

266 except (FileNotFoundError, subprocess.TimeoutExpired): 

267 return False 

268 

269 def _process_mcp_config( 

270 self, 

271 target_path: Path, 

272 force: bool, 

273 results: dict[str, t.Any], 

274 ) -> None: 

275 source_file = self.pkg_path / "example.mcp.json" 

276 

277 target_file = target_path / ".mcp.json" 

278 

279 if not source_file.exists(): 

280 self._handle_missing_source_file("example.mcp.json", results) 

281 return 

282 

283 try: 

284 with source_file.open() as f: 

285 source_config = json.load(f) 

286 

287 if not isinstance(source_config.get("mcpServers"), dict): 

288 self._handle_file_processing_error( 

289 "example.mcp.json", 

290 ValueError("Invalid example.mcp.json format: missing mcpServers"), 

291 results, 

292 ) 

293 return 

294 

295 crackerjack_servers = source_config["mcpServers"] 

296 

297 if not target_file.exists(): 

298 target_config = {"mcpServers": crackerjack_servers} 

299 self._write_mcp_config_and_track(target_file, target_config, results) 

300 self.console.print( 

301 "[green]✅[/ green] Created .mcp.json with crackerjack MCP servers", 

302 ) 

303 return 

304 

305 if target_file.exists() and not force: 

306 self._merge_mcp_config(target_file, crackerjack_servers, results) 

307 return 

308 

309 target_config = {"mcpServers": crackerjack_servers} 

310 self._write_mcp_config_and_track(target_file, target_config, results) 

311 self.console.print( 

312 "[green]✅[/ green] Updated .mcp.json with crackerjack MCP servers", 

313 ) 

314 

315 except Exception as e: 

316 self._handle_file_processing_error(".mcp.json", e, results) 

317 

318 def _merge_mcp_config( 

319 self, 

320 target_file: Path, 

321 crackerjack_servers: dict[str, t.Any], 

322 results: dict[str, t.Any], 

323 ) -> None: 

324 try: 

325 with target_file.open() as f: 

326 existing_config = json.load(f) 

327 

328 if not isinstance(existing_config.get("mcpServers"), dict): 

329 existing_config["mcpServers"] = {} 

330 

331 existing_servers = existing_config["mcpServers"] 

332 updated_servers = {} 

333 

334 for name, config in crackerjack_servers.items(): 

335 if name in existing_servers: 

336 self.console.print( 

337 f"[yellow]🔄[/ yellow] Updating existing MCP server: {name}", 

338 ) 

339 else: 

340 self.console.print( 

341 f"[green]➕[/ green] Adding new MCP server: {name}", 

342 ) 

343 updated_servers[name] = config 

344 

345 existing_servers.update(updated_servers) 

346 

347 self._write_mcp_config_and_track(target_file, existing_config, results) 

348 

349 t.cast("list[str]", results["files_copied"]).append(".mcp.json (merged)") 

350 

351 except Exception as e: 

352 self._handle_file_processing_error(".mcp.json (merge)", e, results) 

353 

354 def _write_mcp_config_and_track( 

355 self, 

356 target_file: Path, 

357 config: dict[str, t.Any], 

358 results: dict[str, t.Any], 

359 ) -> None: 

360 with target_file.open("w") as f: 

361 json.dump(config, f, indent=2) 

362 

363 t.cast("list[str]", results["files_copied"]).append(".mcp.json") 

364 

365 try: 

366 self.git_service.add_files([str(target_file)]) 

367 except Exception as e: 

368 self.console.print(f"[yellow]⚠️[/ yellow] Could not git add .mcp.json: {e}") 

369 

370 def validate_project_structure(self) -> bool: 

371 required_indicators = [ 

372 self.pkg_path / "pyproject.toml", 

373 self.pkg_path / "setup.py", 

374 ] 

375 

376 return any(path.exists() for path in required_indicators) 

377 

378 def _generate_project_claude_content(self, project_name: str) -> str: 

379 return """ 

380 

381 

382This project uses crackerjack for Python project management and quality assurance. 

383 

384 

385For optimal development experience with this crackerjack - enabled project, use these specialized agents: 

386 

387 

388- * *🏗️ crackerjack - architect * *: Expert in crackerjack's modular architecture and Python project management patterns. **Use PROACTIVELY **for all feature development, architectural decisions, and ensuring code follows crackerjack standards from the start. 

389 

390- * *🐍 python - pro * *: Modern Python development with type hints, async / await patterns, and clean architecture 

391 

392- * *🧪 pytest - hypothesis - specialist * *: Advanced testing patterns, property - based testing, and test optimization 

393 

394 

395- * *🧪 crackerjack - test - specialist * *: Advanced testing specialist for complex testing scenarios and coverage optimization 

396- * *🏗️ backend - architect * *: System design, API architecture, and service integration patterns 

397- * *🔒 security-auditor * *: Security analysis, vulnerability detection, and secure coding practices 

398 

399 

400```bash 

401 

402Task tool with subagent_type ="crackerjack - architect" for feature planning 

403 

404 

405Task tool with subagent_type ="python-pro" for code implementation 

406 

407 

408Task tool with subagent_type ="pytest - hypothesis-specialist" for test development 

409 

410 

411Task tool with subagent_type ="security-auditor" for security analysis 

412``` 

413 

414* *💡 Pro Tip * *: The crackerjack - architect agent automatically ensures code follows crackerjack patterns from the start, eliminating the need for retrofitting and quality fixes. 

415 

416 

417This project follows crackerjack's clean code philosophy: 

418 

419 

420- **EVERY LINE OF CODE IS A LIABILITY * *: The best code is no code 

421- **DRY (Don't Repeat Yourself)* *: If you write it twice, you're doing it wrong 

422- **YAGNI (You Ain't Gonna Need It)* *: Build only what's needed NOW 

423- **KISS (Keep It Simple, Stupid)* *: Complexity is the enemy of maintainability 

424 

425 

426- **Cognitive complexity ≤15 **per function (automatically enforced) 

427- **Coverage ratchet system * *: Never decrease coverage, always improve toward 100 % 

428- **Type annotations required * *: All functions must have return type hints 

429- **Security patterns * *: No hardcoded paths, proper temp file handling 

430- **Python 3.13 + modern patterns * *: Use `|` unions, pathlib over os.path 

431 

432 

433```bash 

434 

435python - m crackerjack 

436 

437 

438python - m crackerjack - t 

439 

440 

441python - m crackerjack - - ai - agent - t 

442 

443 

444python - m crackerjack - a patch 

445``` 

446 

447 

4481. **Plan with crackerjack - architect * *: Ensure proper architecture from the start 

4492. **Implement with python - pro * *: Follow modern Python patterns 

4503. **Test comprehensively * *: Use pytest - hypothesis - specialist for robust testing 

4514. **Run quality checks * *: `python - m crackerjack - t` before committing 

4525. **Security review * *: Use security - auditor for final validation 

453 

454 

455- **Use crackerjack - architect agent proactively **for all significant code changes 

456- **Never reduce test coverage **- the ratchet system only allows improvements 

457- **Follow crackerjack patterns **- the tools will enforce quality automatically 

458- **Leverage AI agent auto - fixing **- `python - m crackerjack - - ai - agent - t` for autonomous quality fixes 

459 

460- -- 

461* This project is enhanced by crackerjack's intelligent Python project management.*""" 

462 

463 def _smart_append_config( 

464 self, 

465 source_file: Path, 

466 target_file: Path, 

467 file_name: str, 

468 project_name: str, 

469 force: bool, 

470 results: dict[str, t.Any], 

471 ) -> None: 

472 if file_name == "CLAUDE.md" and project_name != "crackerjack": 

473 source_content = self._generate_project_claude_content(project_name) 

474 else: 

475 source_content = self._read_and_process_content( 

476 source_file, True, project_name 

477 ) 

478 

479 if not target_file.exists(): 

480 self._write_file_and_track(target_file, source_content, file_name, results) 

481 return 

482 

483 existing_content = target_file.read_text() 

484 

485 crackerjack_start_marker = "< !- - CRACKERJACK INTEGRATION START-->" 

486 crackerjack_end_marker = "< !- - CRACKERJACK INTEGRATION END-->" 

487 

488 if crackerjack_start_marker in existing_content: 

489 if force: 

490 start_idx = existing_content.find(crackerjack_start_marker) 

491 end_idx = existing_content.find(crackerjack_end_marker) 

492 if end_idx != -1: 

493 end_idx += len(crackerjack_end_marker) 

494 

495 existing_content = ( 

496 existing_content[:start_idx] + existing_content[end_idx:] 

497 ).strip() 

498 else: 

499 self._skip_existing_file(f"{file_name} (crackerjack section)", results) 

500 return 

501 

502 merged_content = ( 

503 existing_content.strip() + "\n\n" + crackerjack_start_marker + "\n" 

504 ) 

505 merged_content += source_content.strip() + "\n" 

506 merged_content += crackerjack_end_marker + "\n" 

507 

508 target_file.write_text(merged_content) 

509 t.cast("list[str]", results["files_copied"]).append(f"{file_name} (appended)") 

510 

511 try: 

512 self.git_service.add_files([str(target_file)]) 

513 except Exception as e: 

514 self.console.print( 

515 f"[yellow]⚠️[/ yellow] Could not git add {file_name}: {e}" 

516 ) 

517 

518 self.console.print(f"[green]✅[/ green] Appended to {file_name}") 

519 

520 def _smart_merge_config( 

521 self, 

522 source_file: Path, 

523 target_file: Path, 

524 file_name: str, 

525 project_name: str, 

526 force: bool, 

527 results: dict[str, t.Any], 

528 ) -> None: 

529 if file_name == "pyproject.toml": 

530 self._smart_merge_pyproject( 

531 source_file, 

532 target_file, 

533 project_name, 

534 force, 

535 results, 

536 ) 

537 elif file_name == ".pre-commit-config.yaml": 

538 self._smart_merge_pre_commit_config( 

539 source_file, 

540 target_file, 

541 project_name, 

542 force, 

543 results, 

544 ) 

545 

546 elif not target_file.exists() or force: 

547 content = self._read_and_process_content( 

548 source_file, 

549 True, 

550 project_name, 

551 ) 

552 self._write_file_and_track(target_file, content, file_name, results) 

553 else: 

554 self._skip_existing_file(file_name, results) 

555 

556 def _smart_merge_pyproject( 

557 self, 

558 source_file: Path, 

559 target_file: Path, 

560 project_name: str, 

561 force: bool, 

562 results: dict[str, t.Any], 

563 ) -> None: 

564 with source_file.open("rb") as f: 

565 source_config = tomli.load(f) 

566 

567 if not target_file.exists(): 

568 content = self._read_and_process_content(source_file, True, project_name) 

569 self._write_file_and_track(target_file, content, "pyproject.toml", results) 

570 return 

571 

572 with target_file.open("rb") as f: 

573 target_config = tomli.load(f) 

574 

575 self._ensure_crackerjack_dev_dependency(target_config, source_config) 

576 

577 self._merge_tool_configurations(target_config, source_config, project_name) 

578 

579 self._remove_fixed_coverage_requirements(target_config) 

580 

581 import io 

582 

583 buffer = io.BytesIO() 

584 tomli_w.dump(target_config, buffer) 

585 content = buffer.getvalue().decode("utf-8") 

586 

587 from crackerjack.services.filesystem import FileSystemService 

588 

589 content = FileSystemService.clean_trailing_whitespace_and_newlines(content) 

590 

591 with target_file.open("w", encoding="utf-8") as f: 

592 f.write(content) 

593 

594 t.cast("list[str]", results["files_copied"]).append("pyproject.toml (merged)") 

595 

596 try: 

597 self.git_service.add_files([str(target_file)]) 

598 except Exception as e: 

599 self.console.print( 

600 f"[yellow]⚠️[/ yellow] Could not git add pyproject.toml: {e}", 

601 ) 

602 

603 self.console.print("[green]✅[/ green] Smart merged pyproject.toml") 

604 

605 def _ensure_crackerjack_dev_dependency( 

606 self, 

607 target_config: dict[str, t.Any], 

608 source_config: dict[str, t.Any], 

609 ) -> None: 

610 if "dependency-groups" not in target_config: 

611 target_config["dependency-groups"] = {} 

612 

613 if "dev" not in target_config["dependency-groups"]: 

614 target_config["dependency-groups"]["dev"] = [] 

615 

616 dev_deps = target_config["dependency-groups"]["dev"] 

617 if "crackerjack" not in str(dev_deps): 

618 dev_deps.append("crackerjack") 

619 

620 def _merge_tool_configurations( 

621 self, 

622 target_config: dict[str, t.Any], 

623 source_config: dict[str, t.Any], 

624 project_name: str, 

625 ) -> None: 

626 source_tools = source_config.get("tool", {}) 

627 

628 if "tool" not in target_config: 

629 target_config["tool"] = {} 

630 

631 target_tools = target_config["tool"] 

632 

633 tools_to_merge = [ 

634 "ruff", 

635 "pyright", 

636 "bandit", 

637 "vulture", 

638 "refurb", 

639 "complexipy", 

640 "codespell", 

641 "creosote", 

642 ] 

643 

644 for tool_name in tools_to_merge: 

645 if tool_name in source_tools: 

646 if tool_name not in target_tools: 

647 target_tools[tool_name] = self._replace_project_name_in_tool_config( 

648 source_tools[tool_name], project_name 

649 ) 

650 self.console.print( 

651 f"[green]➕[/ green] Added [tool.{tool_name}] configuration", 

652 ) 

653 else: 

654 self._merge_tool_settings( 

655 target_tools[tool_name], 

656 source_tools[tool_name], 

657 tool_name, 

658 project_name, 

659 ) 

660 

661 self._merge_pytest_markers(target_tools, source_tools) 

662 

663 def _merge_tool_settings( 

664 self, 

665 target_tool: dict[str, t.Any], 

666 source_tool: dict[str, t.Any], 

667 tool_name: str, 

668 project_name: str, 

669 ) -> None: 

670 updated_keys = [] 

671 

672 for key, value in source_tool.items(): 

673 if key not in target_tool: 

674 target_tool[key] = self._replace_project_name_in_config_value( 

675 value, project_name 

676 ) 

677 updated_keys.append(key) 

678 

679 if updated_keys: 

680 self.console.print( 

681 f"[yellow]🔄[/ yellow] Updated [tool.{tool_name}] with: {', '.join(updated_keys)}", 

682 ) 

683 

684 def _merge_pytest_markers( 

685 self, 

686 target_tools: dict[str, t.Any], 

687 source_tools: dict[str, t.Any], 

688 ) -> None: 

689 if "pytest" not in source_tools or "pytest" not in target_tools: 

690 return 

691 

692 source_pytest = source_tools["pytest"] 

693 target_pytest = target_tools["pytest"] 

694 

695 if "ini_options" not in source_pytest or "ini_options" not in target_pytest: 

696 return 

697 

698 source_markers = source_pytest["ini_options"].get("markers", []) 

699 target_markers = target_pytest["ini_options"].get("markers", []) 

700 

701 existing_marker_names = {marker.split(": ")[0] for marker in target_markers} 

702 new_markers = [ 

703 marker 

704 for marker in source_markers 

705 if marker.split(": ")[0] not in existing_marker_names 

706 ] 

707 

708 if new_markers: 

709 target_markers.extend(new_markers) 

710 self.console.print( 

711 f"[green]➕[/ green] Added pytest markers: {len(new_markers)}", 

712 ) 

713 

714 def _remove_fixed_coverage_requirements( 

715 self, 

716 target_config: dict[str, t.Any], 

717 ) -> None: 

718 import re 

719 

720 target_coverage = ( 

721 target_config.get("tool", {}).get("pytest", {}).get("ini_options", {}) 

722 ) 

723 

724 addopts = target_coverage.get("addopts", "") 

725 if isinstance(addopts, str): 

726 original_addopts = addopts 

727 

728 addopts = re.sub( 

729 r"- - cov - fail-under =\d +\.?\d *\s *", "", addopts 

730 ).strip() 

731 

732 addopts = " ".join(addopts.split()) 

733 

734 if original_addopts != addopts: 

735 target_coverage["addopts"] = addopts 

736 self.console.print( 

737 "[green]🔄[/ green] Removed fixed coverage requirement (using ratchet system)", 

738 ) 

739 

740 coverage_report = ( 

741 target_config.get("tool", {}).get("coverage", {}).get("report", {}) 

742 ) 

743 if "fail_under" in coverage_report: 

744 original_fail_under = coverage_report["fail_under"] 

745 coverage_report["fail_under"] = 0 

746 self.console.print( 

747 f"[green]🔄[/ green] Reset coverage.report.fail_under from {original_fail_under} to 0 (ratchet system)", 

748 ) 

749 

750 def _extract_coverage_requirement(self, addopts: str | list[str]) -> int | None: 

751 import re 

752 

753 addopts_str = " ".join(addopts) if isinstance(addopts, list) else addopts 

754 match = re.search(r"- - cov - fail-under =(\d +)", addopts_str) 

755 return int(match.group(1)) if match else None 

756 

757 def _smart_merge_pre_commit_config( 

758 self, 

759 source_file: Path, 

760 target_file: Path, 

761 project_name: str, 

762 force: bool, 

763 results: dict[str, t.Any], 

764 ) -> None: 

765 with source_file.open() as f: 

766 source_config = yaml.safe_load(f) 

767 

768 if not target_file.exists(): 

769 content = self._read_and_process_content( 

770 source_file, 

771 True, 

772 project_name, 

773 ) 

774 

775 from crackerjack.services.filesystem import FileSystemService 

776 

777 content = FileSystemService.clean_trailing_whitespace_and_newlines(content) 

778 self._write_file_and_track( 

779 target_file, 

780 content, 

781 ".pre-commit-config.yaml", 

782 results, 

783 ) 

784 return 

785 

786 with target_file.open() as f: 

787 target_config = yaml.safe_load(f) 

788 

789 if not isinstance(source_config, dict): 

790 source_config = {} 

791 if not isinstance(target_config, dict): 

792 target_config = {} 

793 

794 source_repos = source_config.get("repos", []) 

795 target_repos = target_config.get("repos", []) 

796 

797 existing_repo_urls = {repo.get("repo", "") for repo in target_repos} 

798 

799 new_repos = [ 

800 repo 

801 for repo in source_repos 

802 if repo.get("repo", "") not in existing_repo_urls 

803 ] 

804 

805 if new_repos: 

806 target_repos.extend(new_repos) 

807 target_config["repos"] = target_repos 

808 

809 yaml_content = yaml.dump( 

810 target_config, 

811 default_flow_style=False, 

812 sort_keys=False, 

813 width=float("inf"), 

814 ) 

815 content = ( 

816 yaml_content.decode() 

817 if isinstance(yaml_content, bytes) 

818 else yaml_content 

819 ) 

820 

821 if content is None: 

822 content = "" 

823 

824 from crackerjack.services.filesystem import FileSystemService 

825 

826 content = FileSystemService.clean_trailing_whitespace_and_newlines(content) 

827 

828 with target_file.open("w") as f: 

829 f.write(content) 

830 

831 t.cast("list[str]", results["files_copied"]).append( 

832 ".pre-commit-config.yaml (merged)", 

833 ) 

834 

835 try: 

836 self.git_service.add_files([str(target_file)]) 

837 except Exception as e: 

838 self.console.print( 

839 f"[yellow]⚠️[/ yellow] Could not git add .pre-commit-config.yaml: {e}", 

840 ) 

841 

842 self.console.print( 

843 f"[green]✅[/ green] Merged .pre-commit-config.yaml ({len(new_repos)} new repos)", 

844 ) 

845 else: 

846 self._skip_existing_file(".pre-commit-config.yaml (no new repos)", results) 

847 

848 def _replace_project_name_in_tool_config( 

849 self, tool_config: dict[str, t.Any], project_name: str 

850 ) -> dict[str, t.Any]: 

851 if project_name == "crackerjack": 

852 return tool_config 

853 

854 import copy 

855 

856 result = copy.deepcopy(tool_config) 

857 

858 return self._replace_project_name_in_config_value(result, project_name) 

859 

860 def _replace_project_name_in_config_value( 

861 self, value: t.Any, project_name: str 

862 ) -> t.Any: 

863 if project_name == "crackerjack": 

864 return value 

865 

866 if isinstance(value, str): 

867 return value.replace("crackerjack", project_name) 

868 elif isinstance(value, list): 

869 return [ 

870 self._replace_project_name_in_config_value(item, project_name) 

871 for item in value 

872 ] 

873 elif isinstance(value, dict): 

874 return { 

875 key: self._replace_project_name_in_config_value(val, project_name) 

876 for key, val in value.items() 

877 } 

878 return value