Skip to content

Commit

Permalink
Merge pull request #2010 from glensc/ruff-configure
Browse files Browse the repository at this point in the history
Linter: Enable more ruff format/linter rules
  • Loading branch information
glensc authored Jul 8, 2024
2 parents e59b844 + 607d9b1 commit 2431e17
Show file tree
Hide file tree
Showing 104 changed files with 329 additions and 469 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ repos:
- id: destroyed-symlinks

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.4.4
rev: v0.5.1
hooks:
- id: ruff
args: [ --fix ]
Expand Down
2 changes: 2 additions & 0 deletions plextraktsync/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
from __future__ import annotations

__version__ = "0.31.0dev0"
2 changes: 2 additions & 0 deletions plextraktsync/__main__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

if len(__package__) == 0:
import sys

Expand Down
26 changes: 8 additions & 18 deletions plextraktsync/cli.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from functools import wraps
from os import environ

Expand Down Expand Up @@ -25,9 +27,7 @@ def wrap(*args, **kwargs):
try:
cmd(*args, **kwargs)
except EOFError as e:
raise ClickException(
f"Program requested terminal, No terminal is connected: {e}"
)
raise ClickException(f"Program requested terminal, No terminal is connected: {e}")
except ClickException as e:
from plextraktsync.factory import logging

Expand Down Expand Up @@ -83,9 +83,7 @@ def cli(

if not ctx.invoked_subcommand:
logger = factory.logger
logger.warning(
'plextraktsync without command is deprecated. Executing "plextraktsync sync"'
)
logger.warning('plextraktsync without command is deprecated. Executing "plextraktsync sync"')
sync()


Expand Down Expand Up @@ -178,12 +176,8 @@ def plex_login():

@command()
@click.option("--library", help="Specify Library to use")
@click.option(
"--show", "show", type=str, show_default=True, help="Sync specific show only"
)
@click.option(
"--movie", "movie", type=str, show_default=True, help="Sync specific movie only"
)
@click.option("--show", "show", type=str, show_default=True, help="Sync specific show only")
@click.option("--movie", "movie", type=str, show_default=True, help="Sync specific movie only")
@click.option(
"--id",
"ids",
Expand All @@ -195,9 +189,7 @@ def plex_login():
@click.option(
"--sync",
"sync_option",
type=click.Choice(
["all", "movies", "tv", "shows", "watchlist"], case_sensitive=False
),
type=click.Choice(["all", "movies", "tv", "shows", "watchlist"], case_sensitive=False),
default="all",
show_default=True,
help="Specify what to sync",
Expand Down Expand Up @@ -342,9 +334,7 @@ def watched_shows():


@command()
@click.option(
"--urls-expire-after", is_flag=True, help="Print urls_expire_after configuration"
)
@click.option("--urls-expire-after", is_flag=True, help="Print urls_expire_after configuration")
@click.option("--edit", is_flag=True, help="Open config file in editor")
@click.option("--locate", is_flag=True, help="Locate config file in file browser")
def config():
Expand Down
6 changes: 3 additions & 3 deletions plextraktsync/commands/bug_report.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from urllib.parse import urlencode

from plextraktsync.util.openurl import openurl
Expand Down Expand Up @@ -26,9 +28,7 @@ def bug_url():
def bug_report():
url = bug_url()

print(
"Opening bug report URL in browser, if that doesn't work open the link manually:"
)
print("Opening bug report URL in browser, if that doesn't work open the link manually:")
print("")
print(url)
openurl(url)
23 changes: 7 additions & 16 deletions plextraktsync/commands/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,14 @@ def get_sorted_cache(session: CachedSession, sorting: str, reverse: bool):
yield from sorter(session.cache.responses.values())


def responses_by_url(
session: CachedSession, url: str
) -> Generator[CachedRequest, Any, None]:
return (
response for response in session.cache.responses.values() if response.url == url
)
def responses_by_url(session: CachedSession, url: str) -> Generator[CachedRequest, Any, None]:
return (response for response in session.cache.responses.values() if response.url == url)


# https://stackoverflow.com/questions/36106712/how-can-i-limit-iterations-of-a-loop-in-python
def limit_iterator(items, limit: int):
if not limit or limit <= 0:
i = 0
for v in items:
yield i, v
i += 1
yield from enumerate(items)

else:
yield from zip(range(limit), items)
Expand All @@ -49,12 +42,12 @@ def render_xml(data):
return None

root = ElementTree.fromstring(data)
try:
import contextlib

with contextlib.suppress(AttributeError):
# requires python 3.9
# https://stackoverflow.com/a/39482716/2314626
ElementTree.indent(root)
except AttributeError:
pass

return ElementTree.tostring(root, encoding="utf8").decode("utf8")

Expand All @@ -75,9 +68,7 @@ def inspect_url(session: CachedSession, url: str):
matches = responses_by_url(session, url)
for m in matches:
content_type = m.headers["Content-Type"]
if content_type.startswith("text/xml") or content_type.startswith(
"application/xml"
):
if content_type.startswith("text/xml") or content_type.startswith("application/xml"):
print(f"<!-- {m} -->")
for name, value in m.headers.items():
print(f"<!-- {name}: {value} -->")
Expand Down
2 changes: 2 additions & 0 deletions plextraktsync/commands/clear_collections.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from plextraktsync.factory import factory, logger


Expand Down
2 changes: 2 additions & 0 deletions plextraktsync/commands/config.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from plextraktsync.factory import factory


Expand Down
4 changes: 1 addition & 3 deletions plextraktsync/commands/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ def download_media(plex: PlexApi, pm: PlexLibraryItem, savepath: Path):
def download_subtitles(plex: PlexApi, pm: PlexLibraryItem, savepath: Path):
print(f"Subtitles for {pm}:")
for index, sub in enumerate(pm.subtitle_streams, start=1):
print(
f" Subtitle {index}: ({sub.language}) {sub.title} (codec: {sub.codec}, selected: {sub.selected}, transient: {sub.transient})"
)
print(f" Subtitle {index}: ({sub.language}) {sub.title} (codec: {sub.codec}, selected: {sub.selected}, transient: {sub.transient})")

filename = "".join(
[
Expand Down
8 changes: 2 additions & 6 deletions plextraktsync/commands/imdb_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,16 +75,12 @@ def imdb_import(input: PathLike, dry_run: bool):
print = factory.print

for r in read_csv(input):
print(
f"Importing [blue]{r.media_type} {r.imdb}[/]: {r.title} ({r.year}), rated at {r.rate_date}"
)
print(f"Importing [blue]{r.media_type} {r.imdb}[/]: {r.title} ({r.year}), rated at {r.rate_date}")
m = trakt.search_by_id(r.imdb, "imdb", r.media_type)
rating = trakt.rating(m)
if r.rating == rating:
print(f"Rating {rating} already exists")
continue
print(
f"{'Would rate' if dry_run else 'Rating'} {m} with {r.rating} (was {rating})"
)
print(f"{'Would rate' if dry_run else 'Rating'} {m} with {r.rating} (was {rating})")
if not dry_run:
trakt.rate(m, r.rating, r.rate_date)
2 changes: 2 additions & 0 deletions plextraktsync/commands/info.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from plextraktsync.factory import factory
from plextraktsync.path import cache_dir, config_dir, log_dir, servers_config

Expand Down
15 changes: 5 additions & 10 deletions plextraktsync/commands/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,14 @@ def inspect_media(plex_id: PlexId):
print("Subtitles:")
for index, subtitle in enumerate(pm.subtitle_streams, start=1):
print(
f" Subtitle {index}: ({subtitle.language}) {subtitle.title} (codec: {subtitle.codec}, selected: {subtitle.selected}, transient: {subtitle.transient})"
f" Subtitle {index}: ({subtitle.language}) {subtitle.title}"
f" (codec: {subtitle.codec}, selected: {subtitle.selected}, transient: {subtitle.transient})"
)

print("Parts:")
for index, part in enumerate(pm.parts, start=1):
size = naturalsize(part.size, binary=True)
file_link = (
f"[link=file://{quote_plus(part.file)}]{escape(part.file)}[/link]"
)
file_link = f"[link=file://{quote_plus(part.file)}]{escape(part.file)}[/link]"
print(f" Part {index} (exists: {part.exists}): {file_link} {size}")

print("Markers:")
Expand All @@ -77,16 +76,12 @@ def inspect_media(plex_id: PlexId):

print("Guids:")
for guid in pm.guids:
print(
f" Guid: {guid.provider_link}, Id: {guid.id}, Provider: '{guid.provider}'"
)
print(f" Guid: {guid.provider_link}, Id: {guid.id}, Provider: '{guid.provider}'")

print(f"Metadata: {pm.to_json()}")
print(f"Played on Plex: {pm.is_watched}")

history = (
plex.history(media, device=True, account=True) if not pm.is_discover else []
)
history = plex.history(media, device=True, account=True) if not pm.is_discover else []
print("Plex play history:")
for h in history:
d = h.device
Expand Down
6 changes: 3 additions & 3 deletions plextraktsync/commands/login.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from plextraktsync.commands.plex_login import plex_login_autoconfig
from plextraktsync.commands.trakt_login import has_trakt_token, trakt_login_autoconfig
from plextraktsync.factory import factory
Expand All @@ -18,9 +20,7 @@ def login():
print(highlight("Checking Plex and Trakt login credentials existence"))
print("")
print("It will not test if the credentials are valid, only that they are present.")
print(
'If you need to re-login use "plex-login" or "trakt-login" commands respectively.'
)
print('If you need to re-login use "plex-login" or "trakt-login" commands respectively.')
print("")
ensure_login()
print(success("Done!"))
22 changes: 5 additions & 17 deletions plextraktsync/commands/plex_login.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,8 @@
PROMPT_PLEX_PASSWORD = prompt("Please enter your Plex password")
PROMPT_PLEX_USERNAME = prompt("Please enter your Plex username or e-mail")
PROMPT_PLEX_CODE = prompt("Enter a 2FA code if enabled, or leave blank otherwise")
PROMPT_PLEX_RELOGIN = prompt(
"You already have Plex Access Token, do you want to log in again?"
)
SUCCESS_MESSAGE = success(
"Plex Media Server Authentication Token and base URL have been added to servers.yml"
)
PROMPT_PLEX_RELOGIN = prompt("You already have Plex Access Token, do you want to log in again?")
SUCCESS_MESSAGE = success("Plex Media Server Authentication Token and base URL have been added to servers.yml")
CONFIG = factory.config

style = get_style(
Expand Down Expand Up @@ -64,9 +60,7 @@ def server_urls(server: MyPlexResource):
def myplex_login(username, password):
while True:
username = Prompt.ask(PROMPT_PLEX_USERNAME, default=username)
password = Prompt.ask(
PROMPT_PLEX_PASSWORD, password=True, default=password, show_default=False
)
password = Prompt.ask(PROMPT_PLEX_PASSWORD, password=True, default=password, show_default=False)
code = Prompt.ask(PROMPT_PLEX_CODE)
try:
return MyPlexAccount(username=username, password=password, code=code)
Expand Down Expand Up @@ -108,9 +102,7 @@ def format_server(s):
lines = []
product = f"{s.product}/{s.productVersion}"
platform = f"{s.device}: {s.platform}/{s.platformVersion}"
lines.append(
f"{s.name}: Last seen: {str(s.lastSeenAt)}, Server: {product} on {platform}"
)
lines.append(f"{s.name}: Last seen: {str(s.lastSeenAt)}, Server: {product} on {platform}")
c: ResourceConnection
for c in s.connections:
lines.append(f" {c.uri}")
Expand Down Expand Up @@ -170,11 +162,7 @@ def choose_server(account: MyPlexAccount) -> tuple[MyPlexResource, PlexServer]:

# Connect to obtain baseUrl
print()
print(
title(
f"Attempting to connect to {server.name}. This may take time and print some errors."
)
)
print(title(f"Attempting to connect to {server.name}. This may take time and print some errors."))
print(title("Server connections:"))
for c in server.connections:
print(f" {c.uri}")
Expand Down
4 changes: 1 addition & 3 deletions plextraktsync/commands/self_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,7 @@ def self_update(pr: int):
execp(f"pipx uninstall plextraktsync@{pr}")

print(f"Updating PlexTraktSync to the pull request #{pr} version using pipx")
execp(
f"pipx install --suffix=@{pr} --force git+https://github.com/Taxel/PlexTraktSync@refs/pull/{pr}/head"
)
execp(f"pipx install --suffix=@{pr} --force git+https://github.com/Taxel/PlexTraktSync@refs/pull/{pr}/head")
return

print("Updating PlexTraktSync to the latest version using pipx")
Expand Down
12 changes: 3 additions & 9 deletions plextraktsync/commands/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,13 @@ def sync(
dry_run=dry_run,
)
if server:
logger.warning(
'"plextraktsync sync --server=<name>" is deprecated use "plextraktsync --server=<name> sync"'
)
logger.warning('"plextraktsync sync --server=<name>" is deprecated use "plextraktsync --server=<name> sync"')
config.update(server=server)
if no_progress_bar:
logger.warning(
'"plextraktsync sync --no-progress-bar" is deprecated use "plextraktsync --no-progressbar sync"'
)
logger.warning('"plextraktsync sync --no-progress-bar" is deprecated use "plextraktsync --no-progressbar sync"')
config.update(progress=False)
if batch_delay:
logger.warning(
'"plextraktsync sync --batch-delay=<number>" is deprecated use "plextraktsync ---batch-delay=<number> sync"'
)
logger.warning('"plextraktsync sync --batch-delay=<number>" is deprecated use "plextraktsync ---batch-delay=<number> sync"')
config.update(batch_delay=batch_delay)

ensure_login()
Expand Down
5 changes: 1 addition & 4 deletions plextraktsync/commands/trakt_login.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,7 @@

PROMPT_TRAKT_CLIENT_ID = prompt("Please enter your client id")
PROMPT_TRAKT_CLIENT_SECRET = prompt("Please enter your client secret")
TRAKT_LOGIN_SUCCESS = success(
"You are now logged into Trakt. "
"Your Trakt credentials have been added in .env and .pytrakt.json files."
)
TRAKT_LOGIN_SUCCESS = success("You are now logged into Trakt. Your Trakt credentials have been added in .env and .pytrakt.json files.")


def trakt_authenticate(api: TraktApi):
Expand Down
2 changes: 2 additions & 0 deletions plextraktsync/commands/unmatched.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from plextraktsync.commands.login import ensure_login
from plextraktsync.decorators.coro import coro
from plextraktsync.factory import factory
Expand Down
6 changes: 3 additions & 3 deletions plextraktsync/commands/watched_shows.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from rich.table import Table

from plextraktsync.factory import factory
Expand All @@ -7,9 +9,7 @@ def watched_shows():
trakt = factory.trakt_api
print = factory.print

table = Table(
show_header=True, header_style="bold magenta", title="Watched shows on Trakt"
)
table = Table(show_header=True, header_style="bold magenta", title="Watched shows on Trakt")
table.add_column("Id", style="dim", width=6)
table.add_column("Slug")
table.add_column("Seasons", justify="right")
Expand Down
Loading

0 comments on commit 2431e17

Please sign in to comment.