Skip to content

Commit 6fc657f

Browse files
committed
.pre-commit: move from isort/black to ruff/ty
- Ruff combines and extends capabilities of both of those tools, - add `ty` type checker hook - would likely work even better if the type hinting improved in the codebase, currently there are too many Any/Unknowns detected. Maybe consider using MonkeyType to generate stub files from types detected at runtime. Signed-off-by: iwanicki92 <iwanicki92@gmail.com>
1 parent a9fccbf commit 6fc657f

16 files changed

Lines changed: 683 additions & 141 deletions

.codespellrc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
[codespell]
22
exclude-file = .codespellx
3-
ignore-words-list = "FPT,FTP,fpt,ftp,checkin"
3+
ignore-words-list = FPT,FTP,fpt,ftp,checkin

.pre-commit-config.yaml

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -49,17 +49,11 @@ repos:
4949
- id: shellcheck
5050
args: ["--severity=warning"]
5151

52-
- repo: https://github.com/pycqa/isort
53-
rev: 9.0.0b1
52+
- repo: https://github.com/astral-sh/ruff-pre-commit
53+
rev: v0.16.0
5454
hooks:
55-
- id: isort
56-
name: isort (python)
57-
58-
- repo: https://github.com/psf/black
59-
rev: 26.5.1
60-
hooks:
61-
- id: black
62-
args: ["--line-length", "79"]
55+
- id: ruff-check
56+
- id: ruff-format
6357

6458
- repo: https://github.com/MarketSquare/robotframework-robocop
6559
rev: v8.4.1
@@ -70,3 +64,9 @@ repos:
7064
- id: robocop-format
7165
additional_dependencies:
7266
- typing_extensions
67+
68+
- repo: https://github.com/astral-sh/ty-pre-commit
69+
rev: v0.0.65
70+
hooks:
71+
- id: ty
72+
args: [--isolated, --group, test, --project, osfv_cli]

osfv_cli/pyproject.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,6 @@ osfv_cli = "osfv.cli.cli:main"
3131

3232
[tool.poetry]
3333
include = ["src/models/*.yml"]
34+
35+
[tool.ruff]
36+
line-length = 80

osfv_cli/src/osfv/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import sys
22

33
if __name__ == "__main__":
4-
from osfv.osfv_cli.osfv_cli import main
4+
from osfv.cli.cli import main
55

66
sys.exit(main())

osfv_cli/src/osfv/cli/cli.py

Lines changed: 9 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,14 @@
1313
import pexpect
1414
import requests
1515
import typer
16+
from typer import Argument, Context, Option
17+
1618
from osfv.libs import utils
1719
from osfv.libs.models import Models
1820
from osfv.libs.rte import RTE
1921
from osfv.libs.snipeit_api import SnipeIT
2022
from osfv.libs.sonoff_api import SonoffDevice
2123
from osfv.libs.zabbix import Zabbix
22-
from typer import Argument, Context, Option
2324

2425

2526
class API:
@@ -461,9 +462,7 @@ def update_zabbix_assets():
461462
for s in forbidden_symbols:
462463
new_key = new_key.replace(s, "_")
463464

464-
snipeit_assets[new_key] = snipeit_assets.pop(
465-
snipeit_assets_keys[i]
466-
)
465+
snipeit_assets[new_key] = snipeit_assets.pop(snipeit_assets_keys[i])
467466

468467
if snipeit_configuration_error:
469468
print(
@@ -486,9 +485,7 @@ def update_zabbix_assets():
486485
):
487486
update_available = True
488487

489-
common_keys = set(snipeit_assets.keys()) & set(
490-
current_zabbix_assets.keys()
491-
)
488+
common_keys = set(snipeit_assets.keys()) & set(current_zabbix_assets.keys())
492489

493490
if keys_not_present_in_zabbix.__len__() > 0:
494491
print("Assets not present in Zabbix (these will be added):")
@@ -1068,9 +1065,7 @@ def flash_write(
10681065
] = Path("write.rom"),
10691066
bios: Annotated[
10701067
bool,
1071-
Option(
1072-
"--bios", "-b", help='Adds "-i bios --ifd" to flashrom command'
1073-
),
1068+
Option("--bios", "-b", help='Adds "-i bios --ifd" to flashrom command'),
10741069
] = False,
10751070
dry_mecheck: Annotated[
10761071
bool,
@@ -1119,23 +1114,17 @@ def flash_erase(ctx):
11191114
## sonoff commands
11201115

11211116

1122-
def sonoff_setup(
1123-
sonoff_ip: str | None, rte_ip: str | None
1124-
) -> tuple[bool, int]:
1117+
def sonoff_setup(sonoff_ip: str | None, rte_ip: str | None) -> tuple[bool, int]:
11251118
if not sonoff_ip:
11261119
if not rte_ip:
11271120
print("Either sonoff_ip or rte_ip is required")
11281121
raise typer.Exit(1)
1129-
sonoff_ip = apis.get_or_create_snipeit().get_sonoff_ip_by_rte_ip(
1130-
rte_ip
1131-
)
1122+
sonoff_ip = apis.get_or_create_snipeit().get_sonoff_ip_by_rte_ip(rte_ip)
11321123
if not sonoff_ip:
11331124
print(f"No Sonoff Device found with RTE IP: {rte_ip}")
11341125
raise typer.Exit(1)
11351126

1136-
asset_id = apis.get_or_create_snipeit().get_asset_id_by_sonoff_ip(
1137-
sonoff_ip
1138-
)
1127+
asset_id = apis.get_or_create_snipeit().get_asset_id_by_sonoff_ip(sonoff_ip)
11391128
if asset_id is None:
11401129
print(f"No asset found with Sonoff IP: {sonoff_ip}")
11411130
raise typer.Exit(1)
@@ -1382,9 +1371,7 @@ def get_zabbix_compatible_assets_from_asset(asset):
13821371
if field_name in ["RTE IP", "Sonoff IP", "PiKVM IP"]:
13831372
field_value = field_data.get("value")
13841373
if field_value:
1385-
key = f"{asset['asset_tag']}_{field_name}".replace(
1386-
" ", "_"
1387-
)
1374+
key = f"{asset['asset_tag']}_{field_name}".replace(" ", "_")
13881375
result[key] = field_value
13891376
return result
13901377

osfv_cli/src/osfv/libs/flash_image.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import os
22
import struct
3-
import sys
3+
from collections.abc import Sequence
44
from itertools import repeat
55

66

77
class FlashImage:
88
# based on flashrom/utils/ich_descriptor_tool.c
9-
REGION_INDICES = [
9+
REGION_INDICES: Sequence[str] = (
1010
"fd",
1111
"bios",
1212
"me",
@@ -23,7 +23,7 @@ class FlashImage:
2323
"reg13",
2424
"reg14",
2525
"reg15",
26-
]
26+
)
2727
NUMBER_OF_REGIONS = len(REGION_INDICES)
2828
FLVALSIG = 0x0FF0A55A
2929

@@ -40,7 +40,7 @@ def get_exit_code(self):
4040
return self.EXIT_CODE
4141

4242
def get_image_data(self):
43-
return imageData
43+
return self.imageData
4444

4545
def get_region_index(self, region_name):
4646
try:
@@ -85,9 +85,7 @@ def load_image_file(self, image_path):
8585

8686
FLMAP0 = struct.unpack(
8787
"<I",
88-
self.imageData[
89-
(valsig_offset + 0x04) : (valsig_offset + 0x08)
90-
],
88+
self.imageData[(valsig_offset + 0x04) : (valsig_offset + 0x08)],
9189
)[0x00]
9290
FRBA = (FLMAP0 >> 0x0C) & 0x00000FF0
9391

@@ -98,9 +96,7 @@ def load_image_file(self, image_path):
9896
region_format = f"<{self.NUMBER_OF_REGIONS}I"
9997
self.REGIONS = struct.unpack(
10098
region_format,
101-
self.imageData[
102-
FRBA : (FRBA + (0x04 * self.NUMBER_OF_REGIONS))
103-
],
99+
self.imageData[FRBA : (FRBA + (0x04 * self.NUMBER_OF_REGIONS))],
104100
)
105101
return True
106102

osfv_cli/src/osfv/libs/models.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import os
22
import sys
3-
import time
43
from pathlib import Path
54

5+
import voluptuous
66
import yaml
77
from importlib_resources import files
88
from voluptuous import Any, Optional, Required, Schema
@@ -13,7 +13,7 @@ def __init__(self):
1313
pass
1414

1515
def list_models(self):
16-
print(f"Supported DUT models:")
16+
print("Supported DUT models:")
1717
file_path = os.path.join(files("osfv"), "models")
1818

1919
for roots, dirs, filenames in os.walk(file_path):
@@ -44,9 +44,7 @@ def load_model_data(self, dut_model, exit_on_failure=True):
4444
if not os.path.isfile(file_path):
4545
if exit_on_failure:
4646
raise UnsupportedDUTModel(
47-
"The {file_path} model is not yet supported".format(
48-
file_path=dut_model
49-
)
47+
f"The {dut_model} model is not yet supported"
5048
)
5149
else:
5250
model_YML_status = False
@@ -95,9 +93,9 @@ def load_model_data(self, dut_model, exit_on_failure=True):
9593

9694
try:
9795
schema(data)
98-
except Exception as e:
96+
except voluptuous.Error as e:
9997
if exit_on_failure:
100-
exit(f"Model file is invalid: {e}")
98+
sys.exit(f"Model file is invalid: {e}")
10199
else:
102100
model_YML_status = False
103101

@@ -119,9 +117,8 @@ def load_model_data(self, dut_model, exit_on_failure=True):
119117
current_field = current_field[key]
120118
else:
121119
if exit_on_failure:
122-
exit(
123-
f"Required field '{field}' is missing in model "
124-
f"config."
120+
sys.exit(
121+
f"Required field '{field}' is missing in model config."
125122
)
126123
else:
127124
model_YML_status = False

osfv_cli/src/osfv/libs/rte.py

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,10 @@
44

55
import paramiko
66
import requests
7-
import yaml
8-
from importlib_resources import files
7+
98
from osfv.libs.models import Models
109
from osfv.libs.rtectrl_api import rtectrl
11-
from voluptuous import Any, Optional, Required, Schema
10+
from osfv.libs.utils import OSFVException
1211

1312

1413
class RTE(rtectrl):
@@ -46,9 +45,8 @@ def __init__(self, rte_ip, dut_model, sonoff):
4645
self.sonoff = sonoff
4746
if not self.sonoff_sanity_check():
4847
raise SonoffNotFound(
49-
exit(
50-
f"Missing value for 'sonoff_ip' or Sonoff not found "
51-
f"in SnipeIT"
48+
sys.exit(
49+
"Missing value for 'sonoff_ip' or Sonoff not found in SnipeIT"
5250
)
5351
)
5452

@@ -202,12 +200,12 @@ def psu_on(self):
202200
self.sonoff.turn_on()
203201
state = self.sonoff.get_state()
204202
if state != self.PSU_STATE_ON:
205-
raise Exception("Failed to power control ON")
203+
raise OSFVException("Failed to power control ON")
206204
elif self.dut_data["pwr_ctrl"]["relay"] is True:
207205
self.relay_set(self.PSU_STATE_ON)
208206
state = self.relay_get()
209207
if state != self.PSU_STATE_ON:
210-
raise Exception("Failed to power control ON")
208+
raise OSFVException("Failed to power control ON")
211209
time.sleep(5)
212210

213211
def psu_off(self):
@@ -226,12 +224,12 @@ def psu_off(self):
226224
self.sonoff.turn_off()
227225
state = self.sonoff.get_state()
228226
if state != self.PSU_STATE_OFF:
229-
raise Exception("Failed to power control OFF")
227+
raise OSFVException("Failed to power control OFF")
230228
elif self.dut_data["pwr_ctrl"]["relay"] is True:
231229
self.relay_set(self.PSU_STATE_OFF)
232230
state = self.relay_get()
233231
if state != self.PSU_STATE_OFF:
234-
raise Exception("Failed to power control OFF")
232+
raise OSFVException("Failed to power control OFF")
235233
time.sleep(2)
236234

237235
def psu_get(self):
@@ -302,7 +300,7 @@ def pwr_ctrl_before_flash(self, programmer, power_state):
302300
if self.dut_data["pwr_ctrl"]["discharge_psu"]:
303301
self.discharge_psu()
304302
else:
305-
exit(
303+
sys.exit(
306304
f"Power state: '{power_state}' is not supported. Please check "
307305
f"model config."
308306
)
@@ -341,11 +339,11 @@ def create_layout_file(self):
341339
layout_content += f"{region['range']} {region['name']}\n"
342340

343341
# Create temporary file
344-
temp_file = tempfile.NamedTemporaryFile(
342+
with tempfile.NamedTemporaryFile(
345343
mode="w", suffix=".txt", delete=False
346-
)
347-
temp_file.write(layout_content)
348-
temp_file.close()
344+
) as temp_file:
345+
temp_file.write(layout_content)
346+
temp_file.close()
349347

350348
return temp_file.name
351349

@@ -476,12 +474,14 @@ def flash_create_args(self, extra_args=""):
476474
args = ""
477475

478476
# Set chip explicitly, if defined in model configuration
479-
if "flash_chip" in self.dut_data:
480-
if "model" in self.dut_data["flash_chip"]:
481-
args = " ".join(["-c", self.dut_data["flash_chip"]["model"]])
477+
if (
478+
"flash_chip" in self.dut_data
479+
and "model" in self.dut_data["flash_chip"]
480+
):
481+
args = " ".join(["-c", self.dut_data["flash_chip"]["model"]])
482482

483483
if extra_args:
484-
args = " ".join([args, extra_args])
484+
args = f"{args} {extra_args}"
485485

486486
return args
487487

@@ -522,7 +522,7 @@ def flash_erase(self):
522522
Returns:
523523
int: The return code from the flashrom command execution.
524524
"""
525-
args = self.flash_create_args(f"-E")
525+
args = self.flash_create_args("-E")
526526
return self.flash_cmd(args)
527527

528528
def flash_write(self, write_file, bios=False):
@@ -557,9 +557,11 @@ def flash_write(self, write_file, bios=False):
557557
rc = self.flash_cmd(args, write_file=write_file)
558558
time.sleep(2)
559559

560-
if "reset_cmos" in self.dut_data:
561-
if self.dut_data["reset_cmos"] == True:
562-
self.reset_cmos()
560+
if (
561+
"reset_cmos" in self.dut_data
562+
and self.dut_data["reset_cmos"] == True
563+
):
564+
self.reset_cmos()
563565
return rc
564566

565567
def sonoff_sanity_check(self):

0 commit comments

Comments
 (0)