Skip to content

Commit

Permalink
Maintenance: Replace pylint with ruff (#1675)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcelveldt authored Sep 19, 2024
1 parent c1aadac commit e2046b4
Show file tree
Hide file tree
Showing 30 changed files with 31 additions and 128 deletions.
17 changes: 6 additions & 11 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -80,17 +80,12 @@ repos:
always_run: true
args:
- --branch=main
# - id: pylint
# name: 🌟 Starring code with pylint
# language: system
# types: [python]
# entry: scripts/run-in-env.sh pylint
# - id: trailing-whitespace
# name: ✄ Trim Trailing Whitespace
# language: system
# types: [text]
# entry: scripts/run-in-env.sh trailing-whitespace-fixer
# stages: [commit, push, manual]
- id: trailing-whitespace
name: ✄ Trim Trailing Whitespace
language: system
types: [text]
entry: scripts/run-in-env.sh trailing-whitespace-fixer
stages: [commit, push, manual]
- id: mypy
name: mypy
entry: scripts/run-in-env.sh mypy
Expand Down
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ RUN uv pip install \
--no-cache \
--find-links "https://wheels.home-assistant.io/musllinux/" \
"music-assistant[server]@dist/music_assistant-${MASS_VERSION}-py3-none-any.whl"

# Set some labels
LABEL \
org.opencontainers.image.title="Music Assistant Server" \
Expand All @@ -32,7 +32,7 @@ LABEL \
io.hass.platform="${TARGETPLATFORM}" \
io.hass.type="addon"

RUN rm -rf dist
RUN rm -rf dist

VOLUME [ "/data" ]
EXPOSE 8095
Expand Down
1 change: 0 additions & 1 deletion music_assistant/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,6 @@ def setup_logger(data_path: str, level: str = "DEBUG"):

def _enable_posix_spawn() -> None:
"""Enable posix_spawn on Alpine Linux."""
# pylint: disable=protected-access
if subprocess._USE_POSIX_SPAWN:
return

Expand Down
8 changes: 1 addition & 7 deletions music_assistant/common/helpers/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,8 @@
from urllib.parse import urlparse
from uuid import UUID

# pylint: disable=invalid-name
T = TypeVar("T")
CALLBACK_TYPE = Callable[[], None]
# pylint: enable=invalid-name

keyword_pattern = re.compile("title=|artist=")
title_pattern = re.compile(r"title=\"(?P<title>.*?)\"")
Expand Down Expand Up @@ -207,7 +205,6 @@ async def get_ip() -> str:

def _get_ip() -> str:
"""Get primary IP-address for this host."""
# pylint: disable=broad-except,no-member
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
Expand Down Expand Up @@ -251,7 +248,7 @@ async def get_ip_from_host(dns_name: str) -> str | None:
def _resolve() -> str | None:
try:
return socket.gethostbyname(dns_name)
except Exception: # pylint: disable=broad-except
except Exception:
# fail gracefully!
return None

Expand All @@ -262,7 +259,6 @@ async def get_ip_pton(ip_string: str | None = None) -> bytes:
"""Return socket pton for local ip."""
if ip_string is None:
ip_string = await get_ip()
# pylint:disable=no-member
try:
return await asyncio.to_thread(socket.inet_pton, socket.AF_INET, ip_string)
except OSError:
Expand All @@ -272,12 +268,10 @@ async def get_ip_pton(ip_string: str | None = None) -> bytes:
def get_folder_size(folderpath: str) -> float:
"""Return folder size in gb."""
total_size = 0
# pylint: disable=unused-variable
for dirpath, _dirnames, filenames in os.walk(folderpath):
for _file in filenames:
_fp = os.path.join(dirpath, _file)
total_size += os.path.getsize(_fp)
# pylint: enable=unused-variable
return total_size / float(1 << 30)


Expand Down
2 changes: 0 additions & 2 deletions music_assistant/common/models/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@
from music_assistant.common.helpers.json import get_serializable_value
from music_assistant.common.models.event import MassEvent

# pylint: disable=unnecessary-lambda


@dataclass
class CommandMessage(DataClassORJSONMixin):
Expand Down
4 changes: 1 addition & 3 deletions music_assistant/common/models/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,5 @@ class MassEvent(DataClassORJSONMixin):
object_id: str | None = None # player_id, queue_id or uri
data: Any = field(
default=None,
metadata={
"serialize": lambda v: get_serializable_value(v) # pylint: disable=unnecessary-lambda
},
metadata={"serialize": lambda v: get_serializable_value(v)},
)
2 changes: 1 addition & 1 deletion music_assistant/server/controllers/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ async def get(
) and (not checksum or db_row["checksum"] == checksum and db_row["expires"] >= cur_time):
try:
data = await asyncio.to_thread(json_loads, db_row["data"])
except Exception as exc: # pylint: disable=broad-except
except Exception as exc:
LOGGER.error(
"Error parsing cache data for %s: %s",
memory_key,
Expand Down
2 changes: 1 addition & 1 deletion music_assistant/server/controllers/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -665,7 +665,7 @@ async def _load(self) -> None:
return
except FileNotFoundError:
pass
except JSON_DECODE_EXCEPTIONS: # pylint: disable=catching-non-exception
except JSON_DECODE_EXCEPTIONS:
LOGGER.exception("Error while reading persistent storage file %s", filename)
LOGGER.debug("Started with empty storage: No persistent storage file found.")

Expand Down
2 changes: 1 addition & 1 deletion music_assistant/server/controllers/players.py
Original file line number Diff line number Diff line change
Expand Up @@ -1125,7 +1125,7 @@ async def _poll_players(self) -> None:
player.available = False
player.state = PlayerState.IDLE
player.powered = False
except Exception as err: # pylint: disable=broad-except
except Exception as err:
self.logger.warning(
"Error while requesting latest state from player %s: %s",
player.display_name,
Expand Down
2 changes: 0 additions & 2 deletions music_assistant/server/controllers/streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,6 @@
FLOW_DEFAULT_BIT_DEPTH = 24


# pylint:disable=too-many-locals

isfile = wrap(os.path.isfile)


Expand Down
4 changes: 2 additions & 2 deletions music_assistant/server/controllers/webserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ def handle_event(event: MassEvent) -> None:
except asyncio.CancelledError:
self._logger.debug("Connection closed by client")

except Exception: # pylint: disable=broad-except
except Exception:
self._logger.exception("Unexpected error inside websocket API")

finally:
Expand Down Expand Up @@ -361,7 +361,7 @@ async def _run_handler(self, handler: APICommandHandler, msg: CommandMessage) ->
elif asyncio.iscoroutine(result):
result = await result
self._send_message(SuccessResultMessage(msg.message_id, result))
except Exception as err: # pylint: disable=broad-except
except Exception as err:
if self._logger.isEnabledFor(logging.DEBUG):
self._logger.exception("Error handling message: %s", msg)
else:
Expand Down
2 changes: 1 addition & 1 deletion music_assistant/server/helpers/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def parse_value(name: str, value: Any, value_type: Any, default: Any = MISSING)
logging.getLogger(__name__).warning(err)
return None
if origin is type:
return eval(value) # pylint: disable=eval-used
return eval(value)
if value_type is Any:
return value
if value is None and value_type is not NoneType:
Expand Down
1 change: 0 additions & 1 deletion music_assistant/server/helpers/app_vars.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# pylint: skip-file
# fmt: off
# flake8: noqa
# ruff: noqa
Expand Down
3 changes: 1 addition & 2 deletions music_assistant/server/helpers/audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
from music_assistant.server import MusicAssistant

LOGGER = logging.getLogger(f"{MASS_LOGGER_NAME}.audio")
# pylint:disable=consider-using-f-string,too-many-locals,too-many-statements

# ruff: noqa: PLR0915

HTTP_HEADERS = {"User-Agent": "Lavf/60.16.100.MusicAssistant"}
Expand Down Expand Up @@ -425,7 +425,6 @@ async def get_media_stream(

def create_wave_header(samplerate=44100, channels=2, bitspersample=16, duration=None):
"""Generate a wave header from given params."""
# pylint: disable=no-member
file = BytesIO()

# Generate format chunk
Expand Down
2 changes: 1 addition & 1 deletion music_assistant/server/helpers/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def _create_image():
except UnidentifiedImageError:
raise FileNotFoundError(f"Invalid image: {path_or_url}")
if size:
img.thumbnail((size, size), Image.LANCZOS) # pylint: disable=no-member
img.thumbnail((size, size), Image.LANCZOS)

mode = "RGBA" if image_format == "PNG" else "RGB"
img.convert(mode).save(data, image_format, optimize=True)
Expand Down
6 changes: 3 additions & 3 deletions music_assistant/server/helpers/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ async def async_wrapper(*args: Any) -> None:
"""Catch and log exception."""
try:
await async_func(*args)
except Exception: # pylint: disable=broad-except
except Exception:
log_exception(format_err, *args)

wrapper_func = async_wrapper
Expand All @@ -152,7 +152,7 @@ def wrapper(*args: Any) -> None:
"""Catch and log exception."""
try:
func(*args)
except Exception: # pylint: disable=broad-except
except Exception:
log_exception(format_err, *args)

wrapper_func = wrapper
Expand All @@ -168,7 +168,7 @@ async def coro_wrapper(*args: Any) -> _T | None:
"""Catch and log exception."""
try:
return await target
except Exception: # pylint: disable=broad-except
except Exception:
log_exception(format_err, *args)
return None

Expand Down
2 changes: 0 additions & 2 deletions music_assistant/server/helpers/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@

DEFAULT_CHUNKSIZE = 64000

# pylint: disable=invalid-name


class AsyncProcess:
"""
Expand Down
2 changes: 1 addition & 1 deletion music_assistant/server/helpers/webserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def register_dynamic_route(self, path: str, handler: Awaitable, method: str = "*
msg = "Dynamic routes are not enabled"
raise RuntimeError(msg)
key = f"{method}.{path}"
if key in self._dynamic_routes: # pylint: disable=unsupported-membership-test
if key in self._dynamic_routes:
msg = f"Route {path} already registered."
raise RuntimeError(msg)
self._dynamic_routes[key] = handler
Expand Down
1 change: 0 additions & 1 deletion music_assistant/server/models/player_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,6 @@ def on_group_child_power(
@property
def players(self) -> list[Player]:
"""Return all players belonging to this provider."""
# pylint: disable=no-member
return [
player
for player in self.mass.players
Expand Down
2 changes: 0 additions & 2 deletions music_assistant/server/providers/apple_music/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@
)
from music_assistant.common.models.streamdetails import StreamDetails
from music_assistant.constants import CONF_PASSWORD

# pylint: disable=no-name-in-module
from music_assistant.server.helpers.app_vars import app_var
from music_assistant.server.helpers.audio import get_hls_substream
from music_assistant.server.helpers.throttle_retry import ThrottlerManager, throttle_with_retries
Expand Down
1 change: 0 additions & 1 deletion music_assistant/server/providers/chromecast/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,6 @@ def invalidate(self) -> None:
All following callbacks won't be forwarded.
"""
# pylint: disable=protected-access
if self.castplayer.cast_info.is_audio_group:
self._mz_mgr.remove_multizone(self._uuid)
else:
Expand Down
8 changes: 2 additions & 6 deletions music_assistant/server/providers/deezer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,7 @@
)
from music_assistant.common.models.provider import ProviderManifest
from music_assistant.common.models.streamdetails import StreamDetails

# pylint: disable=no-name-in-module
from music_assistant.server.helpers.app_vars import app_var

# pylint: enable=no-name-in-module
from music_assistant.server.helpers.auth import AuthenticationHelper
from music_assistant.server.models import ProviderInstanceType
from music_assistant.server.models.music_provider import MusicProvider
Expand Down Expand Up @@ -128,7 +124,7 @@ async def setup(

async def get_config_entries(
mass: MusicAssistant,
instance_id: str | None = None, # noqa: ARG001 pylint: disable=W0613
instance_id: str | None = None, # noqa: ARG001
action: str | None = None,
values: dict[str, ConfigValueType] | None = None,
) -> tuple[ConfigEntry, ...]:
Expand Down Expand Up @@ -166,7 +162,7 @@ async def get_config_entries(
)


class DeezerProvider(MusicProvider): # pylint: disable=W0223
class DeezerProvider(MusicProvider):
"""Deezer provider support."""

client: deezer.Client
Expand Down
2 changes: 1 addition & 1 deletion music_assistant/server/providers/fanarttv/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from music_assistant.common.models.enums import ConfigEntryType, ExternalID, ProviderFeature
from music_assistant.common.models.media_items import ImageType, MediaItemImage, MediaItemMetadata
from music_assistant.server.controllers.cache import use_cache
from music_assistant.server.helpers.app_vars import app_var # pylint: disable=no-name-in-module
from music_assistant.server.helpers.app_vars import app_var
from music_assistant.server.helpers.throttle_retry import Throttler
from music_assistant.server.models.metadata_provider import MetadataProvider

Expand Down
4 changes: 2 additions & 2 deletions music_assistant/server/providers/filesystem_local/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ async def _process_item(self, item: FileSystemItem, prev_checksum: str | None) -
playlist,
overwrite_existing=prev_checksum is not None,
)
except Exception as err: # pylint: disable=broad-except
except Exception as err:
# we don't want the whole sync to crash on one file so we catch all exceptions here
self.logger.error(
"Error processing %s - %s",
Expand Down Expand Up @@ -553,7 +553,7 @@ async def get_playlist_tracks(self, prov_playlist_id: str, page: int = 0) -> lis
track.position = idx
result.append(track)

except Exception as err: # pylint: disable=broad-except
except Exception as err:
self.logger.warning(
"Error while parsing playlist %s: %s",
prov_playlist_id,
Expand Down
2 changes: 1 addition & 1 deletion music_assistant/server/providers/jellyfin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ async def setup(

async def get_config_entries(
mass: MusicAssistant,
instance_id: str | None = None, # pylint: disable=W0613
instance_id: str | None = None,
action: str | None = None,
values: dict[str, ConfigValueType] | None = None,
) -> tuple[ConfigEntry, ...]:
Expand Down
6 changes: 0 additions & 6 deletions music_assistant/server/providers/qobuz/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,7 @@
VARIOUS_ARTISTS_MBID,
VARIOUS_ARTISTS_NAME,
)

# pylint: disable=no-name-in-module
from music_assistant.server.helpers.app_vars import app_var

# pylint: enable=no-name-in-module
from music_assistant.server.helpers.throttle_retry import ThrottlerManager, throttle_with_retries
from music_assistant.server.helpers.util import lock
from music_assistant.server.models.music_provider import MusicProvider
Expand Down Expand Up @@ -585,7 +581,6 @@ async def _parse_album(self, album_obj: dict, artist_obj: dict | None = None):

async def _parse_track(self, track_obj: dict) -> Track:
"""Parse qobuz track object to generic layout."""
# pylint: disable=too-many-branches
name, version = parse_title_and_version(track_obj["title"], track_obj.get("version"))
track = Track(
item_id=str(track_obj["id"]),
Expand Down Expand Up @@ -743,7 +738,6 @@ async def _get_all_items(self, endpoint, key="tracks", **kwargs):
@throttle_with_retries
async def _get_data(self, endpoint, sign_request=False, **kwargs):
"""Get data from api."""
# pylint: disable=too-many-branches
self.logger.debug("Handling GET request to %s", endpoint)
url = f"http://www.qobuz.com/api.json/0.2/{endpoint}"
headers = {"X-App-Id": app_var(0)}
Expand Down
2 changes: 1 addition & 1 deletion music_assistant/server/providers/sonos_s1/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def _find_target_identifier(instance: Any, fallback_soco: SoCo | None) -> str |
if soco := getattr(instance, "soco", fallback_soco):
# Holds a SoCo instance attribute
# Only use attributes with no I/O
return soco._player_name or soco.ip_address # pylint: disable=protected-access
return soco._player_name or soco.ip_address
return None


Expand Down
4 changes: 0 additions & 4 deletions music_assistant/server/providers/spotify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,8 @@
Track,
)
from music_assistant.common.models.streamdetails import StreamDetails

# pylint: disable=no-name-in-module
from music_assistant.constants import VERBOSE_LOG_LEVEL
from music_assistant.server.helpers.app_vars import app_var

# pylint: enable=no-name-in-module
from music_assistant.server.helpers.audio import get_chunksize
from music_assistant.server.helpers.auth import AuthenticationHelper
from music_assistant.server.helpers.process import AsyncProcess, check_output
Expand Down
Loading

0 comments on commit e2046b4

Please sign in to comment.