From 37f8843f5fecc9bb4a5eb5b18eea35b1bbc16489 Mon Sep 17 00:00:00 2001
From: Simeon Simeonov
Date: Fri, 5 Jul 2024 22:55:03 +0200
Subject: Add more fixes and linting
---
.ruff.toml | 109 ++++++++++++++++++++++++++++++++++++++++++++
Changelog | 4 ++
README.md | 8 ++--
beinc_generic_client.py | 41 ++++++++---------
beinc_pull.py | 42 ++++++++---------
beinc_server.py | 118 ++++++++++++++++++++++--------------------------
beinc_weechat.py | 66 +++++++++++++--------------
7 files changed, 237 insertions(+), 151 deletions(-)
create mode 100644 .ruff.toml
diff --git a/.ruff.toml b/.ruff.toml
new file mode 100644
index 0000000..1037228
--- /dev/null
+++ b/.ruff.toml
@@ -0,0 +1,109 @@
+cache-dir = "~/.cache/ruff"
+indent-width = 4
+line-length = 79
+target-version = "py39"
+
+[lint]
+select = ["ALL", "D101", "D102", "D103", "D104"]
+ignore = [
+ "ANN",
+ "BLE001",
+ "COM812",
+ "D",
+ "EM101", # Exception must not use a string literal, assign to variable first
+ "EM102", # Exception must not use an f-string literal, assign to variable first
+ "ERA001",
+ "FBT001",
+ "FBT002",
+ "INP001",
+ "ISC001",
+ "N802",
+ "N806",
+ "PLR2004",
+ "PTH111",
+ "RUF012",
+ "RUF013",
+ "S101",
+ "T201",
+ "TRY003",
+ "TRY300",
+ "UP020"
+]
+
+# D101 - Missing docstring in public class
+# D102 - Missing docstring in public method
+# D200 - One-line docstring should fit on one line
+# D203 - 1 blank line required before class docstring
+# D205 - 1 blank line required between summary line and description
+# D403 - First word of the first line should be capitalized: `str` -> `Str`
+# FBT001 - Boolean-typed positional argument in function definition
+# FBT002 - Boolean default positional argument in function definition
+# INP001 - File `beinc_weechat.py` is part of an implicit namespace package. Add an `__init__.py`
+# N802 - Function name `do_GET` should be lowercase
+# N806 - Variable `POST_data` in function should be lowercase
+# PTH111 - `os.path.expanduser()` should be replaced by `Path.expanduser()`
+# PLR2004 - Magic value used in comparison, consider replacing `200` with a constant variable
+# RUF012 - Mutable class attributes should be annotated with `typing.ClassVar`
+# RUF013 - PEP 484 prohibits implicit `Optional`
+# S101 - Use of `assert` detected
+# T201 - `print` found
+# TRY003 - Avoid specifying long messages outside the exception class
+# TRY300 - Consider moving this statement to an `else` block
+# UP020 - Use builtin `open`
+
+# Allow fix for all enabled rules (when `--fix`) is provided.
+fixable = ["ALL"]
+unfixable = []
+
+# custom settings
+[lint.per-file-ignores]
+"beinc_generic_client.py" = [
+ "S310" # Audit URL open for permitted schemes. Allowing use of `file:` or custom schemes is often unexpected
+]
+"beinc_pull.py" = [
+ "S310", # Audit URL open for permitted schemes. Allowing use of `file:` or custom schemes is often unexpected
+ "TRY002", # Create your own exception
+ "TRY301" # Abstract `raise` to an inner function
+]
+"beinc_weechat.py" = [
+ "ARG001", # Unused function argument: `data`
+ "C901", # `beinc_cmd_target_handler` is too complex (13 > 10)
+ "DTZ005", # `datetime.datetime.now()` called without a `tz` argument
+ "PLR0912", # Too many branches (16 > 12)
+ "PLW0603", # Using the global statement to update `global_values` is discouraged
+ "PTH118", # `os.path.join()` should be replaced by `Path` with `/` operator
+ "S310", # Audit URL open for permitted schemes. Allowing use of `file:` or custom schemes is often unexpected
+ "TRY002", # Create your own exception
+ "TRY301" # Abstract `raise` to an inner function
+]
+
+
+[format]
+# Like Black, use double quotes for strings.
+quote-style = "single"
+
+# Like Black, indent with spaces, rather than tabs.
+indent-style = "space"
+
+# Like Black, respect magic trailing commas.
+skip-magic-trailing-comma = true
+
+# Like Black, automatically detect the appropriate line ending.
+line-ending = "auto"
+
+# Enable auto-formatting of code examples in docstrings. Markdown,
+# reStructuredText code/literal blocks and doctests are all supported.
+#
+# This is currently disabled by default, but it is planned for this
+# to be opt-out in the future.
+docstring-code-format = false
+
+# Set the line length limit used when formatting code snippets in
+# docstrings.
+#
+# This only has an effect when the `docstring-code-format` setting is
+# enabled.
+docstring-code-line-length = "dynamic"
+
+[lint.flake8-quotes]
+inline-quotes = "single"
diff --git a/Changelog b/Changelog
index 6692d08..a7f8b6b 100644
--- a/Changelog
+++ b/Changelog
@@ -1,3 +1,7 @@
+v4.4:
+ - replace the functionality from the deprecated cgi module
+ - do some more format / linting (add .ruff.toml)
+
v4.3:
- remove obsolete SSL/TLS code
- use black alike coding style
diff --git a/README.md b/README.md
index 1994c15..f7a446c 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-Copyright (C) 2014-2022 - Simeon Simeonov
+Copyright (C) 2014-2024 - Simeon Simeonov
See the end of the file for license conditions.
@@ -90,13 +90,11 @@ your URL will be: https://hostname:port
## Supported systems & requirements
Any system running the software required for the selected components.
-All components tested on: Gentoo GNU/Linux,
- Ubuntu GNU/Linux 18.4,
- FreeBSD 12.x
+All components tested on: Gentoo GNU/Linux, FreeBSD (12.x, 13.x)
### Requirements
-All components: Python >= 3.6.*
+All components: Python >= 3.9.*
beinc_server.py: pynotify >= 0.1 (optional)
beinc_weechat.py: Weechat >= 0.4.0
diff --git a/beinc_generic_client.py b/beinc_generic_client.py
index 476287e..44e8698 100755
--- a/beinc_generic_client.py
+++ b/beinc_generic_client.py
@@ -1,8 +1,7 @@
#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-# Blackmore's Enhanced IRC-Notification Collection (BEINC) v4.3
-# Copyright (C) 2013-2022 Simeon Simeonov
+# Blackmore's Enhanced IRC-Notification Collection (BEINC)
+# Copyright (C) 2013-2024 Simeon Simeonov
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -17,12 +16,14 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
"""A generic BEINC client that can be used for testing or as a template"""
+
import argparse
import errno
import getpass
import io
import json
import os
+import pathlib
import socket
import ssl
import sys
@@ -30,7 +31,7 @@ import urllib.parse
import urllib.request
__author__ = 'Simeon Simeonov'
-__version__ = '4.3'
+__version__ = '4.4'
__license__ = 'GPL3'
@@ -55,14 +56,14 @@ def fetch_password(args_password):
except KeyboardInterrupt:
eprint(os.linesep + 'Prompt terminated')
sys.exit(errno.EACCES)
- elif os.path.isfile(args_password):
+ elif pathlib.Path(args_password).is_file():
try:
with io.open(args_password, 'r', encoding='utf-8') as fp:
passwd = fp.readline()
if passwd.strip():
return passwd.strip()
- except Exception as e:
- eprint(f'Unable to open password file: {e}')
+ except Exception as exp:
+ eprint(f'Unable to open password file: {exp}')
sys.exit(1)
return args_password
@@ -83,17 +84,14 @@ def pull_notifications(ssl_context, args):
response = urllib.request.urlopen(
args.url,
data=urllib.parse.urlencode(
- (
- ('resource_name', args.rname),
- ('password', args.password),
- )
+ (('resource_name', args.rname), ('password', args.password))
).encode('utf-8'),
timeout=args.socket_timeout,
context=ssl_context,
)
response_dict = json.loads(response.read().decode('utf-8'))
if response.code != 200:
- raise socket.error(response_dict.get('message', ''))
+ raise OSError(response_dict.get('message', ''))
return response_dict['data']['messages']
@@ -122,7 +120,7 @@ def push_notification(ssl_context, args):
)
response_dict = json.loads(response.read().decode('utf-8'))
if response.code != 200:
- raise socket.error(response_dict.get('message', ''))
+ raise OSError(response_dict.get('message', ''))
def main(inargs=None):
@@ -131,10 +129,7 @@ def main(inargs=None):
description='The following options are available'
)
parser.add_argument(
- 'url',
- metavar='URL',
- type=str,
- help='BEINC server destination URL',
+ 'url', metavar='URL', type=str, help='BEINC server destination URL'
)
parser.add_argument(
'-c',
@@ -242,14 +237,14 @@ def main(inargs=None):
push_notification(context, args)
print('OK')
sys.exit(0)
- except ssl.SSLError as e:
- eprint(f'BEINC SSL/TLS error: {e}')
+ except ssl.SSLError as err:
+ eprint(f'BEINC SSL/TLS error: {err}')
sys.exit(errno.EPERM)
- except socket.error as e:
- eprint(f'BEINC connection error: {e}')
+ except OSError as err:
+ eprint(f'BEINC connection error: {err}')
sys.exit(errno.EPERM)
- except Exception as e:
- eprint(f'BEINC generic client error: {e}')
+ except Exception as exp:
+ eprint(f'BEINC generic client error: {exp}')
sys.exit(errno.EPERM)
diff --git a/beinc_pull.py b/beinc_pull.py
index 118a08a..6ce9c2f 100755
--- a/beinc_pull.py
+++ b/beinc_pull.py
@@ -1,8 +1,7 @@
#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-# Blackmore's Enhanced IRC-Notification Collection (BEINC) v4.3
-# Copyright (C) 2013-2022 Simeon Simeonov
+# Blackmore's Enhanced IRC-Notification Collection (BEINC)
+# Copyright (C) 2013-2024 Simeon Simeonov
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -17,14 +16,15 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
"""A simple client that pulls notifications from a BEINC server"""
+
import argparse
import errno
import getpass
import io
import json
import os
+import pathlib
import sched
-import socket
import ssl
import sys
import time
@@ -38,7 +38,7 @@ except ImportError:
__author__ = 'Simeon Simeonov'
-__version__ = '4.3'
+__version__ = '4.4'
__license__ = 'GPL3'
@@ -63,14 +63,14 @@ def fetch_password(args_password):
except KeyboardInterrupt:
eprint(os.linesep + 'Prompt terminated')
sys.exit(errno.EACCES)
- elif os.path.isfile(args_password):
+ elif pathlib.Path(args_password).is_file():
try:
with io.open(args_password, 'r', encoding='utf-8') as fp:
passwd = fp.readline()
if passwd.strip():
return passwd.strip()
- except Exception as e:
- eprint(f'Unable to open password file: {e}')
+ except Exception as exp:
+ eprint(f'Unable to open password file: {exp}')
sys.exit(1)
return args_password
@@ -98,8 +98,7 @@ def display_notification(args, title, message):
if not pynotify.init('BEINC Notify'):
raise Exception('There was a problem with libnotify')
notification_obj = pynotify.Notification(
- summary=title,
- message=message,
+ summary=title, message=message
)
notification_obj.timeout = 1000 * args.osd_timeout
notification_obj.set_category('im.received')
@@ -139,25 +138,23 @@ def pull_notifications(scheduler, args):
)
response_dict = json.loads(response.read().decode('utf-8'))
if response.code != 200:
- raise socket.error(response_dict.get('message', ''))
+ raise OSError(response_dict.get('message', ''))
for entry in response_dict['data']['messages']:
display_notification(
- args,
- entry.get('title', ''),
- entry.get('message', ''),
+ args, entry.get('title', ''), entry.get('message', '')
)
response.close()
scheduler.enter(
args.frequency, 1, pull_notifications, (scheduler, args)
)
- except ssl.SSLError as e:
- eprint(f'BEINC SSL/TLS error: {e}')
+ except ssl.SSLError as err:
+ eprint(f'BEINC SSL/TLS error: {err}')
sys.exit(errno.EPERM)
- except socket.error as e:
- eprint(f'BEINC connection error: {e}')
+ except OSError as err:
+ eprint(f'BEINC connection error: {err}')
sys.exit(errno.EPERM)
- except Exception as e:
- eprint(f'BEINC generic client error: {e}')
+ except Exception as exp:
+ eprint(f'BEINC generic client error: {exp}')
sys.exit(errno.EPERM)
@@ -167,10 +164,7 @@ def main(inargs=None):
description='The following options are available'
)
parser.add_argument(
- 'url',
- metavar='URL',
- type=str,
- help='BEINC server destination URL',
+ 'url', metavar='URL', type=str, help='BEINC server destination URL'
)
parser.add_argument(
'-c',
diff --git a/beinc_server.py b/beinc_server.py
index 0098fba..647d7f1 100755
--- a/beinc_server.py
+++ b/beinc_server.py
@@ -1,8 +1,7 @@
#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-# Blackmore's Enhanced IRC-Notification Collection (BEINC) v4.3
-# Copyright (C) 2013-2023 Simeon Simeonov
+# Blackmore's Enhanced IRC-Notification Collection (BEINC)
+# Copyright (C) 2013-2024 Simeon Simeonov
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -16,14 +15,16 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
-
+"""BEINC standalone server implementation"""
import argparse
+import contextlib
import errno
import io
import json
import logging
import os
+import pathlib
import ssl
import sys
import urllib.parse
@@ -38,7 +39,7 @@ except ImportError:
__author__ = 'Simeon Simeonov'
-__version__ = '4.3'
+__version__ = '4.4'
__license__ = 'GPL3'
@@ -48,24 +49,24 @@ BEINC_OSD_TYPE_PYNOTIFY = 1
BEINC_CURRENT_CONFIG_VERSION = 3
-class BEINCError400(Exception):
- """BEINCError400"""
+class BEINC400Error(Exception):
+ """BEINC400Error"""
-class BEINCError401(Exception):
- """BEINCError401"""
+class BEINC401Error(Exception):
+ """BEINC401Error"""
-class BEINCError403(Exception):
- """BEINCError403"""
+class BEINC403Error(Exception):
+ """BEINC403Error"""
-class BEINCError404(Exception):
- """BEINCError404"""
+class BEINC404Error(Exception):
+ """BEINC404Error"""
-class BEINCError405(Exception):
- """BEINCError405"""
+class BEINC405Error(Exception):
+ """BEINC405Error"""
def eprint(*arg, **kwargs):
@@ -79,15 +80,15 @@ def beinc_login_required(method):
@wraps(method)
def wrapper(self, data, *arg, **kwargs):
if data.get('resource_name') is None:
- raise BEINCError403('Resource-name missing')
+ raise BEINC403Error('Resource-name missing')
if data.get('password') is None:
- raise BEINCError401('Password missing')
+ raise BEINC401Error('Password missing')
try:
instance = self.server.instances[data.get('resource_name')]
except Exception:
- raise BEINCError401('Wrong instance or password') from None
+ raise BEINC401Error('Wrong instance or password') from None
if not instance.password_match(data.get('password')):
- raise BEINCError401('Wrong instance or password')
+ raise BEINC401Error('Wrong instance or password')
return method(self, data, *arg, **kwargs)
return wrapper
@@ -124,10 +125,10 @@ class BEINCInstance:
)
self._osd_notification.set_category('im.received')
self._osd_type = BEINC_OSD_TYPE_PYNOTIFY
- except Exception as e:
+ except Exception as exp:
eprint(
f'Unable to set up a pynotify notification object '
- f'for "{self._name}" ({e})'
+ f'for "{self._name}" ({exp})'
)
sys.exit(errno.EPERM)
@@ -217,13 +218,11 @@ class BEINCCustomHandler(BaseHTTPRequestHandler):
if headers is None:
headers = {}
if 'content-length' in headers:
- try:
+ with contextlib.suppress(ValueError):
clen = int(headers['content-length'])
- except ValueError:
- pass
return dict(urllib.parse.parse_qsl(fp.read(clen).decode('utf-8')))
- except Exception as e:
- raise BEINCError400('Invalid POST request') from e
+ except Exception as exp:
+ raise BEINC400Error('Invalid POST request') from exp
def do_POST(self):
"""Handle POST requests"""
@@ -245,18 +244,18 @@ class BEINCCustomHandler(BaseHTTPRequestHandler):
elif self.path.strip('/') == 'beinc/pull':
result = self._handle_pull(POST_data)
self._render_to_JSON_response(result)
- except BEINCError400 as e:
- self._generate_json_error(400, str(e))
- except BEINCError401 as e:
- self._generate_json_error(401, str(e))
- except BEINCError403 as e:
- self._generate_json_error(403, str(e))
- except BEINCError404 as e:
- self._generate_json_error(404, str(e))
- except BEINCError405 as e:
- self._generate_json_error(405, str(e))
- except Exception as e:
- self._generate_json_error(500, f'Unexpected error: {e}')
+ except BEINC400Error as err:
+ self._generate_json_error(400, str(err))
+ except BEINC401Error as err:
+ self._generate_json_error(401, str(err))
+ except BEINC403Error as err:
+ self._generate_json_error(403, str(err))
+ except BEINC404Error as err:
+ self._generate_json_error(404, str(err))
+ except BEINC405Error as err:
+ self._generate_json_error(405, str(err))
+ except Exception as exp:
+ self._generate_json_error(500, f'Unexpected error: {exp}')
def do_GET(self):
"""Handle GET Requests"""
@@ -266,25 +265,19 @@ class BEINCCustomHandler(BaseHTTPRequestHandler):
def _handle_push(self, data):
"""Handle push"""
instance = self.server.instances[data.get('resource_name')]
- try:
- instance.send_message(data.get('title'), data.get('message'))
- return {'message': 'OK. Sent.'}
- except Exception as e:
- self._generate_json_error(500, str(e))
+ instance.send_message(data.get('title'), data.get('message'))
+ return {'message': 'OK. Sent.'}
@beinc_login_required
def _handle_pull(self, data):
"""Handle pull"""
instance = self.server.instances[data.get('resource_name')]
- try:
- if not instance.queueable:
- raise BEINCError405('This instance does not support queuing')
- return {
- 'message': 'OK. Fetched.',
- 'data': {'messages': instance.get_queue()},
- }
- except Exception as e:
- self._generate_json_error(500, str(e))
+ if not instance.queueable:
+ raise BEINC405Error('This instance does not support queuing')
+ return {
+ 'message': 'OK. Fetched.',
+ 'data': {'messages': instance.get_queue()},
+ }
def _generate_json_error(self, code, message):
"""
@@ -349,15 +342,13 @@ class BEINCNotifyServer(HTTPServer):
for instance in self._config['server']['instances']:
self._instances[instance['name']] = BEINCInstance(instance)
logger.info('Instance %s added', instance['name'])
- except Exception as e:
- eprint(f"Unable to create instance \"{instance['name']}\": {e}")
+ except Exception as exp:
+ eprint(f"Unable to create instance \"{instance['name']}\": {exp}")
sys.exit(1)
@property
def instances(self):
- """
- a property that returns the instance list (read-only)
- """
+ """a property that returns the instance list (read-only)"""
return self._instances
@@ -424,11 +415,11 @@ if __name__ == '__main__':
try:
with io.open(args.config_file, 'r', encoding='utf-8') as fp:
config_dict = json.load(fp)
- except Exception as e:
- eprint(f'Unable to parse {args.config_file}: {e}')
+ except Exception as exp:
+ eprint(f'Unable to parse {args.config_file}: {exp}')
sys.exit(errno.EIO)
try:
- if os.path.isfile(args.logger_config):
+ if pathlib.Path(args.logger_config).is_file():
fileConfig(args.logger_config)
logger = logging.getLogger(args.logger_name)
else:
@@ -456,8 +447,7 @@ if __name__ == '__main__':
'ssl_ciphers'
)
beinc_server = BEINCNotifyServer(
- (args.hostname, args.port),
- BEINCCustomHandler,
+ (args.hostname, args.port), BEINCCustomHandler
)
beinc_server.set_config(config_dict)
if ssl_certificate and ssl_private_key:
@@ -474,7 +464,7 @@ if __name__ == '__main__':
beinc_server.serve_forever()
except KeyboardInterrupt:
print('\n\nTerminating...')
- except Exception as e:
- eprint(f'BEINCServer critical error: {e}')
+ except Exception as exp:
+ eprint(f'BEINCServer critical error: {exp}')
sys.exit(1)
sys.exit(0)
diff --git a/beinc_weechat.py b/beinc_weechat.py
index b3550d8..cdbfe1f 100644
--- a/beinc_weechat.py
+++ b/beinc_weechat.py
@@ -1,7 +1,5 @@
-# -*- coding: utf-8 -*-
-
-# Blackmore's Enhanced IRC-Notification Collection (BEINC) v4.3
-# Copyright (C) 2013-2022 Simeon Simeonov
+# Blackmore's Enhanced IRC-Notification Collection (BEINC)
+# Copyright (C) 2013-2024 Simeon Simeonov
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -16,11 +14,11 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
"""BEINC client for Weechat"""
+
import datetime
import io
import json
import os
-import socket
import ssl
import urllib.parse
import urllib.request
@@ -28,7 +26,7 @@ import urllib.request
import weechat
__author__ = 'Simeon Simeonov'
-__version__ = '4.3'
+__version__ = '4.4'
__license__ = 'GPL3'
@@ -178,19 +176,18 @@ class WeechatTarget:
try:
title = self._fetch_formatted_str(self._pm_title_template, values)
message = self._fetch_formatted_str(
- self._pm_message_template,
- values,
+ self._pm_message_template, values
)
if not self._send_beinc_message(title, message) and self._debug:
beinc_prnt(
f'BEINC DEBUG: send_private_message_notification-ERROR '
f'for "{self._name}": _send_beinc_message -> False'
)
- except Exception as e:
+ except Exception as exp:
if self._debug:
beinc_prnt(
f'BEINC DEBUG: send_private_message_notification-ERROR '
- f'for "{self._name}": {e}'
+ f'for "{self._name}": {exp}'
)
def send_channel_message_notification(self, values):
@@ -210,11 +207,11 @@ class WeechatTarget:
f'BEINC DEBUG: send_channel_message_notification-ERROR '
f'for "{self._name}": _send_beinc_message -> False'
)
- except Exception as e:
+ except Exception as exp:
if self._debug:
beinc_prnt(
f'BEINC DEBUG: send_channel_message_notification-ERROR '
- f'for "{self._name}": {e}'
+ f'for "{self._name}": {exp}'
)
def send_notify_message_notification(self, values):
@@ -234,11 +231,11 @@ class WeechatTarget:
f'BEINC DEBUG: send_notify_message_notification-ERROR '
f'for "{self._name}": _send_beinc_message -> False'
)
- except Exception as e:
+ except Exception as exp:
if self._debug:
beinc_prnt(
f'BEINC DEBUG: send_notify_message_notification-ERROR '
- f'for "{self._name}": {e}'
+ f'for "{self._name}": {exp}'
)
def send_broadcast_notification(self, message):
@@ -256,11 +253,11 @@ class WeechatTarget:
f'BEINC DEBUG: send_broadcast_notification-ERROR '
f'for "{self._name}": _send_beinc_message -> False'
)
- except Exception as e:
+ except Exception as exp:
if self._debug:
beinc_prnt(
f'BEINC DEBUG: send_broadcast_notification-ERROR '
- f'for "{self._name}": {e}'
+ f'for "{self._name}": {exp}'
)
def _context_setup(self):
@@ -282,12 +279,12 @@ class WeechatTarget:
context.set_ciphers(self._ssl_ciphers)
self._context = context
return True
- except ssl.SSLError as e:
+ except ssl.SSLError as err:
if self._debug:
- beinc_prnt(f'BEINC DEBUG: SSL/TLS error: {e}\n')
- except Exception as e:
+ beinc_prnt(f'BEINC DEBUG: SSL/TLS error: {err}\n')
+ except Exception as exp:
if self._debug:
- beinc_prnt(f'BEINC DEBUG: Generic context error: {e}\n')
+ beinc_prnt(f'BEINC DEBUG: Generic context error: {exp}\n')
self._context = None
return False
@@ -351,7 +348,7 @@ class WeechatTarget:
)
response_dict = json.loads(response.read().decode('utf-8'))
if response.code != 200:
- raise socket.error(response_dict.get('message', ''))
+ raise OSError(response_dict.get('message', ''))
if self._debug:
beinc_prnt(
"BEINC DEBUG: Server responded: "
@@ -359,15 +356,15 @@ class WeechatTarget:
)
self._last_message = datetime.datetime.now()
return True
- except ssl.SSLError as e:
+ except ssl.SSLError as err:
if self._debug:
- beinc_prnt(f'BEINC DEBUG: SSL/TLS error: {e}\n')
- except socket.error as e:
+ beinc_prnt(f'BEINC DEBUG: SSL/TLS error: {err}\n')
+ except OSError as err:
if self._debug:
- beinc_prnt(f'BEINC DEBUG: Connection error: {e}\n')
- except Exception as e:
+ beinc_prnt(f'BEINC DEBUG: Connection error: {err}\n')
+ except Exception as exp:
if self._debug:
- beinc_prnt(f'BEINC DEBUG: Unable to send message: {e}\n')
+ beinc_prnt(f'BEINC DEBUG: Unable to send message: {exp}\n')
return False
@@ -398,7 +395,7 @@ def beinc_cmd_target_handler(cmd_tokens):
if cmd_tokens[0] == 'list':
beinc_prnt('--- Globals ---')
for key, value in global_values.items():
- beinc_prnt(f'{key} -> {str(value)}')
+ beinc_prnt(f'{key} -> {value}')
beinc_prnt('--- Targets ---')
for target in target_list:
beinc_prnt(str(target))
@@ -539,8 +536,7 @@ def beinc_init():
try:
beinc_config_file_str = os.path.join(
- weechat.info_get('weechat_dir', ''),
- 'beinc_weechat.json',
+ weechat.info_get('weechat_dir', ''), 'beinc_weechat.json'
)
beinc_prnt(f'Parsing {beinc_config_file_str}...')
custom_error = 'load error'
@@ -565,8 +561,8 @@ def beinc_init():
for target in config_dict['irc_client']['targets']:
try:
new_target = WeechatTarget(target)
- except Exception as e:
- beinc_prnt(f'Unable to add target: {e}')
+ except Exception as exp:
+ beinc_prnt(f'Unable to add target: {exp}')
continue
if new_target.channel_messages_policy:
global_values['global_channel_messages_policy'] = True
@@ -577,10 +573,10 @@ def beinc_init():
target_list.append(new_target)
beinc_prnt(f'BEINC target "{new_target.name}" added')
beinc_prnt('Done!')
- except Exception as e:
+ except Exception as exp:
beinc_prnt(
f'ERROR: unable to parse {beinc_config_file_str}: '
- f'{custom_error} - {e}\nBEINC is now disabled'
+ f'{custom_error} - {exp}\nBEINC is now disabled'
)
enabled = False
# do not return error / exit the script
@@ -594,7 +590,7 @@ weechat.register(
__author__,
__version__,
__license__,
- 'Blackmore\'s Extended IRC Notification Collection (Weechat Client)',
+ "Blackmore's Extended IRC Notification Collection (Weechat Client)",
'',
'',
)
--
cgit v1.3