refactor: Make formatters functions

Formatters have been classes so far which contained some data (the
tamplate to use for formatting and the annotations and documents to
format) and the actual formatting logic (an execute function).

However, we can inject the annotations to be formatted and the templates
so far are static only, so they can be simple variables (we can think
about how to inject them at another point should it come up, no
bikeshedding now).

This way, we can simply pass around one function per formatter, which
should make the code much lighter, easier to add to and especially less
stateful which means less areas of broken interactions to worry about.
This commit is contained in:
Marty Oehme 2023-09-21 21:54:24 +02:00
parent 929e70d7ac
commit 7ee8d4911e
Signed by: Marty
GPG key ID: EDBF2ED917B2EF6A
3 changed files with 70 additions and 110 deletions

View file

@ -6,33 +6,35 @@ import papis.api
import papis.git
import papis.config
import Levenshtein
from papis_extract.annotation import AnnotatedDocument
from papis_extract.formatter import Formatter
logger = papis.logging.get_logger(__name__)
def to_stdout(formatter: Formatter) -> None:
def to_stdout(formatter: Formatter, annotated_docs: list[AnnotatedDocument]) -> None:
"""Pretty print annotations to stdout.
Gives a nice human-readable representations of
the annotations in somewhat of a list form.
Not intended for machine-readability.
"""
output:str = formatter.execute()
print(output.rstrip('\n'))
output: str = formatter(annotated_docs)
print(output.rstrip("\n"))
def to_notes(formatter: Formatter, edit: bool, git: bool) -> None:
def to_notes(
formatter: Formatter, annotated_docs: list[AnnotatedDocument], edit: bool, git: bool
) -> None:
"""Write annotations into document notes.
Permanently writes the given annotations into notes
belonging to papis documents. Creates new notes for
documents missing a note field or appends to existing.
"""
annotated_docs = formatter.annotated_docs
for entry in annotated_docs:
formatted_annotations = formatter.execute(entry).split("\n")
formatted_annotations = formatter([entry]).split("\n")
if formatted_annotations:
_add_annots_to_note(entry.document, formatted_annotations)
@ -67,7 +69,8 @@ def _add_annots_to_note(
# add newline if theres no empty space at file end
if len(existing) > 0 and existing[-1].strip() != "":
f.write("\n")
f.write("\n".join(new_annotations))
print(new_annotations)
f.write("\n\n".join(new_annotations))
f.write("\n")
logger.info(
f"Wrote {len(new_annotations)} "