Skip to content

Commit 29ea7bd

Browse files
fundakolnordicjm
authored andcommitted
scripts: Fix ruff issues
Fixed all ruff's issues from PR #2502. Signed-off-by: Lukasz Fundakowski <[email protected]>
1 parent 71b41e3 commit 29ea7bd

File tree

9 files changed

+138
-70
lines changed

9 files changed

+138
-70
lines changed

ci/fih_test_docker/damage_image.py

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,9 @@ def __len__(self):
114114

115115
def get_arguments():
116116
parser = argparse.ArgumentParser(description='Corrupt an MCUBoot image')
117-
parser.add_argument("-i", "--in-file", required=True, help='The input image to be corrupted (read only)')
117+
parser.add_argument(
118+
"-i", "--in-file", required=True, help='The input image to be corrupted (read only)'
119+
)
118120
parser.add_argument("-o", "--out-file", required=True, help='the corrupted image')
119121
parser.add_argument('-a', '--image-hash',
120122
default=False,
@@ -147,7 +149,10 @@ def damage_image(args, in_file, out_file_content, image_offset):
147149
# Find the Image header
148150
image_header = ImageHeader.read_from_binary(in_file)
149151
if image_header.ih_magic != IMAGE_MAGIC:
150-
raise Exception(f"Invalid magic in image_header: 0x{image_header.ih_magic:X} instead of 0x{IMAGE_MAGIC:X}")
152+
raise Exception(
153+
f"Invalid magic in image_header: 0x{image_header.ih_magic:X} "
154+
"instead of 0x{IMAGE_MAGIC:X}"
155+
)
151156

152157
# Find the TLV header
153158
tlv_info_offset = image_header.ih_hdr_size + image_header.ih_img_size
@@ -157,7 +162,10 @@ def damage_image(args, in_file, out_file_content, image_offset):
157162
if tlv_info.it_magic == TLV_PROT_INFO_MAGIC:
158163
logging.debug(f"Protected TLV found at offset 0x{tlv_info_offset:X}")
159164
if image_header.ih_protect_tlv_size != tlv_info.it_tlv_tot:
160-
raise Exception(f"Invalid prot TLV len ({image_header.ih_protect_tlv_size:d} vs. {tlv_info.it_tlv_tot:d})")
165+
raise Exception(
166+
f"Invalid prot TLV len ({image_header.ih_protect_tlv_size:d} "
167+
"vs. {tlv_info.it_tlv_tot:d})"
168+
)
161169

162170
# seek to unprotected TLV
163171
tlv_info_offset += tlv_info.it_tlv_tot
@@ -170,7 +178,9 @@ def damage_image(args, in_file, out_file_content, image_offset):
170178

171179
logging.debug(f"Unprotected TLV found at offset 0x{tlv_info_offset:X}")
172180
if tlv_info.it_magic != TLV_INFO_MAGIC:
173-
raise Exception(f"Invalid magic in tlv info: 0x{tlv_info.it_magic:X} instead of 0x{TLV_INFO_MAGIC:X}")
181+
raise Exception(
182+
f"Invalid magic in tlv info: 0x{tlv_info.it_magic:X} instead of 0x{TLV_INFO_MAGIC:X}"
183+
)
174184

175185
tlv_off = tlv_info_offset + len(ImageTLVInfo())
176186
tlv_end = tlv_info_offset + tlv_info.it_tlv_tot
@@ -180,9 +190,15 @@ def damage_image(args, in_file, out_file_content, image_offset):
180190
in_file.seek(image_offset + tlv_off, 0)
181191
tlv = ImageTLV.read_from_binary(in_file)
182192

183-
logging.debug(f" tlv {get_tlv_type_string(tlv.it_type):24s} len = {tlv.it_len:4d}, len = {len(tlv):4d}")
193+
logging.debug(
194+
f" tlv {get_tlv_type_string(tlv.it_type):24s} "
195+
"len = {tlv.it_len:4d}, len = {len(tlv):4d}"
196+
)
184197

185-
if is_valid_signature(tlv) and args.signature or tlv.it_type == TLV_VALUES['SHA256'] and args.image_hash:
198+
if (
199+
is_valid_signature(tlv) and args.signature
200+
or tlv.it_type == TLV_VALUES['SHA256'] and args.image_hash
201+
):
186202
damage_tlv(image_offset, tlv_off, tlv, out_file_content)
187203

188204
tlv_off += len(tlv)
@@ -194,17 +210,13 @@ def main():
194210
logging.debug("The script was started")
195211

196212
copyfile(args.in_file, args.out_file)
197-
in_file = open(args.in_file, 'rb')
213+
with open(args.in_file, 'rb') as in_file:
214+
out_file_content = bytearray(in_file.read())
198215

199-
out_file_content = bytearray(in_file.read())
216+
damage_image(args, in_file, out_file_content, 0)
200217

201-
damage_image(args, in_file, out_file_content, 0)
202-
203-
in_file.close()
204-
205-
file_to_damage = open(args.out_file, 'wb')
206-
file_to_damage.write(out_file_content)
207-
file_to_damage.close()
218+
with open(args.out_file, 'wb') as file_to_damage:
219+
file_to_damage.write(out_file_content)
208220

209221

210222
if __name__ == "__main__":

ci/fih_test_docker/generate_test_report.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,20 +23,28 @@ def print_results(results):
2323

2424
print("{:s}: {:d}.".format(CATEGORIES['TOTAL'], test_stats[CATEGORIES['TOTAL']]))
2525
print("{:s} ({:d}):".format(CATEGORIES['SUCCESS'], test_stats[CATEGORIES['SUCCESS']]))
26-
print(" {:s}: ({:d}):".format(CATEGORIES['ADDRES_NOEXEC'], test_stats[CATEGORIES['ADDRES_NOEXEC']]))
26+
print(" {:s}: ({:d}):".format(
27+
CATEGORIES['ADDRES_NOEXEC'], test_stats[CATEGORIES['ADDRES_NOEXEC']])
28+
)
2729
test_with_skip = test_stats[CATEGORIES['SUCCESS']] - test_stats[CATEGORIES['ADDRES_NOEXEC']]
2830
print(" {:s}: ({:d}):".format(CATEGORIES['SKIPPED'], test_with_skip))
29-
print(" {:s} ({:d}):".format(CATEGORIES['NO_BOOT'], test_with_skip - test_stats[CATEGORIES['BOOT']]))
31+
print(" {:s} ({:d}):".format(
32+
CATEGORIES['NO_BOOT'], test_with_skip - test_stats[CATEGORIES['BOOT']])
33+
)
3034
for last_line in failed_boot_last_lines:
3135
print(f" last line: {last_line:s} ({failed_boot_last_lines[last_line]:d})")
3236
print(" {:s} ({:d})".format(CATEGORIES['BOOT'], test_stats[CATEGORIES['BOOT']]))
33-
print("{:s} ({:d}):".format(CATEGORIES['FAILED'], test_stats[CATEGORIES['TOTAL']] - test_stats[CATEGORIES['SUCCESS']]))
37+
print("{:s} ({:d}):".format(
38+
CATEGORIES['FAILED'], test_stats[CATEGORIES['TOTAL']] - test_stats[CATEGORIES['SUCCESS']])
39+
)
3440
for reason in exec_fail_reasons:
3541
print(f" {reason:s} ({exec_fail_reasons[reason]:d})")
3642

3743

3844
def main():
39-
parser = argparse.ArgumentParser(description='''Process a FIH test output yaml file, and output a human readable report''')
45+
parser = argparse.ArgumentParser(
46+
description='''Process a FIH test output yaml file, and output a human readable report'''
47+
)
4048
parser.add_argument('filename', help='yaml file to process')
4149

4250
args = parser.parse_args()

ci/get_features.py

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -16,29 +16,38 @@
1616

1717
import argparse
1818
import os.path
19+
import sys
1920

2021
try:
2122
import tomllib
2223
except ModuleNotFoundError:
2324
import tomli as tomllib
2425

25-
parser = argparse.ArgumentParser(description='Print features from a Cargo.toml.')
26-
parser.add_argument('infile', help='Input file to parse')
2726

28-
args = parser.parse_args()
29-
if not os.path.isfile(args.infile):
30-
print("File not found")
31-
exit(1)
27+
def main() -> int:
28+
parser = argparse.ArgumentParser(description='Print features from a Cargo.toml.')
29+
parser.add_argument('infile', help='Input file to parse')
3230

33-
try:
34-
cargo_toml = open(args.infile).read()
35-
except Exception:
36-
print(f"Error reading \"{args.infile}\"")
37-
exit(1)
31+
args = parser.parse_args()
32+
if not os.path.isfile(args.infile):
33+
print("File not found")
34+
return 1
35+
36+
try:
37+
with open(args.infile) as file:
38+
cargo_toml = file.read()
39+
except Exception:
40+
print(f"Error reading \"{args.infile}\"")
41+
return 1
42+
43+
config = tomllib.loads(cargo_toml)
44+
if 'features' not in config:
45+
print("Missing \"[features]\" section")
46+
return 1
47+
48+
print(" ".join([k for k in config['features'] if k != 'default']))
49+
return 0
3850

39-
config = tomllib.loads(cargo_toml)
40-
if 'features' not in config:
41-
print("Missing \"[features]\" section")
42-
exit(1)
4351

44-
print(" ".join([k for k in config['features'] if k != 'default']))
52+
if __name__ == "__main__":
53+
sys.exit(main())

scripts/assemble.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ def same_keys(a, b):
3636
return False
3737
return all(bk in a for bk in b)
3838

39-
offset_re = re.compile(r"^#define DT_FLASH_AREA_([0-9A-Z_]+)_OFFSET(_0)?\s+(0x[0-9a-fA-F]+|[0-9]+)$")
39+
offset_re = re.compile(
40+
r"^#define DT_FLASH_AREA_([0-9A-Z_]+)_OFFSET(_0)?\s+(0x[0-9a-fA-F]+|[0-9]+)$"
41+
)
4042
size_re = re.compile(r"^#define DT_FLASH_AREA_([0-9A-Z_]+)_SIZE(_0)?\s+(0x[0-9a-fA-F]+|[0-9]+)$")
4143

4244
class Assembly:

scripts/imgtool/boot_record.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,5 +48,6 @@ def create_sw_component_data(sw_type, sw_version, sw_measurement_description,
4848
# Note: The measurement value must be the last item of the property
4949
# list because later it will be modified by the bootloader.
5050
last_key = list(properties.keys())[-1]
51-
assert last_key == SwComponent.MEASUREMENT_VALUE, 'Measurement value is not the last item of the property list'
51+
assert last_key == SwComponent.MEASUREMENT_VALUE, \
52+
'Measurement value is not the last item of the property list'
5253
return dumps(properties)

scripts/imgtool/dumpinfo.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,11 @@ def parse_size(size_hex):
6262

6363

6464
def parse_status(status_hex):
65-
return f"{STATUS[status_hex]} ({status_hex})" if status_hex in STATUS else f"INVALID ({status_hex})"
65+
return (
66+
f"{STATUS[status_hex]} ({status_hex})"
67+
if status_hex in STATUS
68+
else f"INVALID ({status_hex})"
69+
)
6670

6771

6872
def parse_boot_magic(trailer_magic):
@@ -131,7 +135,7 @@ def dump_imginfo(imgfile, outfile=None, silent=False):
131135
with open(imgfile, "rb") as f:
132136
b = f.read()
133137
except FileNotFoundError:
134-
raise click.UsageError(f"Image file not found ({imgfile})")
138+
raise click.UsageError(f"Image file not found ({imgfile})") from None
135139

136140
# Parsing the image header
137141
_header = struct.unpack('IIHHIIBBHI', b[:28])

scripts/imgtool/image.py

Lines changed: 39 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -103,14 +103,19 @@
103103
TLV_VENDOR_RES_MIN = 0x00a0
104104
TLV_VENDOR_RES_MAX = 0xfffe
105105

106-
STRUCT_ENDIAN_DICT = {
107-
'little': '<',
108-
'big': '>'
109-
}
106+
STRUCT_ENDIAN_DICT = {'little': '<', 'big': '>'}
110107

111-
VerifyResult = Enum('VerifyResult',
112-
['OK', 'INVALID_MAGIC', 'INVALID_TLV_INFO_MAGIC', 'INVALID_HASH', 'INVALID_SIGNATURE',
113-
'KEY_MISMATCH'])
108+
VerifyResult = Enum(
109+
'VerifyResult',
110+
[
111+
'OK',
112+
'INVALID_MAGIC',
113+
'INVALID_TLV_INFO_MAGIC',
114+
'INVALID_HASH',
115+
'INVALID_SIGNATURE',
116+
'KEY_MISMATCH',
117+
],
118+
)
114119

115120

116121
def align_up(num, align):
@@ -134,8 +139,11 @@ def add(self, kind, payload):
134139
e = STRUCT_ENDIAN_DICT[self.endian]
135140
if isinstance(kind, int):
136141
if not TLV_VENDOR_RES_MIN <= kind <= TLV_VENDOR_RES_MAX:
137-
msg = f"Invalid custom TLV type value '0x{kind:04x}', allowed " \
138-
f"value should be between 0x{TLV_VENDOR_RES_MIN:04x} and 0x{TLV_VENDOR_RES_MAX:04x}"
142+
msg = (
143+
f"Invalid custom TLV type value '0x{kind:04x}', allowed "
144+
f"value should be between 0x{TLV_VENDOR_RES_MIN:04x} and "
145+
"0x{TLV_VENDOR_RES_MAX:04x}"
146+
)
139147
raise click.UsageError(msg)
140148
buf = struct.pack(e + 'HH', kind, len(payload))
141149
else:
@@ -216,8 +224,8 @@ def key_and_user_sha_to_alg_and_tlv(key, user_sha, is_pure = False):
216224
allowed = allowed_key_ssh[type(key)]
217225

218226
except KeyError:
219-
raise click.UsageError(f"Colud not find allowed hash algorithms for {type(key)}"
220-
)
227+
raise click.UsageError(
228+
f"Could not find allowed hash algorithms for {type(key)}") from None
221229

222230
# Pure enforces auto, and user selection is ignored
223231
if user_sha == 'auto' or is_pure:
@@ -226,8 +234,10 @@ def key_and_user_sha_to_alg_and_tlv(key, user_sha, is_pure = False):
226234
if user_sha in allowed:
227235
return USER_SHA_TO_ALG_AND_TLV[user_sha]
228236

229-
raise click.UsageError(f"Key {key.sig_type()} can not be used with --sha {user_sha}; allowed sha are one of {allowed}"
230-
)
237+
raise click.UsageError(
238+
f"Key {key.sig_type()} can not be used with --sha {user_sha}; "
239+
"allowed sha are one of {allowed}"
240+
) from None
231241

232242

233243
def get_digest(tlv_type, hash_region):
@@ -245,11 +255,12 @@ def tlv_matches_key_type(tlv_type, key):
245255
# return True, on exception we return False.
246256
_, _ = key_and_user_sha_to_alg_and_tlv(key, tlv_sha_to_sha(tlv_type))
247257
return True
248-
except:
258+
except Exception:
249259
pass
250260

251261
return False
252262

263+
253264
def parse_uuid(namespace, value):
254265
# Check if UUID is in the RAW format (12345678-1234-5678-1234-567812345678)
255266
uuid_re = r'[0-9A-f]{8}-[0-9A-f]{4}-[0-9A-f]{4}-[0-9A-f]{4}-[0-9A-f]{12}'
@@ -371,7 +382,7 @@ def load(self, path):
371382
self.infile_data = f.read()
372383
self.payload = copy.copy(self.infile_data)
373384
except FileNotFoundError:
374-
raise click.UsageError("Input file not found")
385+
raise click.UsageError("Input file not found") from None
375386

376387
# Add the image header if needed.
377388
if self.pad_header and self.header_size > 0:
@@ -444,10 +455,13 @@ def save(self, path, hex_addr=None):
444455
f.write(self.payload)
445456

446457
def check_header(self):
447-
if self.header_size > 0 and not self.pad_header:
448-
if any(v != 0 for v in self.payload[0:self.header_size]):
449-
raise click.UsageError("Header padding was not requested and "
450-
"image does not start with zeros")
458+
if (
459+
self.header_size > 0 and not self.pad_header
460+
and any(v != 0 for v in self.payload[0: self.header_size])
461+
):
462+
raise click.UsageError(
463+
"Header padding was not requested and image does not start with zeros"
464+
)
451465

452466
def check_trailer(self):
453467
if self.slot_size > 0:
@@ -719,7 +733,9 @@ def create(self, key, public_key_format, enckey, dependencies=None,
719733
tlv.add(pub_key.sig_tlv(), fixed_sig['value'])
720734
self.signature = fixed_sig['value']
721735
else:
722-
raise click.UsageError("Can not sign using key and provide fixed-signature at the same time")
736+
raise click.UsageError(
737+
"Can not sign using key and provide fixed-signature at the same time"
738+
)
723739

724740
# At this point the image was hashed + signed, we can remove the
725741
# protected TLVs from the payload (will be re-added later)
@@ -738,7 +754,8 @@ def create(self, key, public_key_format, enckey, dependencies=None,
738754
hmac_sha_alg = hashes.SHA256()
739755
elif hmac_sha == '512':
740756
if not isinstance(enckey, x25519.X25519Public):
741-
raise click.UsageError("Currently only ECIES-X25519 supports HMAC-SHA512")
757+
raise click.UsageError(
758+
"Currently only ECIES-X25519 supports HMAC-SHA512")
742759
hmac_sha_alg = hashes.SHA512()
743760
else:
744761
raise click.UsageError("Unsupported HMAC-SHA")
@@ -886,7 +903,7 @@ def verify(imgfile, key):
886903
with open(imgfile, 'rb') as f:
887904
b = f.read()
888905
except FileNotFoundError:
889-
raise click.UsageError(f"Image file {imgfile} not found")
906+
raise click.UsageError(f"Image file {imgfile} not found") from None
890907

891908
magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16])
892909
version = struct.unpack('BBHI', b[20:28])

scripts/imgtool/keys/__init__.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,28 @@
3434
from .rsa import RSA, RSA_KEY_SIZES, RSAPublic, RSAUsageError
3535
from .x25519 import X25519, X25519Public, X25519UsageError
3636

37+
__all__ = [
38+
"ECDSA256P1",
39+
"ECDSA384P1",
40+
"ECDSA256P1Public",
41+
"ECDSA384P1Public",
42+
"ECDSAUsageError",
43+
"Ed25519",
44+
"Ed25519Public",
45+
"Ed25519UsageError",
46+
"RSA",
47+
"RSA_KEY_SIZES",
48+
"RSAPublic",
49+
"RSAUsageError",
50+
"X25519",
51+
"X25519Public",
52+
"X25519UsageError",
53+
]
54+
3755

3856
class PasswordRequired(Exception):
3957
"""Raised to indicate that the key is password protected, but a
4058
password was not specified."""
41-
pass
4259

4360

4461
def load(path, passwd=None):

0 commit comments

Comments
 (0)