Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[POC] all: fix deepsource checks #2016

Closed
wants to merge 19 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
fbd2135
Add .deepsource.toml
deepsourcebot Jan 15, 2021
b40a653
Refactor unnecessary `else` / `elif` when `if` block has a `raise` st…
deepsource-autofix[bot] Jan 15, 2021
7daa247
Refactor unnecessary `else` / `elif` when `if` block has a `return` s…
deepsource-autofix[bot] Jan 15, 2021
86bda22
Merge pull request #1 from RhinosF1/deepsource-fix-6a0bf49d
RhinosF1 Jan 15, 2021
1dde5b0
Merge pull request #2 from RhinosF1/deepsource-fix-4fdbef4a
RhinosF1 Jan 15, 2021
b1dfb42
Refactor unnecessary `else` / `elif` when `if` block has a `break` st…
deepsource-autofix[bot] Jan 15, 2021
e19ac02
Replace ternary syntax with if expression
deepsource-autofix[bot] Jan 15, 2021
b18acf0
Remove methods with unnecessary super delegation.
deepsource-autofix[bot] Jan 15, 2021
8bc0f24
Refactor the comparison involving `not`
deepsource-autofix[bot] Jan 15, 2021
f2dcfda
Remove unnecessary lambda expression
deepsource-autofix[bot] Jan 15, 2021
c6477f3
Remove unused imports
deepsource-autofix[bot] Jan 15, 2021
4fca0be
Merge pull request #3 from RhinosF1/deepsource-fix-828d5612
RhinosF1 Jan 15, 2021
c54b50d
Merge pull request #5 from RhinosF1/deepsource-fix-9b1a9776
RhinosF1 Jan 15, 2021
31ec426
Merge pull request #6 from RhinosF1/deepsource-fix-c5c5d48c
RhinosF1 Jan 15, 2021
e02bb6b
Merge pull request #7 from RhinosF1/deepsource-fix-3e23912f
RhinosF1 Jan 15, 2021
9fd3c00
Merge pull request #8 from RhinosF1/deepsource-fix-e04ae119
RhinosF1 Jan 15, 2021
2f01eb3
Merge pull request #9 from RhinosF1/deepsource-fix-40ef8951
RhinosF1 Jan 15, 2021
c49921c
Use literal syntax instead of function calls to create data structure
deepsource-autofix[bot] Jan 15, 2021
3da901d
Merge pull request #12 from RhinosF1/deepsource-fix-c5708ba2
RhinosF1 Jan 15, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .deepsource.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
version = 1

test_patterns = ["test/**"]

[[analyzers]]
name = "python"
enabled = true

[analyzers.meta]
runtime_version = "3.x.x"
2 changes: 1 addition & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys, os
import os
parentdir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.sys.path.insert(0,parentdir)
from sopel import __version__
Expand Down
13 changes: 6 additions & 7 deletions sopel/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def __init__(self, config, daemon=False):
For servers that do not support IRCv3, this will be an empty set.
"""

self.privileges = dict()
self.privileges = {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't mind enforcing this kind of style.

"""A dictionary of channels to their users and privilege levels.

The value associated with each channel is a dictionary of
Expand Down Expand Up @@ -684,7 +684,7 @@ def call_rule(self, rule, sopel, trigger):

if '*' in disabled_plugins:
return
elif rule.get_plugin_name() in disabled_plugins:
if rule.get_plugin_name() in disabled_plugins:
return
Comment on lines 685 to 688
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This, on the other hand, is silly. If the tool isn't smart enough to recommend merging the two conditions into one (as below), it shouldn't flag anything. Just using elif shouldn't be a style error, and there are numerous places in this PR where it's changed to plain if for no reason.

if (
    '*' in disabled_plugins
    or rule.get_plugin_name() in disabled_plugins
):
    return


# disable chosen methods from plugins
Expand Down Expand Up @@ -714,11 +714,11 @@ def call(self, func, sopel, trigger):
nick = trigger.nick
current_time = time.time()
if nick not in self._times:
self._times[nick] = dict()
self._times[nick] = {}
if self.nick not in self._times:
self._times[self.nick] = dict()
self._times[self.nick] = {}
if not trigger.is_privmsg and trigger.sender not in self._times:
self._times[trigger.sender] = dict()
self._times[trigger.sender] = {}

if not trigger.admin and not func.unblockable:
if func in self._times[nick]:
Expand Down Expand Up @@ -1280,8 +1280,7 @@ def kick(self, nick, channel=None, message=None):
if channel is None:
if self._trigger.is_privmsg:
raise RuntimeError('Error: KICK requires a channel.')
else:
channel = self._trigger.sender
channel = self._trigger.sender
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This kind of thing is good.

if nick is None:
raise RuntimeError('Error: KICK requires a nick.')
self._bot.kick(nick, channel, message)
6 changes: 3 additions & 3 deletions sopel/cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def handle_init(options):
if ext and ext != '.cfg':
tools.stderr('Configuration wizard accepts .cfg files only')
return 1
elif not ext:
if not ext:
config_filename = config_name + '.cfg'

if os.path.isfile(config_filename):
Expand Down Expand Up @@ -180,7 +180,7 @@ def main():
# init command does not require existing settings
if action == 'list':
return handle_list(options)
elif action == 'init':
if action == 'init':
return handle_init(options)
elif action == 'get':
if action == 'get':
return handle_get(options)
8 changes: 4 additions & 4 deletions sopel/cli/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,11 +538,11 @@ def main():

if action == 'list':
return handle_list(options)
elif action == 'show':
if action == 'show':
return handle_show(options)
elif action == 'configure':
if action == 'configure':
return handle_configure(options)
elif action == 'disable':
if action == 'disable':
return handle_disable(options)
elif action == 'enable':
if action == 'enable':
return handle_enable(options)
8 changes: 4 additions & 4 deletions sopel/cli/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -572,7 +572,7 @@ def command_legacy(opts):
if opts.version:
print_version()
return
elif opts.version_legacy:
if opts.version_legacy:
tools.stderr(
'WARNING: option -v is deprecated; '
'use `sopel -V/--version` instead')
Expand Down Expand Up @@ -625,14 +625,14 @@ def command_legacy(opts):
tools.stderr(
'Try using either the `sopel stop` command or the `sopel restart` command')
return ERR_CODE
elif opts.kill:
if opts.kill:
tools.stderr(
'WARNING: option -k/--kill is deprecated; '
'use `sopel stop --kill` instead')
tools.stderr('Killing the Sopel')
os.kill(old_pid, signal.SIGKILL)
return
elif opts.quit:
if opts.quit:
tools.stderr(
'WARNING: options -q/--quit is deprecated; '
'use `sopel stop` instead')
Expand All @@ -644,7 +644,7 @@ def command_legacy(opts):
# https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/signal
os.kill(old_pid, signal.SIGTERM)
return
elif opts.restart:
if opts.restart:
tools.stderr(
'WARNING: options --restart is deprecated; '
'use `sopel restart` instead')
Expand Down
10 changes: 4 additions & 6 deletions sopel/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,7 @@ def homedir(self):
configured = self.parser.get('core', 'homedir')
if configured:
return configured
else:
return os.path.dirname(self.filename)
return os.path.dirname(self.filename)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But this kind of thing is also good.


def get_defined_sections(self):
"""Retrieve all defined static sections of this configuration.
Expand Down Expand Up @@ -276,7 +275,7 @@ def define_section(self, name, cls_, validate=True):
current_name = str(current.__class__)
new_name = str(cls_)
if (current is not None and not isinstance(current, self.ConfigSection) and
not current_name == new_name):
current_name != new_name):
Comment on lines -279 to +278
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is good, too.

raise ValueError(
"Can not re-define class for section from {} to {}.".format(
current_name, new_name)
Expand Down Expand Up @@ -345,9 +344,8 @@ def __getattr__(self, name):
section = self.ConfigSection(name, items, self) # Return a section
setattr(self, name, section)
return section
else:
raise AttributeError("%r object has no attribute %r"
% (type(self).__name__, name))
raise AttributeError("%r object has no attribute %r"
% (type(self).__name__, name))

def __getitem__(self, name):
return self.__getattr__(name)
Expand Down
8 changes: 3 additions & 5 deletions sopel/config/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ def serialize(self, value):
"""
if not isinstance(value, (list, set)):
raise ValueError('ListAttribute value must be a list.')
elif not value:
if not value:
# return an empty string when there is no value
return ''

Expand Down Expand Up @@ -553,8 +553,7 @@ def parse(self, value):
"""
if value in self.choices:
return value
else:
raise ValueError('Value must be in {}'.format(self.choices))
raise ValueError('Value must be in {}'.format(self.choices))

def serialize(self, value):
"""Make sure ``value`` is valid and safe to write in the config file.
Expand All @@ -566,8 +565,7 @@ def serialize(self, value):
"""
if value in self.choices:
return value
else:
raise ValueError('Value must be in {}'.format(self.choices))
raise ValueError('Value must be in {}'.format(self.choices))


class FilenameAttribute(BaseValidated):
Expand Down
8 changes: 4 additions & 4 deletions sopel/coretasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ def startup(bot, trigger):
modes = '+' + modes
bot.write(('MODE', bot.nick, modes))

bot.memory['retry_join'] = dict()
bot.memory['retry_join'] = {}

channels = bot.config.core.channels
if not channels:
Expand Down Expand Up @@ -330,7 +330,7 @@ def handle_names(bot, trigger):
return
channel = Identifier(channels.group(1))
if channel not in bot.privileges:
bot.privileges[channel] = dict()
bot.privileges[channel] = {}
if channel not in bot.channels:
bot.channels[channel] = target.Channel(channel)

Expand Down Expand Up @@ -592,7 +592,7 @@ def track_join(bot, trigger):
# is it a new channel?
if channel not in bot.channels:
LOGGER.info('Channel joined: %s', channel)
bot.privileges[channel] = dict()
bot.privileges[channel] = {}
bot.channels[channel] = target.Channel(channel)

# did *we* just join?
Expand Down Expand Up @@ -1068,7 +1068,7 @@ def _record_who(bot, channel, user, host, nick, account=None, away=None, modes=N
bot.channels[channel] = target.Channel(channel)
bot.channels[channel].add_user(usr, privs=priv)
if channel not in bot.privileges:
bot.privileges[channel] = dict()
bot.privileges[channel] = {}
bot.privileges[channel][nick] = priv


Expand Down
3 changes: 1 addition & 2 deletions sopel/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -858,8 +858,7 @@ def get_nick_or_channel_value(self, name, key, default=None):
name = Identifier(name)
if name.is_nick():
return self.get_nick_value(name, key, default)
else:
return self.get_channel_value(name, key, default)
return self.get_channel_value(name, key, default)

def get_preferred_value(self, names, key):
"""Get a value for the first name which has it set.
Expand Down
5 changes: 2 additions & 3 deletions sopel/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,10 +221,9 @@ def _get_hex_color(color):

if len(color) == 3:
return ''.join([c * 2 for c in color])
elif len(color) == 6:
if len(color) == 6:
return color
else: # invalid length
raise ValueError('Hexadecimal color value must have either 3 or 6 digits.')
raise ValueError('Hexadecimal color value must have either 3 or 6 digits.')


def hex_color(text, fg=None, bg=None):
Expand Down
2 changes: 1 addition & 1 deletion sopel/irc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def __init__(self, settings):
"""Bot settings."""
self.enabled_capabilities = set()
"""A set containing the IRCv3 capabilities that the bot has enabled."""
self._cap_reqs = dict()
self._cap_reqs = {}
"""A dictionary of capability names to a list of requests."""

# internal machinery
Expand Down
5 changes: 2 additions & 3 deletions sopel/irc/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,8 +315,7 @@ def recv(self, buffer_size):
asyncore.ESHUTDOWN):
self.handle_close()
return ''
elif why[0] == errno.ENOENT:
if why[0] == errno.ENOENT:
# Required in order to keep it non-blocking
return b''
else:
raise
raise
2 changes: 1 addition & 1 deletion sopel/modules/choose.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def _format_safe(text):
"""
if not isinstance(text, str):
raise TypeError("A string is required.")
elif not text:
if not text:
# unnecessary optimization
return ''

Expand Down
2 changes: 0 additions & 2 deletions sopel/modules/currency.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,6 @@ def __init__(self, status):

class UnsupportedCurrencyError(Exception):
"""A currency is currently not supported by the API"""
def __init__(self, currency):
super(UnsupportedCurrencyError, self).__init__(currency)


def build_reply(amount, base, target, out_string):
Expand Down
14 changes: 6 additions & 8 deletions sopel/modules/dice.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,13 @@ def drop_lowest(self, n):
count = self.dice[i]
if n == 0:
break
elif n < count:
if n < count:
self.dice[i] = count - n
self.dropped[i] = n
break
else:
self.dice[i] = 0
self.dropped[i] = count
n = n - count
self.dice[i] = 0
self.dropped[i] = count
n = n - count

for i, count in self.dropped.items():
if self.dice[i] == 0:
Expand Down Expand Up @@ -215,10 +214,9 @@ def _get_eval_str(dice):
def _get_pretty_str(dice):
if dice.num <= 10:
return dice.get_simple_string()
elif dice.get_number_of_faces() <= 10:
if dice.get_number_of_faces() <= 10:
return dice.get_compressed_string()
else:
return "(...)"
return "(...)"

eval_str = arg_str % (tuple(map(_get_eval_str, dice)))
pretty_str = arg_str % (tuple(map(_get_pretty_str, dice)))
Expand Down
4 changes: 2 additions & 2 deletions sopel/modules/find.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def collectlines(bot, trigger):
if line.startswith("s/"): # Don't remember substitutions
return
# store messages in reverse order (most recent first)
elif line.startswith("\x01ACTION"): # For /me messages
if line.startswith("\x01ACTION"): # For /me messages
line = line[:-1]
line_list.appendleft(line)
else:
Expand Down Expand Up @@ -180,7 +180,7 @@ def repl(s):
return # Didn't find anything

# Save the new "edited" message.
action = (me and '\x01ACTION ') or '' # If /me message, prepend \x01ACTION
action = '\x01ACTION ' if me else '' # If /me message, prepend \x01ACTION
history.appendleft(action + new_phrase) # history is in most-recent-first order

# output
Expand Down
10 changes: 4 additions & 6 deletions sopel/modules/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,8 @@ def post_to_clbin(msg):
# find/replace just in case the site tries to be sneaky and save on SSL overhead,
# though it will probably send us an HTTPS link without any tricks.
return result.replace('http://', 'https://', 1)
else:
LOGGER.error("Invalid result %s", result)
raise PostingException('clbin result did not contain expected URL base.')
LOGGER.error("Invalid result %s", result)
raise PostingException('clbin result did not contain expected URL base.')


def post_to_0x0(msg):
Expand All @@ -94,9 +93,8 @@ def post_to_0x0(msg):
# find/replace just in case the site tries to be sneaky and save on SSL overhead,
# though it will probably send us an HTTPS link without any tricks.
return result.replace('http://', 'https://', 1)
else:
LOGGER.error('Invalid result %s', result)
raise PostingException('0x0.st result did not contain expected URL base.')
LOGGER.error('Invalid result %s', result)
raise PostingException('0x0.st result did not contain expected URL base.')


def post_to_hastebin(msg):
Expand Down
12 changes: 5 additions & 7 deletions sopel/modules/ip.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,17 +81,16 @@ def _find_geoip_db(bot):
ipasnum_db = os.path.join(config.ip.GeoIP_db_path, 'GeoLite2-ASN.mmdb')
if (os.path.isfile(cities_db) and os.path.isfile(ipasnum_db)):
return config.ip.GeoIP_db_path
else:
LOGGER.warning(
'GeoIP path configured but DB not found in configured path')
LOGGER.warning(
'GeoIP path configured but DB not found in configured path')

if (os.path.isfile(os.path.join(config.core.homedir, 'GeoLite2-City.mmdb')) and
os.path.isfile(os.path.join(config.core.homedir, 'GeoLite2-ASN.mmdb'))):
return config.core.homedir
elif (os.path.isfile(os.path.join('/usr/share/GeoIP', 'GeoLite2-City.mmdb')) and
if (os.path.isfile(os.path.join('/usr/share/GeoIP', 'GeoLite2-City.mmdb')) and
os.path.isfile(os.path.join('/usr/share/GeoIP', 'GeoLite2-ASN.mmdb'))):
return '/usr/share/GeoIP'
elif urlretrieve:
if urlretrieve:
LOGGER.info('Downloading GeoIP database')
bot.say('Downloading GeoIP database, please wait...')

Expand All @@ -113,8 +112,7 @@ def _find_geoip_db(bot):
urlretrieve(url, full_path)
_decompress(full_path, config.core.homedir)
return bot.config.core.homedir
else:
return False
return False


@plugin.command('iplookup', 'ip')
Expand Down
Loading