Project: pygitweb

103ed4a """
PyGitWeb settings file: ~/.pygitweb/settings.json (or PYGITWEB_SETTINGS_CONFIG).
9c38e6a On first run, writes field defaults (ignoring environment) and creates the file.
When the file exists, loads from JSON then applies explicit environment/.env overrides
for the current process only (with a warning). Environment overrides are never written
back. Changes via the settings UI or setattr persist to the file.
103ed4a """
from __future__ import annotations
import json
import sys
4614448 from collections.abc import Iterator
103ed4a from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
73c9c30 from pygitweb.config import Settings
103ed4a
DEFAULT_SETTINGS_CONFIG_PATH = Path.home() / ".pygitweb" / "settings.json"
_persist_enabled = False
_batch_update = False
_active_path: Path | None = None
_setattr_patched = False
9c38e6a _persisted_settings: Settings | None = None
_NoEnvSettings: type[Settings] | None = None
103ed4a
def settings_config_path() -> Path:
73c9c30 explicit = __import__("os").environ.get("PYGITWEB_SETTINGS_CONFIG", "").strip()
if explicit:
return Path(explicit).expanduser()
return DEFAULT_SETTINGS_CONFIG_PATH
103ed4a
def write_settings_file(settings: Settings, path: Path | None = None) -> None:
73c9c30 target = path or _active_path or settings_config_path()
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(
json.dumps(settings.model_dump(mode="json"), indent=2) + "\n",
encoding="utf-8",
)
103ed4a
def _warn_env_overrides(path: Path, fields: list[str]) -> None:
73c9c30 names = ", ".join(fields)
print(
9c38e6a f"WARNING: PyGitWeb: environment overrides settings file {path}\n"
f" Overridden field(s): {names}\n"
f" These apply for this process only and are not saved to the file.\n",
73c9c30 file=sys.stderr,
)
103ed4a
9c38e6a def _no_env_settings_cls() -> type[Settings]:
"""Settings subclass that ignores environment and .env (file/defaults only)."""
global _NoEnvSettings
if _NoEnvSettings is None:
from pydantic_settings import BaseSettings, PydanticBaseSettingsSource
from pygitweb.config import Settings
class NoEnvSettings(Settings):
@classmethod
def settings_customise_sources(
cls,
settings_cls: type[BaseSettings],
init_settings: PydanticBaseSettingsSource,
env_settings: PydanticBaseSettingsSource,
dotenv_settings: PydanticBaseSettingsSource,
file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]:
return (init_settings,)
_NoEnvSettings = NoEnvSettings
return _NoEnvSettings
def _load_settings_without_env(data: dict[str, object] | None = None) -> Settings:
cls = _no_env_settings_cls()
if data is None:
return cls()
return cls.model_validate(data)
103ed4a def _apply_env_overrides(base: Settings) -> list[str]:
73c9c30 from pygitweb.config import Settings
103ed4a
73c9c30 env_settings = Settings()
overrides: list[str] = []
for name in env_settings.model_fields_set:
env_val = getattr(env_settings, name)
if getattr(base, name) == env_val:
continue
setattr(base, name, env_val)
overrides.append(name)
return overrides
103ed4a
def _patch_settings_setattr() -> None:
73c9c30 global _setattr_patched
if _setattr_patched:
return
103ed4a
73c9c30 from pygitweb.config import Settings
103ed4a
73c9c30 original = Settings.__setattr__
103ed4a
73c9c30 def _setattr(self: object, name: str, value: object) -> None:
original(self, name, value)
if name not in Settings.model_fields or not isinstance(self, Settings):
return
9c38e6a if _persisted_settings is not None and self is not _persisted_settings:
original(_persisted_settings, name, value)
if not _persist_enabled or _batch_update:
return
write_settings_file(_persisted_settings if _persisted_settings is not None else self)
103ed4a
73c9c30 Settings.__setattr__ = _setattr # type: ignore[method-assign]
_setattr_patched = True
103ed4a
def init_settings() -> Settings:
73c9c30 from pygitweb.config import Settings, _finalize_auth_settings
103ed4a
9c38e6a global _persist_enabled, _active_path, _persisted_settings
103ed4a
73c9c30 _persist_enabled = False
9c38e6a _persisted_settings = None
73c9c30 path = settings_config_path()
_active_path = path
103ed4a
73c9c30 if path.is_file():
9c38e6a raw = json.loads(path.read_text(encoding="utf-8"))
persisted = _load_settings_without_env(raw if isinstance(raw, dict) else None)
73c9c30 else:
9c38e6a persisted = _load_settings_without_env(None)
# Full dump has every field, so model_validate_json does not fill gaps from the environment.
runtime = Settings.model_validate_json(persisted.model_dump_json())
overrides = _apply_env_overrides(runtime)
if overrides:
_warn_env_overrides(path, overrides)
_finalize_auth_settings(runtime)
if persisted.AUTH is None:
# Default persisted AUTH to on; do not copy a one-shot PYGITWEB_AUTH=0 into the file.
persisted.AUTH = True
103ed4a
9c38e6a _persisted_settings = persisted
write_settings_file(persisted, path)
73c9c30 _patch_settings_setattr()
_persist_enabled = True
9c38e6a return runtime
103ed4a
@contextmanager
4614448 def settings_batch_update(settings: Settings) -> Iterator[None]:
73c9c30 """Apply multiple setting changes and persist once."""
global _batch_update
_batch_update = True
try:
yield
finally:
_batch_update = False
if _persist_enabled:
9c38e6a write_settings_file(_persisted_settings if _persisted_settings is not None else settings)