jabara.formats.registry のソースコード
"""The format registry: it maps a file name or an archive's source kind to a checkpoint file format."""
from __future__ import annotations
from fnmatch import fnmatchcase
from pathlib import Path
from typing import TypeVar
from jabara.formats.base import CheckpointFormat
F = TypeVar("F", bound=type[CheckpointFormat])
_FORMATS: dict[str, CheckpointFormat] = {}
[ドキュメント]
def register_format(cls: F) -> F:
"""Class decorator that registers a format under its `kind`. Raises `ValueError` if the kind is already
registered or a file-name pattern is taken by a format registered earlier."""
if cls.kind in _FORMATS:
raise ValueError(f"format {cls.kind!r} is already registered")
for other in _FORMATS.values():
if taken := set(cls.names) & set(other.names):
raise ValueError(f"format {cls.kind!r}: {', '.join(sorted(taken))} already belongs to {other.kind!r}")
_FORMATS[cls.kind] = cls()
return cls
[ドキュメント]
def formats() -> list[CheckpointFormat]:
"""The registered formats, in the order they were registered."""
return list(_FORMATS.values())
[ドキュメント]
def format_of_file(path: Path) -> CheckpointFormat:
"""The format that takes a file of this name on its own. Raises `ValueError` naming the patterns otherwise."""
for fmt in _FORMATS.values():
if any(fnmatchcase(path.name, p) for p in fmt.names):
return fmt
patterns = ", ".join(p for fmt in _FORMATS.values() for p in fmt.names)
raise ValueError(f"{path}: not a checkpoint file Jabara recognises ({patterns})")
[ドキュメント]
def format_in_directory(path: Path) -> CheckpointFormat | None:
"""The format that `compress_dir` takes a file of this name with, or None to leave the file alone."""
for fmt in _FORMATS.values():
if any(fnmatchcase(path.name, p) for p in fmt.in_directory):
return fmt
return None
[ドキュメント]
def format_of_kind(kind: object) -> CheckpointFormat | None:
"""The format whose archives record this source kind, or None."""
return _FORMATS.get(kind) if isinstance(kind, str) else None
[ドキュメント]
def directory_patterns() -> list[str]:
"""Every pattern `compress_dir` takes, for messages."""
return [p for fmt in _FORMATS.values() for p in fmt.in_directory]