Save configuration to file. If preserve_db_credentials is True, existing database credentials will be preserved. If preserve_db_credentials is False, credentials from config dict will be written.
(config: Dict[str, str], preserve_db_credentials: bool = True)
| 440 | |
| 441 | |
| 442 | def save_config(config: Dict[str, str], preserve_db_credentials: bool = True): |
| 443 | """ |
| 444 | Save configuration to file. |
| 445 | If preserve_db_credentials is True, existing database credentials will be preserved. |
| 446 | If preserve_db_credentials is False, credentials from config dict will be written. |
| 447 | """ |
| 448 | ensure_config_dir() |
| 449 | |
| 450 | # Determine which credentials to write |
| 451 | credentials_to_write = {} |
| 452 | |
| 453 | if preserve_db_credentials and CONFIG_FILE.exists(): |
| 454 | # Load existing credentials from file to preserve them |
| 455 | try: |
| 456 | with open(CONFIG_FILE, "r", encoding="utf-8") as f: |
| 457 | for line in f: |
| 458 | line = line.strip() |
| 459 | if line and not line.startswith("#") and "=" in line: |
| 460 | key, value = line.split("=", 1) |
| 461 | key = key.strip() |
| 462 | if key in DATABASE_CREDENTIAL_KEYS: |
| 463 | credentials_to_write[key] = value.strip() |
| 464 | except Exception: |
| 465 | pass |
| 466 | # Merge credentials from the config dict (handles both new and updated values) |
| 467 | for key in DATABASE_CREDENTIAL_KEYS: |
| 468 | if key in config: |
| 469 | credentials_to_write[key] = config[key] |
| 470 | else: |
| 471 | # Use credentials from the config dict being passed in |
| 472 | for key in DATABASE_CREDENTIAL_KEYS: |
| 473 | if key in config: |
| 474 | credentials_to_write[key] = config[key] |
| 475 | |
| 476 | try: |
| 477 | lines = [ |
| 478 | "# CodeGraphContext Configuration", |
| 479 | f"# Location: {CONFIG_FILE}", |
| 480 | "", |
| 481 | ] |
| 482 | if credentials_to_write: |
| 483 | lines.append("# ===== Database Credentials =====") |
| 484 | for key in sorted(DATABASE_CREDENTIAL_KEYS): |
| 485 | if key in credentials_to_write: |
| 486 | lines.append(f"{key}={credentials_to_write[key]}") |
| 487 | lines.append("") |
| 488 | lines.append("# ===== Configuration Settings =====") |
| 489 | for key, value in sorted(config.items()): |
| 490 | if key in DATABASE_CREDENTIAL_KEYS: |
| 491 | continue |
| 492 | description = CONFIG_DESCRIPTIONS.get(key, "") |
| 493 | if description: |
| 494 | lines.append(f"# {description}") |
| 495 | lines.append(f"{key}={value}") |
| 496 | lines.append("") |
| 497 | _atomic_write_text(CONFIG_FILE, "\n".join(lines), secure=True) |
| 498 | console.print(f"[green]✅ Configuration saved to {CONFIG_FILE}[/green]") |
| 499 | except Exception as e: |
no test coverage detected