make serializer class
This commit is contained in:
parent
36729799a0
commit
4580611454
@ -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
|
||||
|
||||
|
||||
|
@ -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()
|
||||
|
Loading…
Reference in New Issue
Block a user