Extract parse_song_txt into own method
This commit is contained in:
parent
6d0efae1cf
commit
66b1c22879
@ -5,6 +5,8 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Self
|
||||
|
||||
from karaokatalog.parse_song_txt import parse_song_txt
|
||||
|
||||
type Title = str
|
||||
type Artist = str
|
||||
|
||||
@ -43,8 +45,7 @@ class Song:
|
||||
|
||||
@classmethod
|
||||
def from_song_txt(cls, song_txt: Path) -> Self | None:
|
||||
with song_txt.open(encoding="utf-8", errors="ignore") as f:
|
||||
tags = dict(_parse_tag_line(line) for line in f if line.startswith("#"))
|
||||
tags = parse_song_txt(song_txt)
|
||||
|
||||
title = tags.get("TITLE")
|
||||
artist = tags.get("ARTIST")
|
||||
@ -65,26 +66,9 @@ class Song:
|
||||
song_txt=song_txt,
|
||||
)
|
||||
|
||||
|
||||
def _parse_tag_line(tag_line: str) -> tuple[str, str | None]:
|
||||
"""
|
||||
Parse a tag line of the format:
|
||||
|
||||
#KEY:Value
|
||||
|
||||
or
|
||||
|
||||
#KEY:
|
||||
|
||||
Returns a tuple of (key, value), where the value might be None.
|
||||
"""
|
||||
|
||||
key_and_potentially_value = tuple(
|
||||
tag_line.strip().removeprefix("#").split(":", maxsplit=1)
|
||||
)
|
||||
|
||||
return (
|
||||
key_and_potentially_value
|
||||
if len(key_and_potentially_value) == 2
|
||||
else (key_and_potentially_value[0], None)
|
||||
)
|
||||
def as_dict(self) -> dict[str, str]:
|
||||
return {
|
||||
"title": self.title,
|
||||
"artist": self.artist,
|
||||
# TODO More fields
|
||||
}
|
||||
|
33
karaokatalog/parse_song_txt.py
Normal file
33
karaokatalog/parse_song_txt.py
Normal file
@ -0,0 +1,33 @@
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _parse_tag_line(tag_line: str) -> tuple[str, str | None]:
|
||||
"""
|
||||
Parse a tag line of the format:
|
||||
|
||||
#KEY:Value
|
||||
|
||||
or
|
||||
|
||||
#KEY:
|
||||
|
||||
Returns a tuple of (key, value), where the value might be None.
|
||||
"""
|
||||
|
||||
key_and_potentially_value = tuple(
|
||||
tag_line.strip().removeprefix("#").split(":", maxsplit=1)
|
||||
)
|
||||
|
||||
return (
|
||||
key_and_potentially_value
|
||||
if len(key_and_potentially_value) == 2
|
||||
else (key_and_potentially_value[0], None)
|
||||
)
|
||||
|
||||
|
||||
def parse_song_txt(song_txt: Path) -> dict[str, Any]:
|
||||
with song_txt.open(encoding="utf-8", errors="ignore") as f:
|
||||
tags = dict(_parse_tag_line(line) for line in f if line.startswith("#"))
|
||||
|
||||
return tags
|
Loading…
x
Reference in New Issue
Block a user