Skip to content

Commit

Permalink
internal: fix several linting issues
Browse files Browse the repository at this point in the history
  • Loading branch information
snejus committed Dec 10, 2024
1 parent 190fa0d commit 47ecad2
Show file tree
Hide file tree
Showing 19 changed files with 111 additions and 105 deletions.
22 changes: 11 additions & 11 deletions beetsplug/bandcamp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,11 @@ class BandcampRequestsHandler:
def from_bandcamp(cls, clue: str) -> bool:
"""Check if the clue is likely to be a bandcamp url.
We could check whether 'bandcamp' is found in the url, however, we would be ignoring
cases where the publisher uses their own domain (for example https://eaux.ro) which
in reality points to their Bandcamp page. Historically, we found that regardless
of the domain, the rest of the url stays the same, therefore '/album/' or '/track/'
is what we are looking for in a valid url here.
We could check whether 'bandcamp' is found in the url, however, we would be
ignoring cases where the publisher uses their own domain (for example
https://eaux.ro) which in reality points to their Bandcamp page. Historically,
we found that regardless of the domain, the rest of the url stays the same,
therefore '/album/' or '/track/' is what we are looking for in a valid url here.
"""
return bool(cls.BANDCAMP_URL_PAT.match(clue))

Expand Down Expand Up @@ -147,7 +147,7 @@ def __init__(self) -> None:
if self.config["art"]:
self.register_listener("pluginload", self.loaded)

def adjust_comments_field(self, lib: Library, album: Album) -> None:
def adjust_comments_field(self, lib: Library, album: Album) -> None: # noqa: ARG002
"""If the comments field is too long, store it as album flex attr.
Keep the first 4000 characters in the item and store the full comment as
Expand Down Expand Up @@ -186,7 +186,7 @@ def loaded(self) -> None:
def parse_label_url(cls, text: str) -> str | None:
return m[1] if (m := cls.LABEL_URL_IN_COMMENT.search(text)) else None

def _find_url_in_item(self, item: Item, name: str, _type: CandidateType) -> str:
def _find_url_in_item(self, item: Item, name: str, type_: CandidateType) -> str:
"""Try to extract release URL from the library item.
If the item has previously been imported, `mb_albumid` (or `mb_trackid`
Expand All @@ -204,14 +204,14 @@ def _find_url_in_item(self, item: Item, name: str, _type: CandidateType) -> str:
the number of previous releases that also did not have any valid
alphanums. Therefore, we cannot make a reliable guess here.
"""
if (url := getattr(item, f"mb_{_type}id", "")) and self.from_bandcamp(url):
if (url := getattr(item, f"mb_{type_}id", "")) and self.from_bandcamp(url):
self._info("Fetching the URL attached to the first item, {}", url)
return url

if (label_url := self.parse_label_url(item.comments)) and (
urlified_name := urlify(name)
):
url = f"{label_url}/{_type}/{urlified_name}"
url = f"{label_url}/{type_}/{urlified_name}"
self._info("Trying our guess {} before searching", url)
return url
return ""
Expand Down Expand Up @@ -338,10 +338,10 @@ def get_args() -> Any:
class UrlOrQueryAction(Action):
def __call__(
self,
parser: ArgumentParser,
parser: ArgumentParser, # noqa: ARG002
namespace: Namespace,
values: Any,
option_string: str | None = None,
option_string: str | None = None, # noqa: ARG002
) -> None:
if values:
if values.startswith("https://"):
Expand Down
6 changes: 5 additions & 1 deletion beetsplug/bandcamp/album_name.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

@dataclass
class AlbumName:
SPLIT_RELEASE_ARTIST_COUNT = 2

_series = r"(?i:\b(part|volume|pt|vol)\b\.?)"
SERIES = cached_patternprop(rf"{_series}[ ]?[A-Z\d.-]+\b")
SERIES_FMT = cached_patternprop(rf"^(.+){_series} *0*")
Expand Down Expand Up @@ -275,7 +277,9 @@ def get(

album = self.check_eplp(self.standardize_series(album))

if "split ep" in album.lower() or (not album and len(artists) == 2):
if "split ep" in album.lower() or (
not album and len(artists) == self.SPLIT_RELEASE_ARTIST_COUNT
):
album = " / ".join(artists)

return album or catalognum or original_album
2 changes: 1 addition & 1 deletion beetsplug/bandcamp/genres_lookup.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""List of MusicBrainz genres from https://beta.musicbrainz.org/genres"""
"""List of MusicBrainz genres from https://beta.musicbrainz.org/genres."""

GENRES = {
"2 tone",
Expand Down
40 changes: 20 additions & 20 deletions beetsplug/bandcamp/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,17 +66,17 @@ class MediaInfo(NamedTuple):
description: str

@classmethod
def from_format(cls, _format: JSONDict) -> MediaInfo:
release_format = _format.get("musicReleaseFormat")
def from_format(cls, format_: JSONDict) -> MediaInfo:
release_format = format_.get("musicReleaseFormat")

return cls(
_format["@id"],
format_["@id"],
FORMAT_TO_MEDIA[release_format or "DigitalFormat"],
"" if release_format == "DigitalFormat" else _format["name"],
"" if release_format == "DigitalFormat" else format_["name"],
(
""
if release_format == "DigitalFormat"
else _format.get("description") or ""
else format_.get("description") or ""
),
)

Expand Down Expand Up @@ -163,18 +163,18 @@ def split_artist_title(m: Match[str]) -> str:

# fmt: off
return [
(re.compile(rf"(([\[(])|(^| ))\*?({'|'.join(rm_strings)})(?(2)[])]|([- ]|$))", re.I), ""), # noqa
(re.compile(r" -([^\s-])"), r" - \1"), # hi -bye -> hi - bye # noqa
(re.compile(r"([^\s-])- "), r"\1 - "), # hi- bye -> hi - bye # noqa
(re.compile(r" +"), " "), # hi bye -> hi bye # noqa
(re.compile(r"(- )?\( *"), "("), # hi - ( bye) -> hi (bye) # noqa
(re.compile(r" \)+|(\)+$)"), ")"), # hi (bye )) -> hi (bye) # noqa
(re.compile(r"- Reworked"), "(Reworked)"), # bye - Reworked -> bye (Reworked) # noqa
(re.compile(rf"(\([^)]+mix)$", re.I), r"\1)"), # bye - (Some Mix -> bye - (Some Mix) # noqa
(re.compile(r'(^|- )[“"]([^”"]+)[”"]( \(|$)'), r"\1\2\3"), # "bye" -> bye; hi - "bye" -> hi - bye # noqa
(re.compile(r"\((the )?(remixes)\)", re.I), r"\2"), # Album (Remixes) -> Album Remixes # noqa
(re.compile(r"^(\[[^]-]+\]) - (([^-]|-\w)+ - ([^-]|-\w)+)$"), r"\2 \1"), # [Remixer] - hi - bye -> hi - bye [Remixer] # noqa
(re.compile(r"examine-.+CD\d+_([^_-]+)[_-](.*)"), split_artist_title), # See https://examine-archive.bandcamp.com/album/va-examine-archive-international-sampler-xmn01 # noqa
(re.compile(rf"(([\[(])|(^| ))\*?({'|'.join(rm_strings)})(?(2)[])]|([- ]|$))", re.I), ""), # noqa: E501
(re.compile(r" -([^\s-])"), r" - \1"), # hi -bye -> hi - bye # noqa: E501
(re.compile(r"([^\s-])- "), r"\1 - "), # hi- bye -> hi - bye # noqa: E501
(re.compile(r" +"), " "), # hi bye -> hi bye # noqa: E501
(re.compile(r"(- )?\( *"), "("), # hi - ( bye) -> hi (bye) # noqa: E501
(re.compile(r" \)+|(\)+$)"), ")"), # hi (bye )) -> hi (bye) # noqa: E501
(re.compile(r"- Reworked"), "(Reworked)"), # bye - Reworked -> bye (Reworked) # noqa: E501
(re.compile(r"(\([^)]+mix)$", re.I), r"\1)"), # bye - (Some Mix -> bye - (Some Mix) # noqa: E501
(re.compile(r'(^|- )[“"]([^”"]+)[”"]( \(|$)'), r"\1\2\3"), # "bye" -> bye; hi - "bye" -> hi - bye # noqa: E501
(re.compile(r"\((the )?(remixes)\)", re.I), r"\2"), # Album (Remixes) -> Album Remixes # noqa: E501
(re.compile(r"^(\[[^]-]+\]) - (([^-]|-\w)+ - ([^-]|-\w)+)$"), r"\2 \1"), # [Remixer] - hi - bye -> hi - bye [Remixer] # noqa: E501
(re.compile(r"examine-.+CD\d+_([^_-]+)[_-](.*)"), split_artist_title), # See https://examine-archive.bandcamp.com/album/va-examine-archive-international-sampler-xmn01 # noqa: E501
(re.compile(r'"([^"]+)" by (.+)$'), r"\2 - \1"), # "bye" by hi -> hi - bye # noqa: E501
]
# fmt: on
Expand Down Expand Up @@ -270,9 +270,9 @@ def valid_for_mode(kw: str) -> bool:
# expand badly delimited keywords
for kw in chain.from_iterable(map(cls.KEYWORD_SPLIT.split, keywords)):
# remove full stops and hashes and ensure the expected form of 'and'
_kw = kw.strip("#").replace("&", "and").replace(".", "")
if not is_label_name(_kw) and (is_included(_kw) or valid_for_mode(_kw)):
unique_genres[_kw] = None
kw_ = kw.strip("#").replace("&", "and").replace(".", "")
if not is_label_name(kw_) and (is_included(kw_) or valid_for_mode(kw_)):
unique_genres[kw_] = None

def within_another_genre(genre: str) -> bool:
"""Check if this genre is part of another genre.
Expand Down
2 changes: 1 addition & 1 deletion beetsplug/bandcamp/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

_rm_single_quote_dot = partial(re.compile(r"'|(?<=\d)\.(?=\d)").sub, "")
_non_ascii_to_dash = partial(re.compile(r"\W", flags=re.ASCII).sub, "-")
_squeeze_dashes = partial(re.compile("--+").sub, "-")
_squeeze_dashes = partial(re.compile(r"--+").sub, "-")


@atexit.register
Expand Down
8 changes: 5 additions & 3 deletions beetsplug/bandcamp/metaguru.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,8 @@ def image(self) -> str:
@cached_property
def release_date(self) -> date | None:
"""Parse the datestring that takes the format like below and return date object.
{"datePublished": "17 Jul 2020 00:00:00 GMT"}
{"datePublished": "17 Jul 2020 00:00:00 GMT"}.
If the field is not found, return None.
"""
Expand Down Expand Up @@ -349,7 +350,7 @@ def _search_albumtype(self, word: str) -> bool:
word_pat = re.compile(rf"(?<!-)\b{word}(\b|\.)", re.I)
in_catnum = re.compile(rf"{word}\d", re.I)
release_ref = re.compile(
rf"\b((this|with|present|deliver|new)[\w\s,'-]*?|the|track|full|first) {word}\b",
rf"\b((this|with|present|deliver|new)[\w\s,'-]*?|the|track|full|first) {word}\b", # noqa: E501
re.I,
)
album_name = self.album_name.lower()
Expand Down Expand Up @@ -385,7 +386,8 @@ def is_lp(self) -> bool:
def is_ep(self) -> bool:
"""Return whether the release is an EP."""
return self._search_albumtype(r"e\.?p") or (
" / " in self.album_name and len(self.tracks.artists) == 2
" / " in self.album_name
and len(self.tracks.artists) == AlbumName.SPLIT_RELEASE_ARTIST_COUNT
)

@cached_property
Expand Down
5 changes: 3 additions & 2 deletions beetsplug/bandcamp/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@


def _f(field: str) -> str:
"""Return pattern matching a string that does not start with '<' or space
until the end of the line.
"""Return pattern matching a string that does not start with '<' or space.
Match until the end of the line.
"""
return rf"(?P<{field}>[^\s<][^\n]+)"

Expand Down
8 changes: 4 additions & 4 deletions beetsplug/bandcamp/tracks.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,12 +251,12 @@ def for_media(
self, media: str, comments: str, include_digi: bool
) -> list[dict[str, Any]]:
if not include_digi and media != "Digital Media":
_tracks = [t for t in self.tracks if not t.digi_only]
tracks_ = [t for t in self.tracks if not t.digi_only]
else:
_tracks = self.tracks
tracks_ = self.tracks

medium_total = {"medium_total": len(_tracks)}
tracks = [t.info | medium_total for t in _tracks]
medium_total = {"medium_total": len(tracks_)}
tracks = [t.info | medium_total for t in tracks_]
if len(tracks) == 1 or media != "Vinyl":
return tracks

Expand Down
8 changes: 5 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,16 @@ def pytest_addoption(parser: Parser) -> None:


def pytest_terminal_summary(
terminalreporter: TerminalReporter, exitstatus: int, config: Config
terminalreporter: TerminalReporter,
exitstatus: int, # noqa: ARG001
config: Config,
) -> None:
base = config.getoption("base")
target = config.getoption("target")
terminalreporter.write(f"--- Compared {target} against {base} ---\n")


def pytest_assertrepr_compare(op: str, left, right):
def pytest_assertrepr_compare(op: str, left: Any, right: Any): # noqa: ARG001
"""Pretty print the difference between dict objects."""
actual, expected = left, right

Expand Down Expand Up @@ -143,7 +145,7 @@ def track_artist() -> str | None:


@pytest.fixture
def json_track(track_name, track_artist) -> JSONDict:
def json_track(track_name: str, track_artist: str | None) -> JSONDict:
return {
"item": {
"@id": "track_url",
Expand Down
2 changes: 1 addition & 1 deletion tests/test_album_name.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def test_clean_name(name, expected):


@pytest.mark.parametrize(
("original", "expected"),
"original, expected",
[
("Self-Medicating LP - WU87d", "Self-Medicating LP"),
("Stone Techno Series - Tetragonal EP", "Tetragonal EP"),
Expand Down
2 changes: 1 addition & 1 deletion tests/test_catalognum.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@


@pytest.mark.parametrize(
("album", "disctitle", "description", "label", "expected"),
"album, disctitle, description, label, expected",
[
("Tracker-229 [PRH-002]", "", "", "", "PRH-002"),
("[PRH-002] Tracker-229", "", "", "", "PRH-002"),
Expand Down
12 changes: 6 additions & 6 deletions tests/test_cmdline.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@
@pytest.mark.parametrize(
"cmdline, args",
[
(["https://bandcamp.com"], {"query": "", "release_url": "https://bandcamp.com", "search_type": "", "index": None, "page": 1}),
(["https://bandcamp.com"], {"query": "", "release_url": "https://bandcamp.com", "search_type": "", "index": None, "page": 1}), # noqa: E501
(["hello"], {"query": "hello", "search_type": "", "index": None, "page": 1}),
(["hello", "-a"], {"query": "hello", "search_type": "a", "index": None, "page": 1}),
(["hello", "-t"], {"query": "hello", "search_type": "t", "index": None, "page": 1}),
(["hello", "-l"], {"query": "hello", "search_type": "b", "index": None, "page": 1}),
(["hello", "-l", "-o", "1"], {"query": "hello", "search_type": "b", "index": 1, "page": 1}),
(["hello", "-l", "-p", "2"], {"query": "hello", "search_type": "b", "index": None, "page": 2}),
(["hello", "-a"], {"query": "hello", "search_type": "a", "index": None, "page": 1}), # noqa: E501
(["hello", "-t"], {"query": "hello", "search_type": "t", "index": None, "page": 1}), # noqa: E501
(["hello", "-l"], {"query": "hello", "search_type": "b", "index": None, "page": 1}), # noqa: E501
(["hello", "-l", "-o", "1"], {"query": "hello", "search_type": "b", "index": 1, "page": 1}), # noqa: E501
(["hello", "-l", "-p", "2"], {"query": "hello", "search_type": "b", "index": None, "page": 2}), # noqa: E501
],
) # fmt: skip
def test_cmdline_flags(cmdline, args):
Expand Down
6 changes: 3 additions & 3 deletions tests/test_genre.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def test_style(json_meta, beets_config):


@pytest.mark.parametrize(
("keywords", "expected"),
"keywords, expected",
[
([], None),
(["crazy music"], None),
Expand Down Expand Up @@ -87,7 +87,7 @@ def test_genre(keywords, mode, mode_result, beets_config):


@pytest.mark.parametrize(
("capitalize", "maximum", "expected"),
"capitalize, maximum, expected",
[
(True, 0, "Folk, Grime, House, Trance"),
(True, 3, "Folk, Grime, House"),
Expand All @@ -105,7 +105,7 @@ def test_genre_options(capitalize, maximum, expected, json_meta, beets_config):


@pytest.mark.parametrize(
("keywords", "label", "expected"),
"keywords, label, expected",
[
(["house", "classical"], "Classical", "classical, house"),
(["house", "hard tunenetwork"], "Hard Tune Network", "house"),
Expand Down
4 changes: 2 additions & 2 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@


@pytest.mark.parametrize(
("disctitle", "expected"),
"disctitle, expected",
[
("2 x Vinyl LP - MTY003", 2),
('3 x 12" Vinyl LP - MTY003', 3),
Expand Down Expand Up @@ -38,7 +38,7 @@ def test_bundles_get_excluded(bundle_format, digital_format):


@pytest.mark.parametrize(
("artists", "expected"),
"artists, expected",
[
(["Art", "Art"], ["Art"]),
(["Art", "Art1"], ["Art", "Art1"]),
Expand Down
28 changes: 14 additions & 14 deletions tests/test_lib.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Tests which process a bunch of Bandcamp JSONs and compare results with the specified
reference JSONs. Currently they are only executed locally and are based on
the maintainer's beets library.
"""Tests which read a bunch of Bandcamp JSONs and compare results with previous runs.
Currently they are only executed locally using around ~5000 release JSON files.
"""

from __future__ import annotations
Expand Down Expand Up @@ -103,7 +103,7 @@ def diff(self) -> str:

def expand(self) -> Iterator[FieldDiff]:
if self.field == "tracks":
for old_track, new_track in zip_longest(self.old, self.new, fillvalue=[]): # type: ignore[var-annotated] # noqa: E501
for old_track, new_track in zip_longest(self.old, self.new, fillvalue=[]): # type: ignore[var-annotated]
yield FieldDiff("album_track", old_track, new_track)
elif self.field == "album_track":
for field, (old, new) in zip_longest(
Expand Down Expand Up @@ -394,8 +394,8 @@ def old(base: JSONDict) -> JSONDict:

def write_results(data: JSONDict, name: str) -> Path:
contents = json.dumps(data, indent=2, sort_keys=True).encode()
_id = hashlib.md5(contents).hexdigest()
results_filepath = RESULTS_DIR / f"{name}-{_id}.json"
id_ = hashlib.md5(contents).hexdigest()
results_filepath = RESULTS_DIR / f"{name}-{id_}.json"
if not results_filepath.exists():
results_filepath.write_bytes(contents)

Expand All @@ -411,19 +411,19 @@ def new(
original_artist: str,
target_filepath: Path,
) -> JSONDict:
_new: AttrDict[Any]
new_: AttrDict[Any]
if "_track_" in target_filepath.name:
_new = guru.singleton
new_ = guru.singleton
else:
_new = next((a for a in guru.albums if a.media == "Vinyl"), guru.albums[0])
_new.album = " / ".join(dict.fromkeys(x["album"] for x in guru.albums))
new_ = next((a for a in guru.albums if a.media == "Vinyl"), guru.albums[0])
new_.album = " / ".join(dict.fromkeys(x["album"] for x in guru.albums))

_new.catalognum = " / ".join(
new_.catalognum = " / ".join(
sorted({x.catalognum for x in guru.albums if x.catalognum})
)
_new.original_name = original_name
_new.original_artist = original_artist
new = dict(_new)
new_.original_name = original_name
new_.original_artist = original_artist
new = dict(new_)

results_filepath = base_filepath.resolve()
if base and results_filepath.parent != RESULTS_DIR:
Expand Down
Loading

0 comments on commit 47ecad2

Please sign in to comment.