From 45806114543a863f5a151c6dd5a85f57380dcd34 Mon Sep 17 00:00:00 2001 From: AJ Slater Date: Tue, 20 Feb 2024 12:55:54 -0800 Subject: [PATCH] make serializer class --- comicfn2dict/cli.py | 3 ++- comicfn2dict/unparse.py | 55 +++++++++++++++++++++++------------------ 2 files changed, 33 insertions(+), 25 deletions(-) diff --git a/comicfn2dict/cli.py b/comicfn2dict/cli.py index d1e6880..e72508e 100755 --- a/comicfn2dict/cli.py +++ b/comicfn2dict/cli.py @@ -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 diff --git a/comicfn2dict/unparse.py b/comicfn2dict/unparse.py index 3d32bde..a04380c 100644 --- a/comicfn2dict/unparse.py +++ b/comicfn2dict/unparse.py @@ -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) - if val in _EMPTY_VALUES: - return "" - final_fmt = fmt(val) if isinstance(fmt, Callable) else fmt - token = final_fmt.format(val).strip() - return token +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(self) -> str: + """Get our preferred basename from a metadata dict.""" + tokens = [] + for tag, fmt in _FILENAME_FORMAT_TAGS: + if token := self._tokenize_tag(tag, fmt): + tokens.append(token) + fn = " ".join(tokens) -def serialize(md: Mapping, ext: bool = True) -> 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): - tokens.append(token) - fn = " ".join(tokens) - if remainders := md.get("remainders"): - remainder = " ".join(remainders) - # TODO oh this is the - delineated remainder :( - fn += f" - {remainder}" - if ext: - fn += "." + md.get("ext", "cbz") - return fn + 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 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()