"""Citation styles: a stored reference written out as a bibliography entry. A reference is stored as fields — 题名, 刊名, 卷, 期, 页码, DOI, 责任者 — and a *paper* prints those fields in the order and with the punctuation one particular style asks for. The two are deliberately separate: the library holds the facts once, and a style decides how to write them down, so adding a style adds a module rather than a column. The module is one style per file, registered in :data:`STYLES`, and this package is the only thing the rest of the application imports: .. code-block:: python from app.citation_styles import DEFAULT_STYLE, format_reference text = format_reference(reference) # the default style gaps = missing_fields(reference) # 「缺 责任者、出版年」 ``DEFAULT_STYLE`` is what a document is assembled with, and the document reports it back as ``reference_style`` so a client can name the format it is showing without hard-coding the choice. """ from typing import Protocol from app.citation_styles import springer from app.models import Reference class Style(Protocol): """What a style module provides. Structural rather than a base class: a style is a module of two functions, and inheriting from something would only add an import to every one of them. """ def format_reference(self, reference: Reference) -> str: """Write one reference out as a bibliography entry.""" def missing_fields(self, reference: Reference) -> list[str]: """Which parts a complete entry is missing, in Chinese.""" #: The styles this build can print, by the token a document reports. STYLES: dict[str, Style] = {"springer": springer} #: The style a document is assembled with when nothing says otherwise. #: #: Springer's basic style: bracketed numerals in the text, a numbered list at the #: end, and entries of the shape ``Names: Title. (year). ``. DEFAULT_STYLE = "springer" def _style(name: str): """Look a style up, or say which ones exist.""" try: return STYLES[name] except KeyError: known = "、".join(sorted(STYLES)) raise ValueError(f"未知的参考文献格式:{name}(可用:{known})") from None def format_reference(reference: Reference | None, style: str = DEFAULT_STYLE) -> str: """Write one reference out as a bibliography entry. ``None`` — a citation whose row the library no longer has — yields the empty string rather than a fabricated entry: the caller decides how to say "unlinked", and this module never guesses. """ if reference is None: return "" return _style(style).format_reference(reference) def missing_fields(reference: Reference | None, style: str = DEFAULT_STYLE) -> list[str]: """Which parts a complete entry is missing, in the style's own terms.""" if reference is None: return [] return _style(style).missing_fields(reference) __all__ = [ "DEFAULT_STYLE", "STYLES", "format_reference", "missing_fields", ]