Fix formatting

This commit is contained in:
Šarūnas Nejus 2025-05-07 03:06:44 +01:00
parent 36d42c5b6f
commit c490ac5810
No known key found for this signature in database
GPG key ID: DD28F6704DBE3435
31 changed files with 67 additions and 71 deletions

View file

@ -121,15 +121,15 @@ class Assertions:
def assertIsFile(self, path): def assertIsFile(self, path):
self.assertExists(path) self.assertExists(path)
assert os.path.isfile( assert os.path.isfile(syspath(path)), (
syspath(path) "path exists, but is not a regular file: {!r}".format(path)
), "path exists, but is not a regular file: {!r}".format(path) )
def assertIsDir(self, path): def assertIsDir(self, path):
self.assertExists(path) self.assertExists(path)
assert os.path.isdir( assert os.path.isdir(syspath(path)), (
syspath(path) "path exists, but is not a directory: {!r}".format(path)
), "path exists, but is not a directory: {!r}".format(path) )
def assert_equal_path(self, a, b): def assert_equal_path(self, a, b):
"""Check that two paths are equal.""" """Check that two paths are equal."""

View file

@ -1768,7 +1768,7 @@ def _open_library(config):
) )
) )
log.debug( log.debug(
"library database: {0}\n" "library directory: {1}", "library database: {0}\nlibrary directory: {1}",
util.displayable_path(lib.path), util.displayable_path(lib.path),
util.displayable_path(lib.directory), util.displayable_path(lib.directory),
) )

View file

@ -1599,9 +1599,7 @@ def list_func(lib, opts, args):
list_cmd = ui.Subcommand("list", help="query the library", aliases=("ls",)) list_cmd = ui.Subcommand("list", help="query the library", aliases=("ls",))
list_cmd.parser.usage += ( list_cmd.parser.usage += "\nExample: %prog -f '$album: $title' artist:beatles"
"\n" "Example: %prog -f '$album: $title' artist:beatles"
)
list_cmd.parser.add_all_common_options() list_cmd.parser.add_all_common_options()
list_cmd.func = list_func list_cmd.func = list_func
default_commands.append(list_cmd) default_commands.append(list_cmd)

View file

@ -559,7 +559,7 @@ def link(path: bytes, dest: bytes, replace: bool = False):
except NotImplementedError: except NotImplementedError:
# raised on python >= 3.2 and Windows versions before Vista # raised on python >= 3.2 and Windows versions before Vista
raise FilesystemError( raise FilesystemError(
"OS does not support symbolic links." "link", "OS does not support symbolic links.link",
(path, dest), (path, dest),
traceback.format_exc(), traceback.format_exc(),
) )
@ -581,14 +581,14 @@ def hardlink(path: bytes, dest: bytes, replace: bool = False):
os.link(syspath(path), syspath(dest)) os.link(syspath(path), syspath(dest))
except NotImplementedError: except NotImplementedError:
raise FilesystemError( raise FilesystemError(
"OS does not support hard links." "link", "OS does not support hard links.link",
(path, dest), (path, dest),
traceback.format_exc(), traceback.format_exc(),
) )
except OSError as exc: except OSError as exc:
if exc.errno == errno.EXDEV: if exc.errno == errno.EXDEV:
raise FilesystemError( raise FilesystemError(
"Cannot hard link across devices." "link", "Cannot hard link across devices.link",
(path, dest), (path, dest),
traceback.format_exc(), traceback.format_exc(),
) )

View file

@ -157,7 +157,7 @@ only files which would be processed",
# If file has no MBID, skip it. # If file has no MBID, skip it.
if not mbid: if not mbid:
self._log.info( self._log.info(
"Not analysing {}, missing " "musicbrainz track id.", item "Not analysing {}, missing musicbrainz track id.", item
) )
return None return None
@ -220,6 +220,6 @@ only files which would be processed",
) )
else: else:
self._log.debug( self._log.debug(
"Successfully submitted AcousticBrainz analysis " "for {}.", "Successfully submitted AcousticBrainz analysis for {}.",
item, item,
) )

View file

@ -286,7 +286,7 @@ class AcousticPlugin(plugins.BeetsPlugin):
yield v, subdata[k] yield v, subdata[k]
else: else:
self._log.warning( self._log.warning(
"Acousticbrainz did not provide info " "about {}", k "Acousticbrainz did not provide info about {}", k
) )
self._log.debug( self._log.debug(
"Data {} could not be mapped to scheme {} " "Data {} could not be mapped to scheme {} "

View file

@ -75,7 +75,7 @@ class BareascPlugin(BeetsPlugin):
"bareasc", help="unidecode version of beet list command" "bareasc", help="unidecode version of beet list command"
) )
cmd.parser.usage += ( cmd.parser.usage += (
"\n" "Example: %prog -f '$album: $title' artist:beatles" "\nExample: %prog -f '$album: $title' artist:beatles"
) )
cmd.parser.add_all_common_options() cmd.parser.add_all_common_options()
cmd.func = self.unidecode_list cmd.func = self.unidecode_list

View file

@ -57,7 +57,7 @@ class BPMPlugin(BeetsPlugin):
def commands(self): def commands(self):
cmd = ui.Subcommand( cmd = ui.Subcommand(
"bpm", "bpm",
help="determine bpm of a song by pressing " "a key to the rhythm", help="determine bpm of a song by pressing a key to the rhythm",
) )
cmd.func = self.command cmd.func = self.command
return [cmd] return [cmd]
@ -79,7 +79,7 @@ class BPMPlugin(BeetsPlugin):
return return
self._log.info( self._log.info(
"Press Enter {0} times to the rhythm or Ctrl-D " "to exit", "Press Enter {0} times to the rhythm or Ctrl-D to exit",
self.config["max_strokes"].get(int), self.config["max_strokes"].get(int),
) )
new_bpm = bpm(self.config["max_strokes"].get(int)) new_bpm = bpm(self.config["max_strokes"].get(int))

View file

@ -236,7 +236,7 @@ class DuplicatesPlugin(BeetsPlugin):
checksum = getattr(item, key, False) checksum = getattr(item, key, False)
if not checksum: if not checksum:
self._log.debug( self._log.debug(
"key {0} on item {1} not cached:" "computing checksum", "key {0} on item {1} not cached:computing checksum",
key, key,
displayable_path(item.path), displayable_path(item.path),
) )
@ -255,7 +255,7 @@ class DuplicatesPlugin(BeetsPlugin):
) )
else: else:
self._log.debug( self._log.debug(
"key {0} on item {1} cached:" "not computing checksum", "key {0} on item {1} cached:not computing checksum",
key, key,
displayable_path(item.path), displayable_path(item.path),
) )
@ -275,13 +275,13 @@ class DuplicatesPlugin(BeetsPlugin):
values = [v for v in values if v not in (None, "")] values = [v for v in values if v not in (None, "")]
if strict and len(values) < len(keys): if strict and len(values) < len(keys):
self._log.debug( self._log.debug(
"some keys {0} on item {1} are null or empty:" " skipping", "some keys {0} on item {1} are null or empty: skipping",
keys, keys,
displayable_path(obj.path), displayable_path(obj.path),
) )
elif not strict and not len(values): elif not strict and not len(values):
self._log.debug( self._log.debug(
"all keys {0} on item {1} are null or empty:" " skipping", "all keys {0} on item {1} are null or empty: skipping",
keys, keys,
displayable_path(obj.path), displayable_path(obj.path),
) )

View file

@ -66,7 +66,7 @@ class EmbedCoverArtPlugin(BeetsPlugin):
if self.config["maxwidth"].get(int) and not ArtResizer.shared.local: if self.config["maxwidth"].get(int) and not ArtResizer.shared.local:
self.config["maxwidth"] = 0 self.config["maxwidth"] = 0
self._log.warning( self._log.warning(
"ImageMagick or PIL not found; " "'maxwidth' option ignored" "ImageMagick or PIL not found; 'maxwidth' option ignored"
) )
if ( if (
self.config["compare_threshold"].get(int) self.config["compare_threshold"].get(int)

View file

@ -686,7 +686,7 @@ class FanartTV(RemoteArtSource):
# can this actually occur? # can this actually occur?
else: else:
self._log.debug( self._log.debug(
"fanart.tv: unexpected mb_releasegroupid in " "response!" "fanart.tv: unexpected mb_releasegroupid in response!"
) )
matches.sort(key=lambda x: int(x["likes"]), reverse=True) matches.sort(key=lambda x: int(x["likes"]), reverse=True)

View file

@ -58,8 +58,7 @@ class ImportAddedPlugin(BeetsPlugin):
or session.config["reflink"] or session.config["reflink"]
): ):
self._log.debug( self._log.debug(
"In place import detected, recording mtimes from " "In place import detected, recording mtimes from source paths"
"source paths"
) )
items = ( items = (
[task.item] [task.item]
@ -95,7 +94,7 @@ class ImportAddedPlugin(BeetsPlugin):
mtime = os.stat(util.syspath(source)).st_mtime mtime = os.stat(util.syspath(source)).st_mtime
self.item_mtime[destination] = mtime self.item_mtime[destination] = mtime
self._log.debug( self._log.debug(
"Recorded mtime {0} for item '{1}' imported from " "'{2}'", "Recorded mtime {0} for item '{1}' imported from '{2}'",
mtime, mtime,
util.displayable_path(destination), util.displayable_path(destination),
util.displayable_path(source), util.displayable_path(source),
@ -130,7 +129,7 @@ class ImportAddedPlugin(BeetsPlugin):
def update_item_times(self, lib, item): def update_item_times(self, lib, item):
if self.reimported_item(item): if self.reimported_item(item):
self._log.debug( self._log.debug(
"Item '{0}' is reimported, skipping import of " "added date.", "Item '{0}' is reimported, skipping import of added date.",
util.displayable_path(item.path), util.displayable_path(item.path),
) )
return return

View file

@ -28,7 +28,7 @@ class InlineError(Exception):
def __init__(self, code, exc): def __init__(self, code, exc):
super().__init__( super().__init__(
("error in inline path field code:\n" "%s\n%s: %s") ("error in inline path field code:\n%s\n%s: %s")
% (code, type(exc).__name__, str(exc)) % (code, type(exc).__name__, str(exc))
) )
@ -87,7 +87,7 @@ class InlinePlugin(BeetsPlugin):
func = _compile_func(python_code) func = _compile_func(python_code)
except SyntaxError: except SyntaxError:
self._log.error( self._log.error(
"syntax error in inline field definition:\n" "{0}", "syntax error in inline field definition:\n{0}",
traceback.format_exc(), traceback.format_exc(),
) )
return return

View file

@ -267,7 +267,7 @@ def process_tracks(lib, tracks, log):
count = int(song.get("play_count", 0)) count = int(song.get("play_count", 0))
new_count = int(tracks[num].get("playcount", 1)) new_count = int(tracks[num].get("playcount", 1))
log.debug( log.debug(
"match: {0} - {1} ({2}) " "updating: play_count {3} => {4}", "match: {0} - {1} ({2}) updating: play_count {3} => {4}",
song.artist, song.artist,
song.title, song.title,
song.album, song.album,

View file

@ -180,7 +180,7 @@ class ListenBrainzPlugin(BeetsPlugin):
) )
for playlist in listenbrainz_playlists: for playlist in listenbrainz_playlists:
self._log.debug( self._log.debug(
f'Playlist: {playlist["type"]} - {playlist["date"]}' f"Playlist: {playlist['type']} - {playlist['date']}"
) )
return listenbrainz_playlists return listenbrainz_playlists

View file

@ -557,7 +557,7 @@ class Genius(SearchBackend):
@cached_property @cached_property
def headers(self) -> dict[str, str]: def headers(self) -> dict[str, str]:
return {"Authorization": f'Bearer {self.config["genius_api_key"]}'} return {"Authorization": f"Bearer {self.config['genius_api_key']}"}
def search(self, artist: str, title: str) -> Iterable[SearchResult]: def search(self, artist: str, title: str) -> Iterable[SearchResult]:
search_data: GeniusAPI.Search = self.fetch_json( search_data: GeniusAPI.Search = self.fetch_json(
@ -913,17 +913,17 @@ class RestFiles:
def write_artist(self, artist: str, items: Iterable[Item]) -> None: def write_artist(self, artist: str, items: Iterable[Item]) -> None:
parts = [ parts = [
f'{artist}\n{"=" * len(artist)}', f"{artist}\n{'=' * len(artist)}",
".. contents::\n :local:", ".. contents::\n :local:",
] ]
for album, items in groupby(items, key=lambda i: i.album): for album, items in groupby(items, key=lambda i: i.album):
parts.append(f'{album}\n{"-" * len(album)}') parts.append(f"{album}\n{'-' * len(album)}")
parts.extend( parts.extend(
part part
for i in items for i in items
if (title := f":index:`{i.title.strip()}`") if (title := f":index:`{i.title.strip()}`")
for part in ( for part in (
f'{title}\n{"~" * len(title)}', f"{title}\n{'~' * len(title)}",
textwrap.indent(i.lyrics, "| "), textwrap.indent(i.lyrics, "| "),
) )
) )

View file

@ -327,7 +327,7 @@ class SmartPlaylistPlugin(BeetsPlugin):
if extm3u: if extm3u:
attr = [(k, entry.item[k]) for k in keys] attr = [(k, entry.item[k]) for k in keys]
al = [ al = [
f" {key}=\"{quote(str(value), safe='/:')}\"" f' {key}="{quote(str(value), safe="/:")}"'
for key, value in attr for key, value in attr
] ]
attrs = "".join(al) attrs = "".join(al)

View file

@ -208,8 +208,7 @@ class SpotifyPlugin(MetadataSourcePlugin, BeetsPlugin):
"Retry-After", DEFAULT_WAITING_TIME "Retry-After", DEFAULT_WAITING_TIME
) )
self._log.debug( self._log.debug(
f"Too many API requests. Retrying after " f"Too many API requests. Retrying after {seconds} seconds."
f"{seconds} seconds."
) )
time.sleep(int(seconds) + 1) time.sleep(int(seconds) + 1)
return self._handle_response( return self._handle_response(

View file

@ -115,7 +115,7 @@ class SubsonicPlaylistPlugin(BeetsPlugin):
)[0] )[0]
if playlists.attrib.get("code", "200") != "200": if playlists.attrib.get("code", "200") != "200":
alt_error = ( alt_error = (
"error getting playlists," " but no error message found" "error getting playlists, but no error message found"
) )
self._log.warn(playlists.attrib.get("message", alt_error)) self._log.warn(playlists.attrib.get("message", alt_error))
return return

View file

@ -54,7 +54,7 @@ class ThePlugin(BeetsPlugin):
else: else:
if not (p.startswith("^") or p.endswith("$")): if not (p.startswith("^") or p.endswith("$")):
self._log.warning( self._log.warning(
'warning: "{0}" will not ' "match string start/end", 'warning: "{0}" will not match string start/end',
p, p,
) )
if self.config["a"]: if self.config["a"]:

View file

@ -161,7 +161,7 @@ class ThumbnailsPlugin(BeetsPlugin):
) )
else: else:
self._log.debug( self._log.debug(
"{1}x{1} thumbnail for {0} exists and is " "recent enough", "{1}x{1} thumbnail for {0} exists and is recent enough",
album, album,
size, size,
) )

View file

@ -93,7 +93,7 @@ class ZeroPlugin(BeetsPlugin):
self._log.error("invalid field: {0}", field) self._log.error("invalid field: {0}", field)
elif field in ("id", "path", "album_id"): elif field in ("id", "path", "album_id"):
self._log.warning( self._log.warning(
"field '{0}' ignored, zeroing " "it would be dangerous", field "field '{0}' ignored, zeroing it would be dangerous", field
) )
else: else:
try: try:

View file

@ -170,7 +170,7 @@ For packagers:
Other changes: Other changes:
{new_header} {new_header}
{'-' * len(new_header)} {"-" * len(new_header)}
""", """,
text, text,
) )

View file

@ -67,9 +67,9 @@ class ConvertMixin:
self.assertIsFile(path) self.assertIsFile(path)
with open(path, "rb") as f: with open(path, "rb") as f:
f.seek(-len(display_tag), os.SEEK_END) f.seek(-len(display_tag), os.SEEK_END)
assert ( assert f.read() == tag, (
f.read() == tag f"{displayable_path(path)} is not tagged with {display_tag}"
), f"{displayable_path(path)} is not tagged with {display_tag}" )
def assertNoFileTag(self, path, tag): def assertNoFileTag(self, path, tag):
"""Assert that the path is a file and the files content does not """Assert that the path is a file and the files content does not
@ -80,9 +80,9 @@ class ConvertMixin:
self.assertIsFile(path) self.assertIsFile(path)
with open(path, "rb") as f: with open(path, "rb") as f:
f.seek(-len(tag), os.SEEK_END) f.seek(-len(tag), os.SEEK_END)
assert ( assert f.read() != tag, (
f.read() != tag f"{displayable_path(path)} is unexpectedly tagged with {display_tag}"
), f"{displayable_path(path)} is unexpectedly tagged with {display_tag}" )
class ConvertTestCase(ConvertMixin, PluginTestCase): class ConvertTestCase(ConvertMixin, PluginTestCase):
@ -124,9 +124,9 @@ class ImportConvertTest(AsIsImporterMixin, ImportHelper, ConvertTestCase):
self.run_asis_importer() self.run_asis_importer()
for path in self.importer.paths: for path in self.importer.paths:
for root, dirnames, filenames in os.walk(path): for root, dirnames, filenames in os.walk(path):
assert ( assert len(fnmatch.filter(filenames, "*.mp3")) == 0, (
len(fnmatch.filter(filenames, "*.mp3")) == 0 f"Non-empty import directory {util.displayable_path(path)}"
), f"Non-empty import directory {util.displayable_path(path)}" )
def get_count_of_import_files(self): def get_count_of_import_files(self):
import_file_count = 0 import_file_count = 0

View file

@ -153,9 +153,9 @@ class EmbedartCliTest(PluginMixin, FetchImageHelper, BeetsTestCase):
self.run_command("embedart", "-y", "-f", self.abbey_differentpath) self.run_command("embedart", "-y", "-f", self.abbey_differentpath)
mediafile = MediaFile(syspath(item.path)) mediafile = MediaFile(syspath(item.path))
assert ( assert mediafile.images[0].data == self.image_data, (
mediafile.images[0].data == self.image_data f"Image written is not {displayable_path(self.abbey_artpath)}"
), f"Image written is not {displayable_path(self.abbey_artpath)}" )
@require_artresizer_compare @require_artresizer_compare
def test_accept_similar_art(self): def test_accept_similar_art(self):
@ -167,9 +167,9 @@ class EmbedartCliTest(PluginMixin, FetchImageHelper, BeetsTestCase):
self.run_command("embedart", "-y", "-f", self.abbey_similarpath) self.run_command("embedart", "-y", "-f", self.abbey_similarpath)
mediafile = MediaFile(syspath(item.path)) mediafile = MediaFile(syspath(item.path))
assert ( assert mediafile.images[0].data == self.image_data, (
mediafile.images[0].data == self.image_data f"Image written is not {displayable_path(self.abbey_similarpath)}"
), f"Image written is not {displayable_path(self.abbey_similarpath)}" )
def test_non_ascii_album_path(self): def test_non_ascii_album_path(self):
resource_path = os.path.join(_common.RSRC, b"image.mp3") resource_path = os.path.join(_common.RSRC, b"image.mp3")

View file

@ -143,7 +143,7 @@ class EmbyUpdateTest(PluginTestCase):
responses.add( responses.add(
responses.POST, responses.POST,
("http://localhost:8096" "/Users/AuthenticateByName"), ("http://localhost:8096/Users/AuthenticateByName"),
body=body, body=body,
status=200, status=200,
content_type="application/json", content_type="application/json",

View file

@ -64,6 +64,6 @@ class MBSubmitPluginTest(PluginMixin, TerminalImportMixin, ImportTestCase):
# Manually build the string for comparing the output. # Manually build the string for comparing the output.
tracklist = ( tracklist = (
"Open files with Picard? " "02. Tag Track 2 - Tag Artist (0:01)" "Open files with Picard? 02. Tag Track 2 - Tag Artist (0:01)"
) )
assert tracklist in output.getvalue() assert tracklist in output.getvalue()

View file

@ -97,7 +97,7 @@ class PlayPluginTest(CleanupModulesMixin, PluginTestCase):
with open(open_mock.call_args[0][0][0], "rb") as f: with open(open_mock.call_args[0][0][0], "rb") as f:
playlist = f.read().decode("utf-8") playlist = f.read().decode("utf-8")
assert ( assert (
f'{os.path.dirname(self.item.path.decode("utf-8"))}\n' == playlist f"{os.path.dirname(self.item.path.decode('utf-8'))}\n" == playlist
) )
def test_raw(self, open_mock): def test_raw(self, open_mock):

View file

@ -174,7 +174,7 @@ class EventsTest(PluginImportTestCase):
logs = [line for line in logs if not line.startswith("Sending event:")] logs = [line for line in logs if not line.startswith("Sending event:")]
assert logs == [ assert logs == [
f'Album: {displayable_path(os.path.join(self.import_dir, b"album"))}', f"Album: {displayable_path(os.path.join(self.import_dir, b'album'))}",
f" {displayable_path(self.import_media[0].path)}", f" {displayable_path(self.import_media[0].path)}",
f" {displayable_path(self.import_media[1].path)}", f" {displayable_path(self.import_media[1].path)}",
] ]

View file

@ -61,9 +61,9 @@ class ParseTest(unittest.TestCase):
""" """
assert isinstance(obj, functemplate.Call), f"not a Call: {obj}" assert isinstance(obj, functemplate.Call), f"not a Call: {obj}"
assert obj.ident == ident, f"wrong identifier: {obj.ident} vs. {ident}" assert obj.ident == ident, f"wrong identifier: {obj.ident} vs. {ident}"
assert ( assert len(obj.args) == numargs, (
len(obj.args) == numargs f"wrong argument count in {obj.ident}: {len(obj.args)} vs. {numargs}"
), f"wrong argument count in {obj.ident}: {len(obj.args)} vs. {numargs}" )
def test_plain_text(self): def test_plain_text(self):
assert list(_normparse("hello world")) == ["hello world"] assert list(_normparse("hello world")) == ["hello world"]

View file

@ -1441,7 +1441,7 @@ class CompletionTest(TestPluginTestCase):
assert tester.returncode == 0 assert tester.returncode == 0
assert out == b"completion tests passed\n", ( assert out == b"completion tests passed\n", (
"test/test_completion.sh did not execute properly. " "test/test_completion.sh did not execute properly. "
f'Output:{out.decode("utf-8")}' f"Output:{out.decode('utf-8')}"
) )