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() args = parser.parse_args()
name = args.path.name name = args.path.name
metadata = ComicFilenameParser(name, verbose=args.verbose).parse() cfnparser = ComicFilenameParser(name, verbose=args.verbose)
metadata = cfnparser.parse()
pprint(metadata) # noqa:T203 pprint(metadata) # noqa:T203

View File

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