Skip to content

Commit c043fa6

Browse files
authored
Linting and formatting, semi-lax. (#172)
* Linting and formatting, semi-lax. - `tox` now runs `black` and `ruff` on the project (the environment is called `lint`). - tox runs `ruff` with --fix to resolve fixable issues. - There is no pre-commit hook or CI integration as of yet. ### Code changes To adhere to even semi-lax linting, there were changes required in the code. These are: - Migrated use of python builtin identifiers (`type`, `id`, and `print`) to more appropriate names. - Some cases of long string literals were using implicit concatenation, which is now explicit (by adding a set of parentheses). ### Outstanding changes with current settings - `print` in history.py (shadowing builtin) was not fixed as it needs a bit more debugging to figure out exactly how it is used. ### Notes There is still a lot to do with regards to linting, formatting, and typing. This PR does not seek to resolve these issues, but attempts to create a baseline of requirements for the codebase to adhere to.
1 parent 9a66b8c commit c043fa6

26 files changed

+2722
-2778
lines changed

.github/workflows/test.yml

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ jobs:
77
runs-on: ${{ matrix.os }}
88
strategy:
99
matrix:
10-
os: [ubuntu-20.04]
10+
os: [ubuntu-20.04] # For python3.6
1111
python-version:
1212
- '3.6'
1313
- '3.7'
@@ -37,3 +37,32 @@ jobs:
3737
pip install -e .
3838
- name: Test and compare api calls
3939
run: ci/run_testsuite_and_record.sh
40+
41+
tox:
42+
name: tox
43+
runs-on: ubuntu-latest
44+
strategy:
45+
fail-fast: false
46+
matrix:
47+
python-version:
48+
- "3.7"
49+
- "3.8"
50+
- "3.9"
51+
- "3.10"
52+
- "3.11"
53+
54+
steps:
55+
- uses: actions/checkout@v3
56+
- name: Set up Python ${{ matrix.python-version }}
57+
uses: actions/setup-python@v4
58+
with:
59+
python-version: ${{ matrix.python-version }}
60+
- name: Install dependencies
61+
run: |
62+
python -m pip install --upgrade pip
63+
python -m pip install tox tox-gh-actions
64+
python -m pip install -r requirements.txt
65+
python -m pip install -r requirements-dev.txt
66+
- name: Test with tox
67+
run: tox r
68+

ci/diff.py

Lines changed: 49 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22
import json
33
import sys
44

5+
56
def group_objects(json_file_path):
6-
with open(json_file_path, 'r') as f:
7+
with open(json_file_path, "r") as f:
78
data = json.load(f)
89

910
grouped_objects = []
@@ -23,53 +24,57 @@ def group_objects(json_file_path):
2324

2425

2526
def main():
27+
if len(sys.argv) != 3:
28+
print("Usage: diff.py <file1> <file2>")
29+
sys.exit(1)
30+
31+
expected = group_objects(sys.argv[1])
32+
result = group_objects(sys.argv[2])
2633

27-
if len(sys.argv) != 3:
28-
print("Usage: diff.py <file1> <file2>")
29-
sys.exit(1)
34+
# Verify that the list of commands is the same
35+
cmdlist1 = []
36+
cmdlist2 = []
37+
for a in expected:
38+
cmdlist1.append(a[0]["command"].rstrip())
39+
for a in result:
40+
cmdlist2.append(a[0]["command"].rstrip())
41+
differ = difflib.Differ()
42+
diff = differ.compare(cmdlist1, cmdlist2)
43+
differences = [
44+
line for line in diff if line.startswith("-") or line.startswith("+")
45+
]
46+
if differences:
47+
print(
48+
"Diff between what commands were run in the recorded result and the current testsuite:"
49+
)
50+
for line in differences:
51+
print(line)
52+
sys.exit(1)
3053

31-
expected = group_objects(sys.argv[1])
32-
result = group_objects(sys.argv[2])
54+
# For each command, verify that the http calls and output is the same
55+
has_diff = False
56+
for i in range(len(expected)):
57+
cmd = expected[i][0]["command"].rstrip()
58+
cmd2 = result[i][0]["command"].rstrip()
59+
if cmd != cmd2:
60+
# This should never happen here, because it would get caught above
61+
print(f"Expected command: {cmd}\nActual command: {cmd2}")
62+
sys.exit(1)
3363

34-
# Verify that the list of commands is the same
35-
cmdlist1 = []
36-
cmdlist2 = []
37-
for a in expected:
38-
cmdlist1.append(a[0]['command'].rstrip())
39-
for a in result:
40-
cmdlist2.append(a[0]['command'].rstrip())
41-
differ = difflib.Differ()
42-
diff = differ.compare(cmdlist1, cmdlist2)
43-
differences = [line for line in diff if line.startswith('-') or line.startswith('+')]
44-
if differences:
45-
print("Diff between what commands were run in the recorded result and the current testsuite:")
46-
for line in differences:
47-
print(line)
48-
sys.exit(1)
64+
s1 = json.dumps(expected[i], indent=4).splitlines(keepends=True)
65+
s2 = json.dumps(result[i], indent=4).splitlines(keepends=True)
66+
if s1 != s2:
67+
has_diff = True
68+
print("=" * 72)
69+
print("Command:", cmd, " -expected, +tested")
70+
print("=" * 72)
71+
gen = difflib.ndiff(s1, s2)
72+
sys.stdout.writelines(gen)
73+
print("\n") # 2 newlines
4974

50-
# For each command, verify that the http calls and output is the same
51-
has_diff = False
52-
for i in range(len(expected)):
53-
cmd = expected[i][0]['command'].rstrip()
54-
cmd2 = result[i][0]['command'].rstrip()
55-
if cmd != cmd2:
56-
# This should never happen here, because it would get caught above
57-
print(f"Expected command: {cmd}\nActual command: {cmd2}")
58-
sys.exit(1)
59-
60-
s1 = json.dumps(expected[i], indent=4).splitlines(keepends=True)
61-
s2 = json.dumps(result[i], indent=4).splitlines(keepends=True)
62-
if s1 != s2:
63-
has_diff = True
64-
print("=" * 72)
65-
print("Command:",cmd," -expected, +tested")
66-
print("=" * 72)
67-
gen = difflib.ndiff(s1,s2)
68-
sys.stdout.writelines(gen)
69-
print("\n") # 2 newlines
75+
if has_diff:
76+
sys.exit(1)
7077

71-
if has_diff:
72-
sys.exit(1)
7378

74-
if __name__ == '__main__':
79+
if __name__ == "__main__":
7580
main()

mreg_cli/__init__.pyi

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
from .log import *
1+
from .log import *

mreg_cli/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
from . import main
22

3-
if __name__ == '__main__':
3+
if __name__ == "__main__":
44
main.main()

mreg_cli/bacnet.py

Lines changed: 59 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,71 +1,69 @@
1-
from .cli import Flag, cli
2-
from .exceptions import HostNotFoundWarning
1+
from .cli import Flag
32
from .history import history
43
from .host import host
5-
from .log import cli_error, cli_info, cli_warning
6-
from .util import (
7-
host_info_by_name,
8-
print_table,
9-
get,
10-
get_list,
11-
post,
12-
delete,
13-
)
4+
from .log import cli_error, cli_info
5+
from .util import delete, get, get_list, host_info_by_name, post, print_table
6+
147

158
def bacnetid_add(args):
169
info = host_info_by_name(args.name)
17-
if 'bacnetid' in info and info['bacnetid'] is not None:
18-
cli_error("{} already has BACnet ID {}.".format(info['name'],info['bacnetid']['id']))
19-
postdata = {'hostname': info['name']}
20-
path = '/api/v1/bacnet/ids/'
21-
bacnetid = getattr(args, 'id')
10+
if "bacnetid" in info and info["bacnetid"] is not None:
11+
cli_error(
12+
"{} already has BACnet ID {}.".format(info["name"], info["bacnetid"]["id"])
13+
)
14+
postdata = {"hostname": info["name"]}
15+
path = "/api/v1/bacnet/ids/"
16+
bacnetid = args.id
2217
if bacnetid:
23-
response = get(path+bacnetid, ok404=True)
18+
response = get(path + bacnetid, ok404=True)
2419
if response:
2520
j = response.json()
26-
cli_error('BACnet ID {} is already in use by {}'.format(j['id'], j['hostname']))
27-
postdata['id'] = bacnetid
28-
history.record_post(path, '', postdata)
21+
cli_error(
22+
"BACnet ID {} is already in use by {}".format(j["id"], j["hostname"])
23+
)
24+
postdata["id"] = bacnetid
25+
history.record_post(path, "", postdata)
2926
post(path, **postdata)
3027
info = host_info_by_name(args.name)
31-
if 'bacnetid' in info and info['bacnetid'] is not None:
32-
b = info['bacnetid']
33-
cli_info("Assigned BACnet ID {} to {}".format(b['id'], info['name']), print_msg=True)
28+
if "bacnetid" in info and info["bacnetid"] is not None:
29+
b = info["bacnetid"]
30+
cli_info(
31+
"Assigned BACnet ID {} to {}".format(b["id"], info["name"]), print_msg=True
32+
)
3433

3534

3635
host.add_command(
37-
prog='bacnetid_add',
38-
description='Assign a BACnet ID to the host.',
39-
short_desc='Add BACnet ID',
36+
prog="bacnetid_add",
37+
description="Assign a BACnet ID to the host.",
38+
short_desc="Add BACnet ID",
4039
callback=bacnetid_add,
4140
flags=[
42-
Flag('name',
43-
description='Name of host.',
44-
metavar='NAME'),
45-
Flag('-id',
46-
description='ID value (0-4194302)',
47-
metavar='ID'),
41+
Flag("name", description="Name of host.", metavar="NAME"),
42+
Flag("-id", description="ID value (0-4194302)", metavar="ID"),
4843
],
4944
)
5045

46+
5147
def bacnetid_remove(args):
5248
info = host_info_by_name(args.name)
53-
if 'bacnetid' not in info or info["bacnetid"] is None:
54-
cli_error("{} does not have a BACnet ID assigned.".format(info['name']))
55-
path = '/api/v1/bacnet/ids/{}'.format(info['bacnetid']['id'])
56-
history.record_delete(path, info['bacnetid'])
49+
if "bacnetid" not in info or info["bacnetid"] is None:
50+
cli_error("{} does not have a BACnet ID assigned.".format(info["name"]))
51+
path = "/api/v1/bacnet/ids/{}".format(info["bacnetid"]["id"])
52+
history.record_delete(path, info["bacnetid"])
5753
delete(path)
58-
cli_info("Unassigned BACnet ID {} from {}".format(info['bacnetid']['id'], info['name']), print_msg=True)
54+
cli_info(
55+
"Unassigned BACnet ID {} from {}".format(info["bacnetid"]["id"], info["name"]),
56+
print_msg=True,
57+
)
58+
5959

6060
host.add_command(
61-
prog='bacnetid_remove',
62-
description='Unassign the BACnet ID from the host.',
63-
short_desc='Remove BACnet ID',
61+
prog="bacnetid_remove",
62+
description="Unassign the BACnet ID from the host.",
63+
short_desc="Remove BACnet ID",
6464
callback=bacnetid_remove,
6565
flags=[
66-
Flag('name',
67-
description='Name of host.',
68-
metavar='NAME'),
66+
Flag("name", description="Name of host.", metavar="NAME"),
6967
],
7068
)
7169

@@ -81,22 +79,27 @@ def bacnetid_list(args):
8179
maxval = args.max
8280
if maxval > 4194302:
8381
cli_error("The maximum ID value is 4194302.")
84-
r = get_list("/api/v1/bacnet/ids/",{'id__range':'{},{}'.format(minval,maxval)})
85-
print_table(('ID','Hostname'), ('id','hostname'), r)
82+
r = get_list("/api/v1/bacnet/ids/", {"id__range": "{},{}".format(minval, maxval)})
83+
print_table(("ID", "Hostname"), ("id", "hostname"), r)
84+
8685

8786
host.add_command(
88-
prog='bacnetid_list',
89-
description='Find/list BACnet IDs and hostnames',
90-
short_desc='List used BACnet IDs',
87+
prog="bacnetid_list",
88+
description="Find/list BACnet IDs and hostnames",
89+
short_desc="List used BACnet IDs",
9190
callback=bacnetid_list,
9291
flags=[
93-
Flag('-min',
94-
description='Minimum ID value (0-4194302)',
95-
type=int,
96-
metavar='MIN'),
97-
Flag('-max',
98-
description='Maximum ID value (0-4194302)',
99-
type=int,
100-
metavar='MAX'),
92+
Flag(
93+
"-min",
94+
description="Minimum ID value (0-4194302)",
95+
flag_type=int,
96+
metavar="MIN",
97+
),
98+
Flag(
99+
"-max",
100+
description="Maximum ID value (0-4194302)",
101+
flag_type=int,
102+
metavar="MAX",
103+
),
101104
],
102105
)

0 commit comments

Comments
 (0)