make serializer class

This commit is contained in:
AJ Slater 2024-02-20 12:55:54 -08:00
parent 36729799a0
commit 4580611454
2 changed files with 33 additions and 25 deletions

View File

@ -20,7 +20,8 @@ def main():
)
args = parser.parse_args()
name = args.path.name
metadata = ComicFilenameParser(name, verbose=args.verbose).parse()
cfnparser = ComicFilenameParser(name, verbose=args.verbose)
metadata = cfnparser.parse()
pprint(metadata) # noqa:T203

View File

@ -26,35 +26,42 @@ _FILENAME_FORMAT_TAGS: tuple[tuple[str, str | Callable], ...] = (
("scan_info", _PAREN_FMT),
)
_EMPTY_VALUES: tuple[None, str] = (None, "")
_DEFAULT_EXT = "cbz"
def _tokenize_tag(md: Mapping, tag: str, fmt: str | Callable) -> str:
val = md.get(tag)
class ComicFilenameSerializer:
def _tokenize_tag(self, tag: str, fmt: str | Callable) -> str:
val = self.metadata.get(tag)
if val in _EMPTY_VALUES:
return ""
final_fmt = fmt(val) if isinstance(fmt, Callable) else fmt
token = final_fmt.format(val).strip()
return token
def serialize(md: Mapping, ext: bool = True) -> str:
def serialize(self) -> str:
"""Get our preferred basename from a metadata dict."""
if not md:
return ""
tokens = []
for tag, fmt in _FILENAME_FORMAT_TAGS:
if token := _tokenize_tag(md, tag, fmt):
if token := self._tokenize_tag(tag, fmt):
tokens.append(token)
fn = " ".join(tokens)
if remainders := md.get("remainders"):
if remainders := self.metadata.get("remainders"):
# TODO make token and add before join?
remainder = " ".join(remainders)
# TODO oh this is the - delineated remainder :(
fn += f" - {remainder}"
if ext:
fn += "." + md.get("ext", "cbz")
if self._ext:
fn += "." + self.metadata.get("ext", _DEFAULT_EXT)
return fn
def __init__(self, metadata: Mapping, ext: bool = True):
self.metadata: Mapping = metadata
self._ext: bool = ext
def dict2comicfn(md: Mapping, ext: bool = True) -> str:
"""Simple API."""
return serialize(md, ext=ext)
return ComicFilenameSerializer(md, ext=ext).serialize()