|
| 1 | +import json |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import toml |
| 5 | +from pydantic import BaseModel, Field |
| 6 | +from pydantic_settings import BaseSettings, SettingsConfigDict |
| 7 | + |
| 8 | +from codegen.shared.configs.constants import CONFIG_PATH, ENV_PATH |
| 9 | + |
| 10 | + |
| 11 | +class TypescriptConfig(BaseModel): |
| 12 | + ts_dependency_manager: bool | None = None |
| 13 | + ts_language_engine: bool | None = None |
| 14 | + v8_ts_engine: bool | None = None |
| 15 | + |
| 16 | + |
| 17 | +class CodebaseFeatureFlags(BaseModel): |
| 18 | + debug: bool | None = None |
| 19 | + verify_graph: bool | None = None |
| 20 | + track_graph: bool | None = None |
| 21 | + method_usages: bool | None = None |
| 22 | + sync_enabled: bool | None = None |
| 23 | + full_range_index: bool | None = None |
| 24 | + ignore_process_errors: bool | None = None |
| 25 | + disable_graph: bool | None = None |
| 26 | + generics: bool | None = None |
| 27 | + import_resolution_overrides: dict[str, str] = Field(default_factory=lambda: {}) |
| 28 | + typescript: TypescriptConfig = Field(default_factory=TypescriptConfig) |
| 29 | + |
| 30 | + |
| 31 | +class RepositoryConfig(BaseModel): |
| 32 | + organization_name: str | None = None |
| 33 | + repo_name: str | None = None |
| 34 | + |
| 35 | + |
| 36 | +class SecretsConfig(BaseSettings): |
| 37 | + model_config = SettingsConfigDict( |
| 38 | + env_prefix="CODEGEN_SECRETS__", |
| 39 | + env_file=ENV_PATH, |
| 40 | + case_sensitive=False, |
| 41 | + ) |
| 42 | + github_token: str | None = None |
| 43 | + openai_api_key: str | None = None |
| 44 | + |
| 45 | + |
| 46 | +class FeatureFlagsConfig(BaseModel): |
| 47 | + codebase: CodebaseFeatureFlags = Field(default_factory=CodebaseFeatureFlags) |
| 48 | + |
| 49 | + |
| 50 | +class Config(BaseSettings): |
| 51 | + model_config = SettingsConfigDict( |
| 52 | + extra="ignore", |
| 53 | + exclude_defaults=False, |
| 54 | + ) |
| 55 | + secrets: SecretsConfig = Field(default_factory=SecretsConfig) |
| 56 | + repository: RepositoryConfig = Field(default_factory=RepositoryConfig) |
| 57 | + feature_flags: FeatureFlagsConfig = Field(default_factory=FeatureFlagsConfig) |
| 58 | + |
| 59 | + def save(self, config_path: Path | None = None) -> None: |
| 60 | + """Save configuration to the config file.""" |
| 61 | + path = config_path or CONFIG_PATH |
| 62 | + |
| 63 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 64 | + |
| 65 | + with open(path, "w") as f: |
| 66 | + toml.dump(self.model_dump(exclude_none=True), f) |
| 67 | + |
| 68 | + def get(self, full_key: str) -> str | None: |
| 69 | + """Get a configuration value as a JSON string.""" |
| 70 | + data = self.model_dump() |
| 71 | + keys = full_key.split(".") |
| 72 | + current = data |
| 73 | + for k in keys: |
| 74 | + if not isinstance(current, dict) or k not in current: |
| 75 | + return None |
| 76 | + current = current[k] |
| 77 | + return json.dumps(current) |
| 78 | + |
| 79 | + def set(self, full_key: str, value: str) -> None: |
| 80 | + """Update a configuration value and save it to the config file. |
| 81 | +
|
| 82 | + Args: |
| 83 | + full_key: Dot-separated path to the config value (e.g. "feature_flags.codebase.debug") |
| 84 | + value: string representing the new value |
| 85 | + """ |
| 86 | + data = self.model_dump() |
| 87 | + keys = full_key.split(".") |
| 88 | + current = data |
| 89 | + current_attr = self |
| 90 | + |
| 91 | + # Traverse through the key path and validate |
| 92 | + for k in keys[:-1]: |
| 93 | + if not isinstance(current, dict) or k not in current: |
| 94 | + msg = f"Invalid configuration path: {full_key}" |
| 95 | + raise KeyError(msg) |
| 96 | + current = current[k] |
| 97 | + current_attr = current_attr.__getattribute__(k) |
| 98 | + |
| 99 | + if not isinstance(current, dict) or keys[-1] not in current: |
| 100 | + msg = f"Invalid configuration path: {full_key}" |
| 101 | + raise KeyError(msg) |
| 102 | + |
| 103 | + # Validate the value type at key |
| 104 | + field_info = current_attr.model_fields[keys[-1]].annotation |
| 105 | + if isinstance(field_info, BaseModel): |
| 106 | + try: |
| 107 | + Config.model_validate(value, strict=False) |
| 108 | + except Exception as e: |
| 109 | + msg = f"Value does not match the expected type for key: {full_key}\n\nError:{e}" |
| 110 | + raise ValueError(msg) |
| 111 | + |
| 112 | + # Set the key value |
| 113 | + if isinstance(current[keys[-1]], dict): |
| 114 | + try: |
| 115 | + current[keys[-1]] = json.loads(value) |
| 116 | + except json.JSONDecodeError as e: |
| 117 | + msg = f"Value must be a valid JSON object for key: {full_key}\n\nError:{e}" |
| 118 | + raise ValueError(msg) |
| 119 | + else: |
| 120 | + current[keys[-1]] = value |
| 121 | + |
| 122 | + # Update the Config object with the new data |
| 123 | + self.__dict__.update(self.__class__.model_validate(data).__dict__) |
| 124 | + |
| 125 | + # Save to config file |
| 126 | + self.save() |
| 127 | + |
| 128 | + def __str__(self) -> str: |
| 129 | + """Return a pretty-printed string representation of the config.""" |
| 130 | + return json.dumps(self.model_dump(exclude_none=False), indent=2) |
0 commit comments