Skip to content

Commit

Permalink
Merge pull request #4156 from vivodi/e501
Browse files Browse the repository at this point in the history
Adopt the `SIM` rules
  • Loading branch information
gazpachoking authored Jan 13, 2025
2 parents 7d2c67b + 46fae4f commit b9a8aff
Show file tree
Hide file tree
Showing 107 changed files with 718 additions and 920 deletions.
9 changes: 5 additions & 4 deletions dev_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,11 @@ def bump_version(bump_type):
if bump_type == 'dev':
ver_split.append('dev')
new_version = '.'.join(ver_split)
for line in fileinput.FileInput('flexget/_version.py', inplace=1):
if line.startswith('__version__ ='):
line = f"__version__ = '{new_version}'\n"
print(line, end='')
with fileinput.input('flexget/_version.py', inplace=True) as input:
for line in input:
if line.startswith('__version__ ='):
line = f"__version__ = '{new_version}'\n"
print(line, end='')
click.echo(f'new version: {new_version}')


Expand Down
10 changes: 3 additions & 7 deletions flexget/api/core/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,21 +427,17 @@ def post(self, session: Session = None) -> Response:
"""Execute task and stream results"""
data = request.json
for task in data.get('tasks'):
if task.lower() not in [
t.lower() for t in self.manager.user_config.get('tasks', {}).keys()
]:
if task.lower() not in [t.lower() for t in self.manager.user_config.get('tasks', {})]:
raise NotFoundError(f'task {task} does not exist')

queue = ExecuteLog()
output = queue if data.get('loglevel') else None
stream = (
True
if any(
stream = bool(
any(
arg[0] in ['progress', 'summary', 'loglevel', 'entry_dump']
for arg in data.items()
if arg[1]
)
else False
)
loglevel = data.pop('loglevel', None)

Expand Down
10 changes: 2 additions & 8 deletions flexget/components/archive/archive.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,7 @@ class Archive:
def on_task_learn(self, task, config):
"""Add new entries into archive. We use learn phase in case the task corrects title or url via some plugins."""

if isinstance(config, bool):
tag_names = []
else:
tag_names = config
tag_names = [] if isinstance(config, bool) else config

tags = []
for tag_name in set(tag_names):
Expand Down Expand Up @@ -102,10 +99,7 @@ def search(self, task, entry, config=None):

session = Session()
entries = set()
if isinstance(config, bool):
tag_names = None
else:
tag_names = config
tag_names = None if isinstance(config, bool) else config
try:
for query in entry.get('search_strings', [entry['title']]):
# clean some characters out of the string for better results
Expand Down
5 changes: 2 additions & 3 deletions flexget/components/archives/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,8 @@ def open(self, member):
def extract_file(self, member, destination):
"""Extract a member file to the specified destination"""
try:
with self.open(member) as source:
with open(destination, 'wb') as target:
shutil.copyfileobj(source, target)
with self.open(member) as source, open(destination, 'wb') as target:
shutil.copyfileobj(source, target)
except OSError as error:
raise FSError(error)

Expand Down
24 changes: 11 additions & 13 deletions flexget/components/bittorrent/torrent.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,12 @@ def on_task_modify(self, task, config):
# a small torrent file since it starts with TORRENT_RE
data = f.read()

if 'content-length' in entry:
if len(data) != entry['content-length']:
entry.fail(
'Torrent file length doesn\'t match to the one reported by the server'
)
self.purge(entry)
continue
if 'content-length' in entry and len(data) != entry['content-length']:
entry.fail(
'Torrent file length doesn\'t match to the one reported by the server'
)
self.purge(entry)
continue

# construct torrent object
try:
Expand Down Expand Up @@ -76,12 +75,11 @@ def on_task_modify(self, task, config):
@plugin.priority(TORRENT_PRIO)
def on_task_output(self, task, config):
for entry in task.entries:
if 'torrent' in entry:
if entry['torrent'].modified:
# re-write data into a file
logger.debug('Writing modified torrent file for {}', entry['title'])
with open(entry['file'], 'wb+') as f:
f.write(entry['torrent'].encode())
if 'torrent' in entry and entry['torrent'].modified:
# re-write data into a file
logger.debug('Writing modified torrent file for {}', entry['title'])
with open(entry['file'], 'wb+') as f:
f.write(entry['torrent'].encode())

def make_filename(self, torrent, entry):
"""Build a filename for this torrent"""
Expand Down
66 changes: 18 additions & 48 deletions flexget/components/emby/api_emby.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,10 +171,7 @@ class EmbyAuth(EmbyApiBase):
_login_type = None

def __init__(self, **kwargs):
if 'server' in kwargs:
server = kwargs.get('server')
else:
server = kwargs
server = kwargs.get('server') if 'server' in kwargs else kwargs

EmbyApiBase.update_using_map(self, EmbyAuth.field_map, server)

Expand Down Expand Up @@ -848,9 +845,7 @@ def _get_list_data(auth, **kwargs):
):
continue

if search_list['Type'] != 'CollectionFolder':
continue
elif (
if search_list['Type'] != 'CollectionFolder' or (
search_list['CollectionType'] != 'tvshows'
and search_list['CollectionType'] != 'movies'
):
Expand All @@ -866,10 +861,7 @@ def is_type(**kwargs):
list_name = kwargs.get('list')

list_data = EmbyApiLibrary._get_list_data(auth, list=list_name)
if not list_data:
return False

return True
return bool(list_data)

@property
def fullname(self):
Expand Down Expand Up @@ -1230,10 +1222,7 @@ def is_type(**kwargs):
list_name = kwargs.get('list')

list_data = EmbyApiPlayList._get_list_data(auth, list=list_name)
if not list_data:
return False

return True
return bool(list_data)

@staticmethod
def create(item, **kwargs):
Expand Down Expand Up @@ -1628,7 +1617,7 @@ def search(**kwargs) -> 'EmbyApiMedia':
EmbyApi.set_provideres_search_arg(args, **kwargs)
else:
args['SearchTerm'], year = EmbyApiMedia.parse_string(
parameters.get('search_string', parameters.get('base_name', None))
parameters.get('search_string', parameters.get('base_name'))
)

if not args['SearchTerm']:
Expand Down Expand Up @@ -1801,7 +1790,7 @@ def search(**kwargs) -> 'EmbyApiSerie':
EmbyApi.set_provideres_search_arg(args, **parameters)
else:
args['SearchTerm'], year = EmbyApiSerie.parse_string(
parameters.get('search_string', parameters.get('base_name', None)), True
parameters.get('search_string', parameters.get('base_name')), True
)

if not args['SearchTerm']:
Expand Down Expand Up @@ -1860,13 +1849,8 @@ def is_type(**kwargs) -> bool:
if kwargs.get('series_name'):
return True

serie, _ = EmbyApiSerie.parse_string(
kwargs.get('search_string', kwargs.get('title', None))
)
if serie:
return True

return False
serie, _ = EmbyApiSerie.parse_string(kwargs.get('search_string', kwargs.get('title')))
return bool(serie)


class EmbyApiSeason(EmbyApiMedia):
Expand Down Expand Up @@ -1999,10 +1983,7 @@ def is_type(**kwargs) -> bool:
if EmbyApiSeason.parse_string(kwargs.get('title')):
return True

if EmbyApiSeason.parse_string(kwargs.get('search_string')):
return True

return False
return bool(EmbyApiSeason.parse_string(kwargs.get('search_string')))

@staticmethod
def parse_string(string: str):
Expand Down Expand Up @@ -2067,10 +2048,10 @@ def search(**kwargs) -> 'EmbyApiSeason':

seasons = seasons['Items']

target_season = parameters.get('season', None)
target_season = parameters.get('season')
if not target_season:
target_season = EmbyApiSeason.parse_string(
parameters.get('search_string', parameters.get('base_name', None))
parameters.get('search_string', parameters.get('base_name'))
)

if target_season:
Expand Down Expand Up @@ -2309,7 +2290,7 @@ def search(**kwargs) -> 'EmbyApiEpisode':

if not target_episode:
target_episode = EmbyApiEpisode.parse_string(
parameters.get('search_string', parameters.get('base_name', None))
parameters.get('search_string', parameters.get('base_name'))
)

episode = []
Expand Down Expand Up @@ -2368,10 +2349,7 @@ def is_type(**kwargs) -> bool:
):
return True

if EmbyApiEpisode.parse_string(kwargs.get('search_string', kwargs.get('title'))):
return True

return False
return bool(EmbyApiEpisode.parse_string(kwargs.get('search_string', kwargs.get('title'))))


class EmbyApiMovie(EmbyApiMedia):
Expand Down Expand Up @@ -2501,7 +2479,7 @@ def search(**kwargs) -> 'EmbyApiMovie':
EmbyApi.set_provideres_search_arg(args, **parameters)
else:
args['SearchTerm'], year = EmbyApiMovie.parse_string(
parameters.get('search_string', parameters.get('base_name', None))
parameters.get('search_string', parameters.get('base_name'))
)

if not args['SearchTerm']:
Expand Down Expand Up @@ -2560,13 +2538,8 @@ def is_type(**kwargs) -> bool:
if kwargs.get('movie_name'):
return True

movie, _ = EmbyApiMovie.parse_string(
kwargs.get('title', kwargs.get('search_string', None))
)
if movie:
return True

return False
movie, _ = EmbyApiMovie.parse_string(kwargs.get('title', kwargs.get('search_string')))
return bool(movie)


class EmbyApi(EmbyApiBase):
Expand Down Expand Up @@ -2631,10 +2604,7 @@ def has_provideres_search_arg(**kwargs) -> bool:
providers = {}
EmbyApi.set_provideres_search_arg(providers, **kwargs)

if providers and providers['AnyProviderIdEquals']:
return True

return False
return bool(providers and providers['AnyProviderIdEquals'])

@staticmethod
def get_auth(**kwargs) -> EmbyAuth:
Expand Down Expand Up @@ -2734,7 +2704,7 @@ def resquest_emby(
emby_connect=False,
**kwargs,
):
verify_certificates = True if emby_connect else False
verify_certificates = bool(emby_connect)

if not auth:
auth = EmbyApi.get_auth(**kwargs)
Expand Down
9 changes: 3 additions & 6 deletions flexget/components/ftp/ftp_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,7 @@ def prepare_config(self, config, task):
return config

def ftp_connect(self, config, ftp_url, current_path):
if config['use-ssl']:
ftp = ftplib.FTP_TLS()
else:
ftp = ftplib.FTP()
ftp = ftplib.FTP_TLS() if config['use-ssl'] else ftplib.FTP()

# ftp.set_debuglevel(2)
logger.debug('Connecting to ' + ftp_url.hostname)
Expand Down Expand Up @@ -177,7 +174,7 @@ def ftp_down(self, ftp, file_name, tmp_path, config, ftp_url, current_path):
if not os.path.exists(tmp_path):
os.makedirs(tmp_path)

local_file = open(os.path.join(tmp_path, file_name), 'a+b')
local_file = open(os.path.join(tmp_path, file_name), 'a+b') # noqa: SIM115
ftp = self.check_connection(ftp, config, ftp_url, current_path)
try:
ftp.sendcmd("TYPE I")
Expand All @@ -203,7 +200,7 @@ def ftp_down(self, ftp, file_name, tmp_path, config, ftp_url, current_path):
# Delete the downloaded file and try again from the beginning.
local_file.close()
os.remove(os.path.join(tmp_path, file_name))
local_file = open(os.path.join(tmp_path, file_name), 'a+b')
local_file = open(os.path.join(tmp_path, file_name), 'a+b') # noqa: SIM115
max_attempts -= 1

size_at_last_err = local_file.tell()
Expand Down
5 changes: 1 addition & 4 deletions flexget/components/history/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@ def do_cli(manager, options):
if options.task:
query = query.filter(db.History.task.like('%' + options.task + '%'))
query = query.order_by(desc(db.History.time)).limit(options.limit)
if options.short:
headers = ['Time', 'Title']
else:
headers = ['Field', 'Value']
headers = ['Time', 'Title'] if options.short else ['Field', 'Value']
title = f'Showing {query.count()} entries from History'
table = TerminalTable(*headers, table_type=options.table_type, title=title)
for item in reversed(query.all()):
Expand Down
50 changes: 24 additions & 26 deletions flexget/components/imdb/imdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,33 +126,31 @@ def on_task_filter(self, task, config):

# Check defined conditions, TODO: rewrite into functions?
reasons = []
if 'min_score' in config:
if entry.get('imdb_score', 0) < config['min_score']:
reasons.append(
'min_score ({} < {})'.format(entry.get('imdb_score'), config['min_score'])
)
if 'min_votes' in config:
if entry.get('imdb_votes', 0) < config['min_votes']:
reasons.append(
'min_votes ({} < {})'.format(entry.get('imdb_votes'), config['min_votes'])
)
if 'min_meta_score' in config:
if entry.get('imdb_meta_score', 0) < config['min_meta_score']:
reasons.append(
'min_meta_score ({} < {})'.format(
entry.get('imdb_meta_score'), config['min_meta_score']
)
)
if 'min_year' in config:
if entry.get('imdb_year', 0) < config['min_year']:
reasons.append(
'min_year ({} < {})'.format(entry.get('imdb_year'), config['min_year'])
)
if 'max_year' in config:
if entry.get('imdb_year', 0) > config['max_year']:
reasons.append(
'max_year ({} > {})'.format(entry.get('imdb_year'), config['max_year'])
if 'min_score' in config and entry.get('imdb_score', 0) < config['min_score']:
reasons.append(
'min_score ({} < {})'.format(entry.get('imdb_score'), config['min_score'])
)
if 'min_votes' in config and entry.get('imdb_votes', 0) < config['min_votes']:
reasons.append(
'min_votes ({} < {})'.format(entry.get('imdb_votes'), config['min_votes'])
)
if (
'min_meta_score' in config
and entry.get('imdb_meta_score', 0) < config['min_meta_score']
):
reasons.append(
'min_meta_score ({} < {})'.format(
entry.get('imdb_meta_score'), config['min_meta_score']
)
)
if 'min_year' in config and entry.get('imdb_year', 0) < config['min_year']:
reasons.append(
'min_year ({} < {})'.format(entry.get('imdb_year'), config['min_year'])
)
if 'max_year' in config and entry.get('imdb_year', 0) > config['max_year']:
reasons.append(
'max_year ({} > {})'.format(entry.get('imdb_year'), config['max_year'])
)

if 'accept_genres' in config:
accepted = config['accept_genres']
Expand Down
5 changes: 2 additions & 3 deletions flexget/components/imdb/imdb_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ class MetainfoImdbUrl:

def on_task_metainfo(self, task, config):
# check if disabled (value set to false)
if 'scan_imdb' in task.config:
if not task.config['scan_imdb']:
return
if 'scan_imdb' in task.config and not task.config['scan_imdb']:
return

for entry in task.entries:
# Don't override already populated imdb_ids
Expand Down
Loading

0 comments on commit b9a8aff

Please sign in to comment.