Skip to content

Commit f23154c

Browse files
committed
scripts: Safely fix python files
Uses ruff with --fix to fix python files in this folder Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
1 parent 2ec608c commit f23154c

19 files changed

+107
-132
lines changed

scripts/assemble.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,13 @@
2222

2323
import argparse
2424
import errno
25-
import io
26-
import re
2725
import os
2826
import os.path
2927
import pickle
28+
import re
3029
import sys
3130

31+
3232
def same_keys(a, b):
3333
"""Determine if the dicts a and b have the same keys in them"""
3434
for ak in a.keys():
@@ -42,7 +42,7 @@ def same_keys(a, b):
4242
offset_re = re.compile(r"^#define DT_FLASH_AREA_([0-9A-Z_]+)_OFFSET(_0)?\s+(0x[0-9a-fA-F]+|[0-9]+)$")
4343
size_re = re.compile(r"^#define DT_FLASH_AREA_([0-9A-Z_]+)_SIZE(_0)?\s+(0x[0-9a-fA-F]+|[0-9]+)$")
4444

45-
class Assembly():
45+
class Assembly:
4646
def __init__(self, output, bootdir, edt):
4747
self.find_slots(edt)
4848
try:
@@ -83,7 +83,7 @@ def find_slots(self, edt):
8383
def add_image(self, source, partition):
8484
with open(self.output, 'ab') as ofd:
8585
pos = ofd.tell()
86-
print("partition {}, pos={}, offset={}".format(partition, pos, self.offsets[partition]))
86+
print(f"partition {partition}, pos={pos}, offset={self.offsets[partition]}")
8787
if pos > self.offsets[partition]:
8888
raise Exception("Partitions not in order, unsupported")
8989
if pos < self.offsets[partition]:
@@ -92,16 +92,16 @@ def add_image(self, source, partition):
9292
with open(source, 'rb') as rfd:
9393
ibuf = rfd.read()
9494
if len(ibuf) > self.sizes[partition]:
95-
raise Exception("Image {} is too large for partition".format(source))
95+
raise Exception(f"Image {source} is too large for partition")
9696
ofd.write(ibuf)
9797

9898
def find_board_name(bootdir):
9999
dot_config = os.path.join(bootdir, "zephyr", ".config")
100-
with open(dot_config, "r") as f:
100+
with open(dot_config) as f:
101101
for line in f:
102102
if line.startswith("CONFIG_BOARD="):
103103
return line.split("=", 1)[1].strip('"')
104-
raise Exception("Expected CONFIG_BOARD line in {}".format(dot_config))
104+
raise Exception(f"Expected CONFIG_BOARD line in {dot_config}")
105105

106106
def main():
107107
parser = argparse.ArgumentParser()

scripts/imgtool/boot_record.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,5 +48,5 @@ 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 SwComponent.MEASUREMENT_VALUE == last_key, 'Measurement value is not the last item of the property list'
51+
assert last_key == SwComponent.MEASUREMENT_VALUE, 'Measurement value is not the last item of the property list'
5252
return dumps(properties)

scripts/imgtool/dumpinfo.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
"""
2020
import os.path
2121
import struct
22-
import sys
2322

2423
import click
2524
import yaml
@@ -51,7 +50,7 @@
5150

5251
def parse_enc(key_field_len):
5352
if key_field_len is not None:
54-
return "(len: {}, if BOOT_SWAP_SAVE_ENCTLV is unset)".format(hex(key_field_len))
53+
return f"(len: {hex(key_field_len)}, if BOOT_SWAP_SAVE_ENCTLV is unset)"
5554
else:
5655
return "Image not encrypted"
5756

@@ -69,7 +68,7 @@ def parse_status(status_hex):
6968
def parse_boot_magic(trailer_magic):
7069
magic = ""
7170
for i in range(BOOT_MAGIC_SIZE):
72-
magic += "{0:#04x} ".format(trailer_magic[i])
71+
magic += f"{trailer_magic[i]:#04x} "
7372
if i == (BOOT_MAGIC_SIZE / 2 - 1):
7473
magic += ("\n" + " ")
7574
return magic
@@ -103,16 +102,15 @@ def print_tlv_records(tlv_list):
103102
tlv_type, tlv_length, tlv_data = tlv.keys()
104103

105104
if tlv[tlv_type] in TLV_TYPES:
106-
print(" " * indent, "{}: {} ({})".format(
107-
tlv_type, TLV_TYPES[tlv[tlv_type]], hex(tlv[tlv_type])))
105+
print(" " * indent, f"{tlv_type}: {TLV_TYPES[tlv[tlv_type]]} ({hex(tlv[tlv_type])})")
108106
else:
109107
print(" " * indent, "{}: {} ({})".format(
110108
tlv_type, "UNKNOWN", hex(tlv[tlv_type])))
111-
print(" " * indent, "{}: ".format(tlv_length), hex(tlv[tlv_length]))
112-
print(" " * indent, "{}: ".format(tlv_data), end="")
109+
print(" " * indent, f"{tlv_length}: ", hex(tlv[tlv_length]))
110+
print(" " * indent, f"{tlv_data}: ", end="")
113111

114112
for j, data in enumerate(tlv[tlv_data]):
115-
print("{0:#04x}".format(data), end=" ")
113+
print(f"{data:#04x}", end=" ")
116114
if ((j + 1) % 8 == 0) and ((j + 1) != len(tlv[tlv_data])):
117115
print("\n", end=" " * (indent + 7))
118116
print()
@@ -133,7 +131,7 @@ def dump_imginfo(imgfile, outfile=None, silent=False):
133131
with open(imgfile, "rb") as f:
134132
b = f.read()
135133
except FileNotFoundError:
136-
raise click.UsageError("Image file not found ({})".format(imgfile))
134+
raise click.UsageError(f"Image file not found ({imgfile})")
137135

138136
# Parsing the image header
139137
_header = struct.unpack('IIHHIIBBHI', b[:28])
@@ -268,8 +266,7 @@ def dump_imginfo(imgfile, outfile=None, silent=False):
268266
if value & image.IMAGE_F[flag]:
269267
if flag_string:
270268
flag_string += ("\n" + (" " * 20))
271-
flag_string += "{} ({})".format(
272-
flag, hex(image.IMAGE_F[flag]))
269+
flag_string += f"{flag} ({hex(image.IMAGE_F[flag])})"
273270
value = flag_string
274271

275272
if not isinstance(value, str):
@@ -279,23 +276,23 @@ def dump_imginfo(imgfile, outfile=None, silent=False):
279276

280277
# Image payload
281278
_sectionoff = header["hdr_size"]
282-
frame_header_text = "Payload (offset: {})".format(hex(_sectionoff))
279+
frame_header_text = f"Payload (offset: {hex(_sectionoff)})"
283280
frame_content = "FW image (size: {} Bytes)".format(hex(header["img_size"]))
284281
print_in_frame(frame_header_text, frame_content)
285282

286283
# TLV area
287284
_sectionoff += header["img_size"]
288285
if protected_tlv_size != 0:
289286
# Protected TLV area
290-
section_name = "Protected TLV area (offset: {})".format(hex(_sectionoff))
287+
section_name = f"Protected TLV area (offset: {hex(_sectionoff)})"
291288
print_in_row(section_name)
292289
print("magic: ", hex(tlv_area["tlv_hdr_prot"]["magic"]))
293290
print("area size:", hex(tlv_area["tlv_hdr_prot"]["tlv_tot"]))
294291
print_tlv_records(tlv_area["tlvs_prot"])
295292
print("#" * _LINE_LENGTH)
296293

297294
_sectionoff += protected_tlv_size
298-
section_name = "TLV area (offset: {})".format(hex(_sectionoff))
295+
section_name = f"TLV area (offset: {hex(_sectionoff)})"
299296
print_in_row(section_name)
300297
print("magic: ", hex(tlv_area["tlv_hdr"]["magic"]))
301298
print("area size:", hex(tlv_area["tlv_hdr"]["tlv_tot"]))
@@ -305,8 +302,8 @@ def dump_imginfo(imgfile, outfile=None, silent=False):
305302
if _img_pad_size:
306303
_sectionoff += tlv_area["tlv_hdr"]["tlv_tot"]
307304
_erased_val = b[_sectionoff]
308-
frame_header_text = "Image padding (offset: {})".format(hex(_sectionoff))
309-
frame_content = "padding ({})".format(hex(_erased_val))
305+
frame_header_text = f"Image padding (offset: {hex(_sectionoff)})"
306+
frame_content = f"padding ({hex(_erased_val)})"
310307
print_in_frame(frame_header_text, frame_content)
311308

312309
# Image trailer

scripts/imgtool/image.py

Lines changed: 18 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -20,19 +20,13 @@
2020
Image signing and management.
2121
"""
2222

23-
from . import version as versmod
24-
from .boot_record import create_sw_component_data
25-
import click
2623
import copy
27-
from enum import Enum
28-
import array
29-
from intelhex import IntelHex
3024
import hashlib
31-
import array
3225
import os.path
3326
import re
3427
import struct
3528
import uuid
29+
from collections import namedtuple
3630
from enum import Enum
3731

3832
import click
@@ -46,11 +40,10 @@
4640
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
4741
from intelhex import IntelHex
4842

49-
from . import version as versmod, keys
43+
from . import keys
44+
from . import version as versmod
5045
from .boot_record import create_sw_component_data
51-
from .keys import rsa, ecdsa, x25519
52-
53-
from collections import namedtuple
46+
from .keys import ecdsa, rsa, x25519
5447

5548
IMAGE_MAGIC = 0x96f3b83d
5649
IMAGE_HEADER_SIZE = 32
@@ -125,7 +118,7 @@ def align_up(num, align):
125118
return (num + (align - 1)) & ~(align - 1)
126119

127120

128-
class TLV():
121+
class TLV:
129122
def __init__(self, endian, magic=TLV_INFO_MAGIC):
130123
self.magic = magic
131124
self.buf = bytearray()
@@ -141,9 +134,8 @@ def add(self, kind, payload):
141134
e = STRUCT_ENDIAN_DICT[self.endian]
142135
if isinstance(kind, int):
143136
if not TLV_VENDOR_RES_MIN <= kind <= TLV_VENDOR_RES_MAX:
144-
msg = "Invalid custom TLV type value '0x{:04x}', allowed " \
145-
"value should be between 0x{:04x} and 0x{:04x}".format(
146-
kind, TLV_VENDOR_RES_MIN, 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}"
147139
raise click.UsageError(msg)
148140
buf = struct.pack(e + 'HH', kind, len(payload))
149141
else:
@@ -153,7 +145,7 @@ def add(self, kind, payload):
153145

154146
def get(self):
155147
if len(self.buf) == 0:
156-
return bytes()
148+
return b""
157149
e = STRUCT_ENDIAN_DICT[self.endian]
158150
header = struct.pack(e + 'HH', self.magic, len(self))
159151
return header + bytes(self.buf)
@@ -177,7 +169,7 @@ def get(self):
177169

178170

179171
def is_sha_tlv(tlv):
180-
return tlv in TLV_SHA_TO_SHA_AND_ALG.keys()
172+
return tlv in TLV_SHA_TO_SHA_AND_ALG
181173

182174

183175
def tlv_sha_to_sha(tlv):
@@ -224,8 +216,8 @@ def key_and_user_sha_to_alg_and_tlv(key, user_sha, is_pure = False):
224216
allowed = allowed_key_ssh[type(key)]
225217

226218
except KeyError:
227-
raise click.UsageError("Colud not find allowed hash algorithms for {}"
228-
.format(type(key)))
219+
raise click.UsageError(f"Colud not find allowed hash algorithms for {type(key)}"
220+
)
229221

230222
# Pure enforces auto, and user selection is ignored
231223
if user_sha == 'auto' or is_pure:
@@ -234,8 +226,8 @@ def key_and_user_sha_to_alg_and_tlv(key, user_sha, is_pure = False):
234226
if user_sha in allowed:
235227
return USER_SHA_TO_ALG_AND_TLV[user_sha]
236228

237-
raise click.UsageError("Key {} can not be used with --sha {}; allowed sha are one of {}"
238-
.format(key.sig_type(), user_sha, allowed))
229+
raise click.UsageError(f"Key {key.sig_type()} can not be used with --sha {user_sha}; allowed sha are one of {allowed}"
230+
)
239231

240232

241233
def get_digest(tlv_type, hash_region):
@@ -461,9 +453,8 @@ def check_trailer(self):
461453
self.save_enctlv, self.enctlv_len)
462454
padding = self.slot_size - (len(self.payload) + tsize)
463455
if padding < 0:
464-
msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds " \
465-
"requested size 0x{:x}".format(
466-
len(self.payload), tsize, self.slot_size)
456+
msg = f"Image size (0x{len(self.payload):x}) + trailer (0x{tsize:x}) exceeds " \
457+
f"requested size 0x{self.slot_size:x}"
467458
raise click.UsageError(msg)
468459

469460
def ecies_hkdf(self, enckey, plainkey, hmac_sha_alg):
@@ -550,9 +541,8 @@ def create(self, key, public_key_format, enckey, dependencies=None,
550541

551542
if sw_type is not None:
552543
if len(sw_type) > MAX_SW_TYPE_LENGTH:
553-
msg = "'{}' is too long ({} characters) for sw_type. Its " \
554-
"maximum allowed length is 12 characters.".format(
555-
sw_type, len(sw_type))
544+
msg = f"'{sw_type}' is too long ({len(sw_type)} characters) for sw_type. Its " \
545+
"maximum allowed length is 12 characters."
556546
raise click.UsageError(msg)
557547

558548
image_version = (str(self.version.major) + '.'
@@ -853,8 +843,7 @@ def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey,
853843
return self.max_align * 2 + magic_align_size
854844
else:
855845
if write_size not in set([1, 2, 4, 8, 16, 32]):
856-
raise click.BadParameter("Invalid alignment: {}".format(
857-
write_size))
846+
raise click.BadParameter(f"Invalid alignment: {write_size}")
858847
m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors
859848
trailer = m * 3 * write_size # status area
860849
if enckey is not None:

scripts/imgtool/keys/__init__.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,19 +21,17 @@
2121

2222
from cryptography.hazmat.backends import default_backend
2323
from cryptography.hazmat.primitives import serialization
24-
from cryptography.hazmat.primitives.asymmetric.rsa import (
25-
RSAPrivateKey, RSAPublicKey)
2624
from cryptography.hazmat.primitives.asymmetric.ec import (
27-
EllipticCurvePrivateKey, EllipticCurvePublicKey)
28-
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
29-
Ed25519PrivateKey, Ed25519PublicKey)
30-
from cryptography.hazmat.primitives.asymmetric.x25519 import (
31-
X25519PrivateKey, X25519PublicKey)
25+
EllipticCurvePrivateKey,
26+
EllipticCurvePublicKey,
27+
)
28+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
29+
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey
30+
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
3231

33-
from .rsa import RSA, RSAPublic, RSAUsageError, RSA_KEY_SIZES
34-
from .ecdsa import (ECDSA256P1, ECDSA256P1Public,
35-
ECDSA384P1, ECDSA384P1Public, ECDSAUsageError)
32+
from .ecdsa import ECDSA256P1, ECDSA384P1, ECDSA256P1Public, ECDSA384P1Public, ECDSAUsageError
3633
from .ed25519 import Ed25519, Ed25519Public, Ed25519UsageError
34+
from .rsa import RSA, RSA_KEY_SIZES, RSAPublic, RSAUsageError
3735
from .x25519 import X25519, X25519Public, X25519UsageError
3836

3937

scripts/imgtool/keys/ecdsa.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
# SPDX-License-Identifier: Apache-2.0
66
import os.path
7-
import hashlib
87

98
from cryptography.hazmat.backends import default_backend
109
from cryptography.hazmat.primitives import serialization
@@ -27,7 +26,7 @@ def __init__(self, key):
2726
self.key = key
2827

2928
def _unsupported(self, name):
30-
raise ECDSAUsageError("Operation {} requires private key".format(name))
29+
raise ECDSAUsageError(f"Operation {name} requires private key")
3130

3231
def _get_public(self):
3332
return self.key

scripts/imgtool/keys/ecdsa_test.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@
1616

1717
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
1818

19-
from imgtool.keys import load, ECDSA256P1, ECDSAUsageError
19+
from imgtool.keys import ECDSA256P1, ECDSAUsageError, load
20+
2021

2122
class EcKeyGeneration(unittest.TestCase):
2223

scripts/imgtool/keys/ed25519.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def shortname(self):
2222
return "ed25519"
2323

2424
def _unsupported(self, name):
25-
raise Ed25519UsageError("Operation {} requires private key".format(name))
25+
raise Ed25519UsageError(f"Operation {name} requires private key")
2626

2727
def _get_public(self):
2828
return self.key
@@ -87,8 +87,7 @@ def _get_public(self):
8787
return self.key.public_key()
8888

8989
def get_private_bytes(self, minimal, format):
90-
raise Ed25519UsageError("Operation not supported with {} keys".format(
91-
self.shortname()))
90+
raise Ed25519UsageError(f"Operation not supported with {self.shortname()} keys")
9291

9392
def export_private(self, path, passwd=None):
9493
"""

scripts/imgtool/keys/ed25519_test.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,10 @@
1212
import unittest
1313

1414
from cryptography.exceptions import InvalidSignature
15-
from cryptography.hazmat.primitives.asymmetric import ed25519
1615

1716
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
1817

19-
from imgtool.keys import load, Ed25519, Ed25519UsageError
18+
from imgtool.keys import Ed25519, Ed25519UsageError, load
2019

2120

2221
class Ed25519KeyGeneration(unittest.TestCase):

0 commit comments

Comments
 (0)