Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 61 additions & 14 deletions plistsync/cli/config.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,19 @@
"""YAML configuration management for the plistsync CLI.

Uses the ``eyconf`` library to load and validate the configuration file. The
plain dataclasses live in :mod:`plistsync.core.config` and
:mod:`plistsync.logger`; this module owns everything that is specific to the
CLI: file locations and the disk-backed loading.
"""
"""CLI-side configuration: file locations, loading and token persistence."""

from __future__ import annotations

import os
from dataclasses import dataclass, field, make_dataclass
from functools import cache
from pathlib import Path
from typing import Annotated, TypeVar
from typing import Annotated, Any, TypeVar, get_args, get_origin, get_type_hints

from eyconf import EYConf
from eyconf.decorators import allow_additional
from platformdirs import user_config_dir

from plistsync.core.config import ServiceConfig
from plistsync.core import Token
from plistsync.core.config import ConfigIO, DataIO, JsonFileIO, ServiceConfig
from plistsync.logger import LoggingConfig, log
from plistsync.services import ServiceLoader

Expand Down Expand Up @@ -175,8 +170,19 @@ def get_config_for(self, config_cls: type[C]) -> C:
If the config class is not registered.
"""
for service_name, config_classes in ServiceConfig.registry().items():
if config_cls in config_classes:
return self.get_service_config(service_name) # type: ignore[return-value]
if config_cls not in config_classes:
continue

service_config = self.get_service_config(service_name)
if isinstance(service_config, config_cls):
return service_config

# The service was registered only after this instance built its
# schema, so its config section is still raw "extra data". Rebuild
# the schema (now including the service) and reload.
self._schema = self._build_schema()
self.reload()
return self.get_service_config(service_name) # type: ignore[return-value]

raise ValueError(f"Service config {config_cls.__name__} is not registered.")

Expand All @@ -201,9 +207,8 @@ def get_service_config(self, service_name: str) -> ServiceConfig:
Raises
------
ValueError
If the service is not registered or has no config schema.
ConfigurationError
If the service is not enabled in the configuration.
If the service is not registered, has no config schema, or the
config instance cannot be resolved.
"""
# Already in the schema: fast return
if service_config := self.data.services.get(service_name):
Expand Down Expand Up @@ -243,7 +248,49 @@ def default_yaml(self):
return super().default_yaml()


def _dataio_token_type(annotation: Any) -> type[Token] | None:
"""Return ``D`` if ``annotation`` contains a ``DataIO[D]``, else ``None``."""
for candidate in (annotation, *get_args(annotation)):
if get_origin(candidate) is DataIO:
args = get_args(candidate)
if args and isinstance(args[0], type) and issubclass(args[0], Token):
return args[0]
return None


@dataclass
class UserDirConfigIO(ConfigIO):
"""Wrapper around EYCONF."""

config: Config = field(default_factory=Config)
directory: Path = field(default_factory=Config.get_dir)

def load(self, service_config_cls: type[C]) -> C:
# TODO: Re-evaluate. For now we only allow the special-case DataIO[Token]
# We should move the DataIO serialization logic into eyconf at some point
service_config = self.config.get_config_for(service_config_cls)
service_name = service_config_cls.service()

hints = get_type_hints(
service_config_cls, include_extras=True, localns={"DataIO": DataIO}
)
for name, annotation in hints.items():
token_type = _dataio_token_type(annotation)
if token_type is None:
continue
path = self.directory / f"{service_name}_{name}.json"
setattr(service_config, name, JsonFileIO[token_type](path)) # type: ignore[valid-type]

return service_config

def save(self, service_config: ServiceConfig) -> None:
# Currently only saves tokens via dataio
# See eyconf issue: #31
pass


__all__ = [
"BaseConfigSchema",
"Config",
"UserDirConfigIO",
]
8 changes: 4 additions & 4 deletions plistsync/cli/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,23 @@
@cached_property
def library(self) -> Library | None:
"""Instantiate the service's library, if it supports one."""
from plistsync.cli.config import Config

library_cls = self.service.library()
if library_cls is None:
return None

config_cls = self.service.config()
config = Config().get_config_for(config_cls) if config_cls is not None else None

Check failure on line 31 in plistsync/cli/context.py

View workflow job for this annotation

GitHub Actions / Check style with Ruff

Ruff (F821)

plistsync/cli/context.py:31:18: F821 Undefined name `Config`
return library_cls.from_config(config)

@cached_property
def config(self) -> ServiceConfig | None:
"""Resolve the service's config, if it supports one."""
from plistsync.cli.config import Config
from plistsync.cli.config import UserDirConfigIO

config_cls = self.service.config()
return Config().get_config_for(config_cls) if config_cls is not None else None
if config_cls is None:
return None
return UserDirConfigIO().load(config_cls)

@property
def name(self) -> str:
Expand Down
15 changes: 10 additions & 5 deletions plistsync/cli/service_commands/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from plistsync.cli.context import (
ServiceCommandContext, # noqa: TC001 (typer resolves it at runtime)
)
from plistsync.core.config import DataIO
from plistsync.errors import AuthenticationError, HowTheForkDidYouEndUpHereError
from plistsync.logger import log
from plistsync.utils.auth import safe_webbrowser_open
Expand Down Expand Up @@ -133,11 +134,15 @@ def auth(
return

token: Token = auth_provider(config).authenticate(CLIInteraction(mode=mode))
token.file_path = config.token_path
token.save()
typer.echo(
f"Authentication successful! Token saved to {str(token.file_path)!r}."
)

# The token field must be a DataIO so that the assignment below persists
# it (ServiceConfig.__setattr__ routes DataIO fields through __set__).
if not isinstance(vars(config).get("token"), DataIO):
raise HowTheForkDidYouEndUpHereError(
f"{type(config).__name__} has no DataIO for 'token'. Cannot persist it!"
)
setattr(config, "token", token)
typer.echo("Authentication successful! Token saved.")

auth.__doc__ = (
f"Authenticate with {auth_provider.service()} or check the"
Expand Down
6 changes: 4 additions & 2 deletions plistsync/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
and path rewriting.
"""

from .auth import AuthProvider, Interaction
from .auth import AuthProvider, Interaction, Token
from .collection import Collection, Library
from .config import ServiceConfig
from .config import ConfigIO, ServiceConfig
from .ids import PlaylistID, TrackID
from .matching import Matches
from .playlist import Playlist, ServicePlaylist
Expand All @@ -18,6 +18,7 @@
__all__ = [
"AuthProvider",
"Collection",
"ConfigIO",
"Interaction",
"Library",
"Matches",
Expand All @@ -26,6 +27,7 @@
"PlaylistID",
"ServiceConfig",
"ServicePlaylist",
"Token",
"Track",
"TrackID",
"TrackInfo",
Expand Down
Loading
Loading