Project: pygitweb

"""
PyGitWeb settings file: ~/.pygitweb/settings.json (or PYGITWEB_SETTINGS_CONFIG).
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.
"""
from __future__ import annotations
import json
import sys
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from pygitweb.config import Settings
DEFAULT_SETTINGS_CONFIG_PATH = Path.home() / ".pygitweb" / "settings.json"
_persist_enabled = False
_batch_update = False
_active_path: Path | None = None
_setattr_patched = False
_persisted_settings: Settings | None = None
_NoEnvSettings: type[Settings] | None = None
def settings_config_path() -> Path:
explicit = __import__("os").environ.get("PYGITWEB_SETTINGS_CONFIG", "").strip()
if explicit:
return Path(explicit).expanduser()
return DEFAULT_SETTINGS_CONFIG_PATH
def write_settings_file(settings: Settings, path: Path | None = None) -> None:
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",
)
def _warn_env_overrides(path: Path, fields: list[str]) -> None:
names = ", ".join(fields)
print(
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",
file=sys.stderr,
)
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)
def _apply_env_overrides(base: Settings) -> list[str]:
from pygitweb.config import Settings
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
def _patch_settings_setattr() -> None:
global _setattr_patched
if _setattr_patched:
return
from pygitweb.config import Settings
original = Settings.__setattr__
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
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)
Settings.__setattr__ = _setattr # type: ignore[method-assign]
_setattr_patched = True
def init_settings() -> Settings:
from pygitweb.config import Settings, _finalize_auth_settings
global _persist_enabled, _active_path, _persisted_settings
_persist_enabled = False
_persisted_settings = None
path = settings_config_path()
_active_path = path
if path.is_file():
raw = json.loads(path.read_text(encoding="utf-8"))
persisted = _load_settings_without_env(raw if isinstance(raw, dict) else None)
else:
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
_persisted_settings = persisted
write_settings_file(persisted, path)
_patch_settings_setattr()
_persist_enabled = True
return runtime
@contextmanager
def settings_batch_update(settings: Settings) -> Iterator[None]:
"""Apply multiple setting changes and persist once."""
global _batch_update
_batch_update = True
try:
yield
finally:
_batch_update = False
if _persist_enabled:
write_settings_file(_persisted_settings if _persisted_settings is not None else settings)