Skip to content

Commit 91a5344

Browse files
committed
Chore: Code formatting and linting
Run Black, isort, and ruff on the core machinery.
1 parent 6f74e31 commit 91a5344

File tree

10 files changed

+439
-385
lines changed

10 files changed

+439
-385
lines changed

mqttwarn/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
# -*- coding: utf-8 -*-
22
# (c) 2014-2018 The mqttwarn developers
33

4-
__version__ = '0.29.1'
4+
__version__ = "0.29.1"
55

6-
__author__ = 'Jan-Piet Mens <jpmens()gmail.com>, Ben Jones <ben.jones12()gmail.com>'
7-
__copyright__ = 'Copyright 2014-2022 Jan-Piet Mens'
8-
__license__ = 'Eclipse Public License - v 2.0 (http://www.eclipse.org/legal/epl-2.0/)'
6+
__author__ = "Jan-Piet Mens <jpmens()gmail.com>, Ben Jones <ben.jones12()gmail.com>"
7+
__copyright__ = "Copyright 2014-2022 Jan-Piet Mens"
8+
__license__ = "Eclipse Public License - v 2.0 (http://www.eclipse.org/legal/epl-2.0/)"

mqttwarn/commands.py

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,24 @@
11
# -*- coding: utf-8 -*-
22
# (c) 2014-2019 The mqttwarn developers
33
from __future__ import print_function
4-
import os
5-
import sys
6-
import json
4+
75
import codecs
8-
import signal
6+
import json
97
import logging
8+
import os
9+
import signal
10+
import sys
1011

1112
from docopt import docopt
1213

1314
from mqttwarn import __version__
14-
from mqttwarn.configuration import load_configuration, Config
15-
from mqttwarn.core import bootstrap, subscribe_forever, cleanup, run_plugin
15+
from mqttwarn.configuration import Config, load_configuration
16+
from mqttwarn.core import bootstrap, cleanup, run_plugin, subscribe_forever
1617
from mqttwarn.util import get_resource_content
1718

1819
logger = logging.getLogger(__name__)
1920

20-
APP_NAME = 'mqttwarn'
21+
APP_NAME = "mqttwarn"
2122

2223

2324
def run():
@@ -57,32 +58,33 @@ def run():
5758
commandline_schema = run.__doc__.format(program=APP_NAME)
5859

5960
# Read commandline options
60-
options = docopt(commandline_schema, version=APP_NAME + ' ' + __version__)
61+
options = docopt(commandline_schema, version=APP_NAME + " " + __version__)
6162

6263
# TODO: Review this. Why do we need it?
63-
utf8_writer = codecs.getwriter('utf-8')
64+
utf8_writer = codecs.getwriter("utf-8")
6465
sys.stdout = utf8_writer(sys.stdout.buffer)
6566

66-
if options['make-config']:
67-
payload = get_resource_content('mqttwarn.examples', 'basic/mqttwarn.ini')
67+
if options["make-config"]:
68+
payload = get_resource_content("mqttwarn.examples", "basic/mqttwarn.ini")
6869
print(payload)
6970

70-
elif options['make-samplefuncs']:
71-
payload = get_resource_content('mqttwarn.examples', 'basic/samplefuncs.py')
71+
elif options["make-samplefuncs"]:
72+
payload = get_resource_content("mqttwarn.examples", "basic/samplefuncs.py")
7273
print(payload)
7374

74-
elif options['--plugin'] and options['--options']:
75+
elif options["--plugin"] and options["--options"]:
7576

7677
# Decode arguments
77-
arg_plugin = options['--plugin']
78-
arg_options = json.loads(options['--options'])
78+
arg_plugin = options["--plugin"]
79+
arg_options = json.loads(options["--options"])
7980
arg_config = None
80-
if "--config" in options and options['--config'] is not None:
81-
arg_config = json.loads(options['--config'])
81+
if "--config" in options and options["--config"] is not None:
82+
arg_config = json.loads(options["--config"])
8283

8384
# Launch service plugin in standalone mode
84-
launch_plugin_standalone(arg_plugin, arg_options, configfile=options.get("--config-file"), config_more=arg_config)
85-
85+
launch_plugin_standalone(
86+
arg_plugin, arg_options, configfile=options.get("--config-file"), config_more=arg_config
87+
)
8688

8789
# Run mqttwarn in service mode when no command line arguments are given
8890
else:
@@ -154,8 +156,8 @@ def setup_logging(config):
154156
if not LOGFILE:
155157
pass
156158

157-
elif LOGFILE.startswith('stream://'):
158-
LOGFILE = LOGFILE.replace('stream://', '')
159+
elif LOGFILE.startswith("stream://"):
160+
LOGFILE = LOGFILE.replace("stream://", "")
159161
logging.basicConfig(stream=eval(LOGFILE), level=LOGLEVEL, format=LOGFORMAT)
160162

161163
# Send log messages to file by configuring "logfile = 'mqttwarn.log'"

mqttwarn/configuration.py

Lines changed: 63 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,31 @@
11
# -*- coding: utf-8 -*-
2-
# (c) 2014-2021 The mqttwarn developers
3-
import os
4-
import sys
2+
# (c) 2014-2022 The mqttwarn developers
53
import ast
64
import codecs
75
import logging
8-
from configparser import RawConfigParser, NoOptionError
6+
import os
7+
import sys
8+
from configparser import NoOptionError, RawConfigParser
9+
10+
from mqttwarn.util import load_functions
911

1012
HAVE_TLS = True
1113
try:
1214
import ssl
1315
except ImportError:
1416
HAVE_TLS = False
1517

16-
from mqttwarn.util import load_functions
1718

1819
logger = logging.getLogger(__name__)
1920

2021

2122
class Config(RawConfigParser):
2223

2324
specials = {
24-
'TRUE' : True,
25-
'FALSE' : False,
26-
'NONE' : None,
27-
}
25+
"TRUE": True,
26+
"FALSE": False,
27+
"NONE": None,
28+
}
2829

2930
def __init__(self, configuration_file=None, defaults=None):
3031

@@ -34,39 +35,39 @@ def __init__(self, configuration_file=None, defaults=None):
3435

3536
RawConfigParser.__init__(self)
3637
if configuration_file is not None:
37-
f = codecs.open(configuration_file, 'r', encoding='utf-8')
38+
f = codecs.open(configuration_file, "r", encoding="utf-8")
3839
self.read_file(f)
3940
f.close()
4041

4142
self.configuration_path = os.path.dirname(configuration_file)
4243

43-
''' set defaults '''
44-
self.hostname = 'localhost'
45-
self.port = 1883
46-
self.username = None
47-
self.password = None
48-
self.clientid = None
49-
self.lwt = None
44+
""" set defaults """
45+
self.hostname = "localhost"
46+
self.port = 1883
47+
self.username = None
48+
self.password = None
49+
self.clientid = None
50+
self.lwt = None
5051
self.skipretained = False
5152
self.cleansession = False
52-
self.protocol = 3
53+
self.protocol = 3
5354

54-
self.logformat = '%(asctime)-15s %(levelname)-8s [%(name)-26s] %(message)s'
55-
self.logfile = "stream://sys.stderr"
56-
self.loglevel = 'DEBUG'
55+
self.logformat = "%(asctime)-15s %(levelname)-8s [%(name)-26s] %(message)s"
56+
self.logfile = "stream://sys.stderr"
57+
self.loglevel = "DEBUG"
5758

58-
self.functions = None
59-
self.num_workers = 1
59+
self.functions = None
60+
self.num_workers = 1
6061

61-
self.ca_certs = None
62-
self.tls_version = None
63-
self.certfile = None
64-
self.keyfile = None
62+
self.ca_certs = None
63+
self.tls_version = None
64+
self.certfile = None
65+
self.keyfile = None
6566
self.tls_insecure = False
66-
self.tls = False
67+
self.tls = False
6768

6869
self.__dict__.update(defaults)
69-
self.__dict__.update(self.config('defaults'))
70+
self.__dict__.update(self.config("defaults"))
7071

7172
if HAVE_TLS is False:
7273
logger.error("TLS parameters set but no TLS available (SSL)")
@@ -77,13 +78,13 @@ def __init__(self, configuration_file=None, defaults=None):
7778
self.tls = True
7879

7980
if self.tls_version is not None:
80-
if self.tls_version == 'tlsv1_2':
81+
if self.tls_version == "tlsv1_2":
8182
self.tls_version = ssl.PROTOCOL_TLSv1_2
82-
if self.tls_version == 'tlsv1_1':
83+
if self.tls_version == "tlsv1_1":
8384
self.tls_version = ssl.PROTOCOL_TLSv1_1
84-
if self.tls_version == 'tlsv1':
85+
if self.tls_version == "tlsv1":
8586
self.tls_version = ssl.PROTOCOL_TLSv1
86-
if self.tls_version == 'sslv3':
87+
if self.tls_version == "sslv3":
8788
self.tls_version = ssl.PROTOCOL_SSLv3
8889

8990
self.loglevelnumber = self.level2number(self.loglevel)
@@ -109,18 +110,17 @@ def __init__(self, configuration_file=None, defaults=None):
109110
def level2number(self, level):
110111

111112
levels = {
112-
'CRITICAL' : 50,
113-
'DEBUG' : 10,
114-
'ERROR' : 40,
115-
'FATAL' : 50,
116-
'INFO' : 20,
117-
'NOTSET' : 0,
118-
'WARN' : 30,
119-
'WARNING' : 30,
113+
"CRITICAL": 50,
114+
"DEBUG": 10,
115+
"ERROR": 40,
116+
"FATAL": 50,
117+
"INFO": 20,
118+
"NOTSET": 0,
119+
"WARN": 30,
120+
"WARNING": 30,
120121
}
121122

122-
return levels.get(level.upper(), levels['DEBUG'])
123-
123+
return levels.get(level.upper(), levels["DEBUG"])
124124

125125
def g(self, section, key, default=None):
126126
try:
@@ -130,7 +130,7 @@ def g(self, section, key, default=None):
130130
return ast.literal_eval(val)
131131
except NoOptionError:
132132
return default
133-
except ValueError: # e.g. %(xxx)s in string
133+
except ValueError: # e.g. %(xxx)s in string
134134
return val
135135
except SyntaxError: # If not python value, e.g. list of targets coma separated
136136
return val
@@ -139,12 +139,12 @@ def g(self, section, key, default=None):
139139
return val
140140

141141
def getlist(self, section, key):
142-
''' Return a list, fail if it isn't a list '''
142+
"""Return a list, fail if it isn't a list"""
143143

144144
val = None
145145
try:
146146
val = self.get(section, key)
147-
val = [s.strip() for s in val.split(',')]
147+
val = [s.strip() for s in val.split(",")]
148148
except Exception as e:
149149
logger.warning("Expecting a list in section `%s', key `%s' (%s)" % (section, key, e))
150150

@@ -159,43 +159,42 @@ def getdict(self, section, key):
159159
return None
160160

161161
def config(self, section):
162-
''' Convert a whole section's options (except the options specified
163-
explicitly below) into a dict, turning
162+
"""Convert a whole section's options (except the options specified
163+
explicitly below) into a dict, turning
164164
165-
[config:mqtt]
166-
host = 'localhost'
167-
username = None
168-
list = [1, 'aaa', 'bbb', 4]
165+
[config:mqtt]
166+
host = 'localhost'
167+
username = None
168+
list = [1, 'aaa', 'bbb', 4]
169169
170-
into
170+
into
171171
172-
{u'username': None, u'host': 'localhost', u'list': [1, 'aaa', 'bbb', 4]}
172+
{u'username': None, u'host': 'localhost', u'list': [1, 'aaa', 'bbb', 4]}
173173
174-
Cannot use config.items() because I want each value to be
175-
retrieved with g() as above '''
174+
Cannot use config.items() because I want each value to be
175+
retrieved with g() as above"""
176176

177177
d = {}
178178
if self.has_section(section):
179-
d = dict((key, self.g(section, key))
180-
for (key) in self.options(section) if key not in ['targets', 'module'])
179+
d = dict((key, self.g(section, key)) for (key) in self.options(section) if key not in ["targets", "module"])
181180
return d
182181

183182

184-
def load_configuration(configfile=None, name='mqttwarn'):
183+
def load_configuration(configfile=None, name="mqttwarn"):
185184

186185
if configfile is None:
187-
configfile = os.getenv(name.upper() + 'INI', name + '.ini')
186+
configfile = os.getenv(name.upper() + "INI", name + ".ini")
188187

189188
if not os.path.exists(configfile):
190189
raise FileNotFoundError('Configuration file "{}" does not exist'.format(configfile))
191190

192191
# TODO: There should be a factory method which creates a `Config` instance,
193192
# including defaults, but without loading a configuration file.
194193
defaults = {
195-
'clientid': name,
196-
'lwt': 'clients/{}'.format(name),
197-
'lwt_alive': '1',
198-
'lwt_dead': '0',
194+
"clientid": name,
195+
"lwt": "clients/{}".format(name),
196+
"lwt_alive": "1",
197+
"lwt_dead": "0",
199198
}
200199

201200
return Config(configfile, defaults=defaults)

0 commit comments

Comments
 (0)