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)
| 473 | |
| 474 | |
| 475 | def save_config(config: Dict[str, str], preserve_db_credentials: bool = True): |
| 476 | """ |
| 477 | Save configuration to file. |
| 478 | If preserve_db_credentials is True, existing database credentials will be preserved. |
| 479 | If preserve_db_credentials is False, credentials from config dict will be written. |
| 480 | """ |
| 481 | ensure_config_dir() |
| 482 | |
| 483 | # Determine which credentials to write |
| 484 | credentials_to_write = {} |
| 485 | |
| 486 | if preserve_db_credentials and CONFIG_FILE.exists(): |
| 487 | # Load existing credentials from file to preserve them |
| 488 | try: |
| 489 | with open(CONFIG_FILE, "r", encoding="utf-8") as f: |
| 490 | for line in f: |
| 491 | line = line.strip() |
| 492 | if line and not line.startswith("#") and "=" in line: |
| 493 | key, value = line.split("=", 1) |
| 494 | key = key.strip() |
| 495 | if key in DATABASE_CREDENTIAL_KEYS: |
| 496 | credentials_to_write[key] = value.strip() |
| 497 | except Exception: |
| 498 | pass |
| 499 | # Merge credentials from the config dict (handles both new and updated values) |
| 500 | for key in DATABASE_CREDENTIAL_KEYS: |
| 501 | if key in config: |
| 502 | credentials_to_write[key] = config[key] |
| 503 | else: |
| 504 | # Use credentials from the config dict being passed in |
| 505 | for key in DATABASE_CREDENTIAL_KEYS: |
| 506 | if key in config: |
| 507 | credentials_to_write[key] = config[key] |
| 508 | |
| 509 | try: |
| 510 | lines = [ |
| 511 | "# CodeGraphContext Configuration", |
| 512 | f"# Location: {CONFIG_FILE}", |
| 513 | "", |
| 514 | ] |
| 515 | if credentials_to_write: |
| 516 | lines.append("# ===== Database Credentials =====") |
| 517 | for key in sorted(DATABASE_CREDENTIAL_KEYS): |
| 518 | if key in credentials_to_write: |
| 519 | lines.append(f"{key}={credentials_to_write[key]}") |
| 520 | lines.append("") |
| 521 | lines.append("# ===== Configuration Settings =====") |
| 522 | for key, value in sorted(config.items()): |
| 523 | if key in DATABASE_CREDENTIAL_KEYS: |
| 524 | continue |
| 525 | description = CONFIG_DESCRIPTIONS.get(key, "") |
| 526 | if description: |
| 527 | lines.append(f"# {description}") |
| 528 | lines.append(f"{key}={value}") |
| 529 | lines.append("") |
| 530 | _atomic_write_text(CONFIG_FILE, "\n".join(lines), secure=True) |
| 531 | console.print(f"[green]✅ Configuration saved to {CONFIG_FILE}[/green]") |
| 532 | except Exception as e: |
no test coverage detected