Skip to content

Commit

Permalink
Upgrade codebase with pyupgrade (>=py3.6)
Browse files Browse the repository at this point in the history
Added pyupgrade utility with manual stage to pre-commit and run on all
files.

Ref: https://github.com/asottile/pyupgrade
Closes: deluge-torrent#326
  • Loading branch information
DjLegolas authored and cas-- committed Dec 29, 2021
1 parent 16895b4 commit ec0bcc1
Show file tree
Hide file tree
Showing 261 changed files with 440 additions and 713 deletions.
6 changes: 6 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,9 @@ repos:
args: [--fix=auto]
- id: trailing-whitespace
name: Fix Trailing whitespace
- repo: https://github.com/asottile/pyupgrade
rev: v2.29.1
hooks:
- id: pyupgrade
args: [--py36-plus]
stages: [manual]
2 changes: 1 addition & 1 deletion DEPENDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ All modules will require the [common](#common) section dependencies.

## Prerequisite

- [Python] _>= 3.5_
- [Python] _>= 3.6_

## Build

Expand Down
3 changes: 1 addition & 2 deletions deluge/_libtorrent.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com>
#
Expand Down Expand Up @@ -32,5 +31,5 @@

if VersionSplit(LT_VERSION) < VersionSplit(REQUIRED_VERSION):
raise LibtorrentImportError(
'Deluge %s requires libtorrent >= %s' % (get_version(), REQUIRED_VERSION)
f'Deluge {get_version()} requires libtorrent >= {REQUIRED_VERSION}'
)
11 changes: 5 additions & 6 deletions deluge/argparserbase.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Andrew Resch <andrewresch@gmail.com>
#
Expand Down Expand Up @@ -93,7 +92,7 @@ def _get_version_detail():
except ImportError:
pass
version_str += 'Python: %s\n' % platform.python_version()
version_str += 'OS: %s %s\n' % (platform.system(), common.get_os_version())
version_str += f'OS: {platform.system()} {common.get_os_version()}\n'
return version_str


Expand Down Expand Up @@ -135,7 +134,7 @@ def _format_action_invocation(self, action):
default = action.dest.upper()
args_string = self._format_args(action, default)
opt = ', '.join(action.option_strings)
parts.append('%s %s' % (opt, args_string))
parts.append(f'{opt} {args_string}')
return ', '.join(parts)


Expand Down Expand Up @@ -163,7 +162,7 @@ def __init__(self, *args, **kwargs):
self.log_stream = kwargs['log_stream']
del kwargs['log_stream']

super(ArgParserBase, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

self.common_setup = False
self.process_arg_group = False
Expand Down Expand Up @@ -244,7 +243,7 @@ def parse_args(self, args=None):
argparse.Namespace: The parsed arguments.
"""
options = super(ArgParserBase, self).parse_args(args=args)
options = super().parse_args(args=args)
return self._handle_ui_options(options)

def parse_known_ui_args(self, args, withhold=None):
Expand All @@ -260,7 +259,7 @@ def parse_known_ui_args(self, args, withhold=None):
"""
if withhold:
args = [a for a in args if a not in withhold]
options, remaining = super(ArgParserBase, self).parse_known_args(args=args)
options, remaining = super().parse_known_args(args=args)
options.remaining = remaining
# Handle common and process group options
return self._handle_ui_options(options)
Expand Down
2 changes: 1 addition & 1 deletion deluge/bencode.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def bdecode(x):
return r


class Bencached(object):
class Bencached:

__slots__ = ['bencoded']

Expand Down
31 changes: 15 additions & 16 deletions deluge/common.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007,2008 Andrew Resch <andrewresch@gmail.com>
#
Expand All @@ -24,7 +23,7 @@
import time
from contextlib import closing
from datetime import datetime
from io import BytesIO, open
from io import BytesIO
from urllib.parse import unquote_plus, urljoin
from urllib.request import pathname2url

Expand Down Expand Up @@ -135,14 +134,14 @@ def get_default_download_dir():

try:
user_dirs_path = os.path.join(xdg_config_home, 'user-dirs.dirs')
with open(user_dirs_path, 'r', encoding='utf8') as _file:
with open(user_dirs_path, encoding='utf8') as _file:
for line in _file:
if not line.startswith('#') and line.startswith('XDG_DOWNLOAD_DIR'):
download_dir = os.path.expandvars(
line.partition('=')[2].rstrip().strip('"')
)
break
except IOError:
except OSError:
pass

if not download_dir:
Expand Down Expand Up @@ -540,9 +539,9 @@ def fpeer(num_peers, total_peers):
"""
if total_peers > -1:
return '{:d} ({:d})'.format(num_peers, total_peers)
return f'{num_peers:d} ({total_peers:d})'
else:
return '{:d}'.format(num_peers)
return f'{num_peers:d}'


def ftime(secs):
Expand All @@ -568,17 +567,17 @@ def ftime(secs):
if secs <= 0:
time_str = ''
elif secs < 60:
time_str = '{}s'.format(secs)
time_str = f'{secs}s'
elif secs < 3600:
time_str = '{}m {}s'.format(secs // 60, secs % 60)
time_str = f'{secs // 60}m {secs % 60}s'
elif secs < 86400:
time_str = '{}h {}m'.format(secs // 3600, secs // 60 % 60)
time_str = f'{secs // 3600}h {secs // 60 % 60}m'
elif secs < 604800:
time_str = '{}d {}h'.format(secs // 86400, secs // 3600 % 24)
time_str = f'{secs // 86400}d {secs // 3600 % 24}h'
elif secs < 31449600:
time_str = '{}w {}d'.format(secs // 604800, secs // 86400 % 7)
time_str = f'{secs // 604800}w {secs // 86400 % 7}d'
else:
time_str = '{}y {}w'.format(secs // 31449600, secs // 604800 % 52)
time_str = f'{secs // 31449600}y {secs // 604800 % 52}w'

return time_str

Expand Down Expand Up @@ -934,7 +933,7 @@ def is_ipv4(ip):
return socket.inet_aton(ip)
else:
return socket.inet_pton(socket.AF_INET, ip)
except socket.error:
except OSError:
return False


Expand All @@ -960,7 +959,7 @@ def is_ipv6(ip):

try:
return socket.inet_pton(socket.AF_INET6, ip)
except (socket.error, AttributeError):
except (OSError, AttributeError):
if windows_check():
log.warning('Unable to verify IPv6 Address on Windows.')
return True
Expand Down Expand Up @@ -1048,7 +1047,7 @@ def utf8_encode_structure(data):


@functools.total_ordering
class VersionSplit(object):
class VersionSplit:
"""
Used for comparing version numbers.
Expand Down Expand Up @@ -1246,7 +1245,7 @@ def set_env_variable(name, value):
)

# Update the copy maintained by msvcrt (used by gtk+ runtime)
result = cdll.msvcrt._wputenv('%s=%s' % (name, value))
result = cdll.msvcrt._wputenv(f'{name}={value}')
if result != 0:
log.info("Failed to set Env Var '%s' (msvcrt._putenv)", name)
else:
Expand Down
11 changes: 5 additions & 6 deletions deluge/component.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2010 Andrew Resch <andrewresch@gmail.com>
#
Expand All @@ -24,13 +23,13 @@ class ComponentAlreadyRegistered(Exception):

class ComponentException(Exception):
def __init__(self, message, tb):
super(ComponentException, self).__init__(message)
super().__init__(message)
self.message = message
self.tb = tb

def __str__(self):
s = super(ComponentException, self).__str__()
return '%s\n%s' % (s, ''.join(self.tb))
s = super().__str__()
return '{}\n{}'.format(s, ''.join(self.tb))

def __eq__(self, other):
if isinstance(other, self.__class__):
Expand All @@ -42,7 +41,7 @@ def __ne__(self, other):
return not self.__eq__(other)


class Component(object):
class Component:
"""Component objects are singletons managed by the :class:`ComponentRegistry`.
When a new Component object is instantiated, it will be automatically
Expand Down Expand Up @@ -247,7 +246,7 @@ def shutdown(self):
pass


class ComponentRegistry(object):
class ComponentRegistry:
"""The ComponentRegistry holds a list of currently registered :class:`Component` objects.
It is used to manage the Components by starting, stopping, pausing and shutting them down.
Expand Down
18 changes: 8 additions & 10 deletions deluge/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 Andrew Resch <andrewresch@gmail.com>
#
Expand Down Expand Up @@ -45,7 +44,6 @@
import pickle
import shutil
from codecs import getwriter
from io import open
from tempfile import NamedTemporaryFile

from deluge.common import JSON_FORMAT, get_default_config_dir
Expand Down Expand Up @@ -102,7 +100,7 @@ def find_json_objects(text, decoder=json.JSONDecoder()):
return objects


class Config(object):
class Config:
"""This class is used to access/create/modify config files.
Args:
Expand Down Expand Up @@ -396,9 +394,9 @@ def load(self, filename=None):
filename = self.__config_file

try:
with open(filename, 'r', encoding='utf8') as _file:
with open(filename, encoding='utf8') as _file:
data = _file.read()
except IOError as ex:
except OSError as ex:
log.warning('Unable to open config file %s: %s', filename, ex)
return

Expand Down Expand Up @@ -451,7 +449,7 @@ def save(self, filename=None):
# Check to see if the current config differs from the one on disk
# We will only write a new config file if there is a difference
try:
with open(filename, 'r', encoding='utf8') as _file:
with open(filename, encoding='utf8') as _file:
data = _file.read()
objects = find_json_objects(data)
start, end = objects[0]
Expand All @@ -463,7 +461,7 @@ def save(self, filename=None):
if self._save_timer and self._save_timer.active():
self._save_timer.cancel()
return True
except (IOError, IndexError) as ex:
except (OSError, IndexError) as ex:
log.warning('Unable to open config file: %s because: %s', filename, ex)

# Save the new config and make sure it's written to disk
Expand All @@ -477,7 +475,7 @@ def save(self, filename=None):
json.dump(self.__config, getwriter('utf8')(_file), **JSON_FORMAT)
_file.flush()
os.fsync(_file.fileno())
except IOError as ex:
except OSError as ex:
log.error('Error writing new config file: %s', ex)
return False

Expand All @@ -488,15 +486,15 @@ def save(self, filename=None):
try:
log.debug('Backing up old config file to %s.bak', filename)
shutil.move(filename, filename + '.bak')
except IOError as ex:
except OSError as ex:
log.warning('Unable to backup old config: %s', ex)

# The new config file has been written successfully, so let's move it over
# the existing one.
try:
log.debug('Moving new config file %s to %s', filename_tmp, filename)
shutil.move(filename_tmp, filename)
except IOError as ex:
except OSError as ex:
log.error('Error moving new config file: %s', ex)
return False
else:
Expand Down
3 changes: 1 addition & 2 deletions deluge/configmanager.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Andrew Resch <andrewresch@gmail.com>
#
Expand All @@ -17,7 +16,7 @@
log = logging.getLogger(__name__)


class _ConfigManager(object):
class _ConfigManager:
def __init__(self):
log.debug('ConfigManager started..')
self.config_files = {}
Expand Down
1 change: 0 additions & 1 deletion deluge/core/alertmanager.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com>
#
Expand Down
20 changes: 9 additions & 11 deletions deluge/core/authmanager.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com>
# Copyright (C) 2011 Pedro Algarvio <pedro@algarvio.me>
Expand All @@ -11,7 +10,6 @@
import logging
import os
import shutil
from io import open

import deluge.component as component
import deluge.configmanager as configmanager
Expand All @@ -37,7 +35,7 @@
AUTH_LEVELS_MAPPING_REVERSE = {v: k for k, v in AUTH_LEVELS_MAPPING.items()}


class Account(object):
class Account:
__slots__ = ('username', 'password', 'authlevel')

def __init__(self, username, password, authlevel):
Expand All @@ -54,10 +52,10 @@ def data(self):
}

def __repr__(self):
return '<Account username="%(username)s" authlevel=%(authlevel)s>' % {
'username': self.username,
'authlevel': self.authlevel,
}
return '<Account username="{username}" authlevel={authlevel}>'.format(
username=self.username,
authlevel=self.authlevel,
)


class AuthManager(component.Component):
Expand Down Expand Up @@ -182,7 +180,7 @@ def write_auth_file(self):
if os.path.isfile(filepath):
log.debug('Creating backup of %s at: %s', filename, filepath_bak)
shutil.copy2(filepath, filepath_bak)
except IOError as ex:
except OSError as ex:
log.error('Unable to backup %s to %s: %s', filepath, filepath_bak, ex)
else:
log.info('Saving the %s at: %s', filename, filepath)
Expand All @@ -196,7 +194,7 @@ def write_auth_file(self):
_file.flush()
os.fsync(_file.fileno())
shutil.move(filepath_tmp, filepath)
except IOError as ex:
except OSError as ex:
log.error('Unable to save %s: %s', filename, ex)
if os.path.isfile(filepath_bak):
log.info('Restoring backup of %s from: %s', filename, filepath_bak)
Expand Down Expand Up @@ -225,9 +223,9 @@ def __load_auth_file(self):
for _filepath in (auth_file, auth_file_bak):
log.info('Opening %s for load: %s', filename, _filepath)
try:
with open(_filepath, 'r', encoding='utf8') as _file:
with open(_filepath, encoding='utf8') as _file:
file_data = _file.readlines()
except IOError as ex:
except OSError as ex:
log.warning('Unable to load %s: %s', _filepath, ex)
file_data = []
else:
Expand Down
Loading

0 comments on commit ec0bcc1

Please sign in to comment.