Skip to content

Commit 9a45179

Browse files
authored
Merge pull request #836 from L77H/UP-ruleset-ruff-linter
pyupgrade "UP" linting rules integration, code fixes to comply
2 parents 22b126c + 0e16ce0 commit 9a45179

File tree

13 files changed

+76
-99
lines changed

13 files changed

+76
-99
lines changed

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ lint.select = [
7676
"F", # ruff default
7777
"I", # isort: all
7878
"PL", # pylint: all
79+
"UP", # pyupgrade: all
7980
"S", # flake8-bandit: all
8081
"N", # pep8-naming: all
8182
"RUF100" # ruff: find unused noqa

securesystemslib/_gpg/common.py

Lines changed: 34 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,8 @@ def parse_pubkey_payload(data):
105105
ptr += 1
106106
if version_number not in SUPPORTED_PUBKEY_PACKET_VERSIONS:
107107
raise PacketVersionNotSupportedError(
108-
"Pubkey packet version '{}' not supported, must be one of {}".format(
109-
version_number, SUPPORTED_PUBKEY_PACKET_VERSIONS
110-
)
108+
f"Pubkey packet version '{version_number}' not supported, "
109+
f"must be one of {SUPPORTED_PUBKEY_PACKET_VERSIONS}"
111110
)
112111

113112
# NOTE: Uncomment this line to decode the time of creation
@@ -130,10 +129,10 @@ def parse_pubkey_payload(data):
130129
# as described in section 5.2.3.21.
131130
if algorithm not in SUPPORTED_SIGNATURE_ALGORITHMS:
132131
raise SignatureAlgorithmNotSupportedError(
133-
"Signature algorithm '{}' not "
132+
f"Signature algorithm '{algorithm}' not "
134133
"supported, please verify that your gpg configuration is creating "
135134
"either DSA, RSA, or EdDSA signatures (see RFC4880 9.1. Public-Key "
136-
"Algorithms).".format(algorithm)
135+
"Algorithms)."
137136
)
138137

139138
keyinfo["type"] = SUPPORTED_SIGNATURE_ALGORITHMS[algorithm]["type"]
@@ -216,8 +215,8 @@ def parse_pubkey_bundle(data):
216215
and not key_bundle[PACKET_TYPE_PRIMARY_KEY]["key"]
217216
):
218217
raise PacketParsingError(
219-
"First packet must be a primary key ('{}'), "
220-
"got '{}'.".format(PACKET_TYPE_PRIMARY_KEY, packet_type)
218+
"First packet must be a primary key "
219+
f"('{PACKET_TYPE_PRIMARY_KEY}'), got '{packet_type}'."
221220
)
222221

223222
if (
@@ -281,26 +280,23 @@ def parse_pubkey_bundle(data):
281280
)
282281

283282
else:
283+
packets_list = [
284+
PACKET_TYPE_PRIMARY_KEY,
285+
PACKET_TYPE_USER_ID,
286+
PACKET_TYPE_USER_ATTR,
287+
PACKET_TYPE_SUB_KEY,
288+
PACKET_TYPE_SIGNATURE,
289+
]
284290
log.info(
285-
"Ignoring gpg key packet '{}', we only handle packets of "
286-
"types '{}' (see RFC4880 4.3. Packet Tags).".format(
287-
packet_type,
288-
[
289-
PACKET_TYPE_PRIMARY_KEY,
290-
PACKET_TYPE_USER_ID,
291-
PACKET_TYPE_USER_ATTR,
292-
PACKET_TYPE_SUB_KEY,
293-
PACKET_TYPE_SIGNATURE,
294-
],
295-
)
291+
f"Ignoring gpg key packet '{packet_type}', "
292+
"we only handle packets of "
293+
f"types '{packets_list}' (see RFC4880 4.3. Packet Tags)."
296294
)
297295

298296
# Both errors might be raised in parse_packet_header and in this loop
299297
except (PacketParsingError, IndexError) as e:
300298
raise PacketParsingError(
301-
"Invalid public key data at position {}: {}.".format(
302-
position, e
303-
)
299+
f"Invalid public key data at position {position}: {e}."
304300
)
305301

306302
# Go to next packet
@@ -610,9 +606,7 @@ def get_pubkey_bundle(data, keyid):
610606
"""
611607
if not data:
612608
raise KeyNotFoundError(
613-
"Could not find gpg key '{}' in empty exported key " "data.".format(
614-
keyid
615-
)
609+
f"Could not find gpg key '{keyid}' in empty exported key data."
616610
)
617611

618612
# Parse out master key and subkeys (enriched and verified via certificates
@@ -643,7 +637,7 @@ def get_pubkey_bundle(data, keyid):
643637

644638
else:
645639
raise KeyNotFoundError(
646-
"Could not find gpg key '{}' in exported key data.".format(keyid)
640+
f"Could not find gpg key '{keyid}' in exported key data."
647641
)
648642

649643
# Add subkeys dictionary to master pubkey "subkeys" field if subkeys exist
@@ -724,8 +718,8 @@ def parse_signature_packet(
724718
ptr += 1
725719
if version_number not in SUPPORTED_SIGNATURE_PACKET_VERSIONS:
726720
raise ValueError(
727-
"Signature version '{}' not supported, must be one of "
728-
"{}.".format(version_number, SUPPORTED_SIGNATURE_PACKET_VERSIONS)
721+
f"Signature version '{version_number}' not supported, "
722+
f"must be one of {SUPPORTED_SIGNATURE_PACKET_VERSIONS}."
729723
)
730724

731725
# Per default we only parse "signatures of a binary document". Other types
@@ -737,21 +731,20 @@ def parse_signature_packet(
737731

738732
if signature_type not in supported_signature_types:
739733
raise ValueError(
740-
"Signature type '{}' not supported, must be one of {} "
741-
"(see RFC4880 5.2.1. Signature Types).".format(
742-
signature_type, supported_signature_types
743-
)
734+
f"Signature type '{signature_type}' not supported, "
735+
f"must be one of {supported_signature_types} "
736+
"(see RFC4880 5.2.1. Signature Types)."
744737
)
745738

746739
signature_algorithm = data[ptr]
747740
ptr += 1
748741

749742
if signature_algorithm not in SUPPORTED_SIGNATURE_ALGORITHMS:
750743
raise ValueError(
751-
"Signature algorithm '{}' not "
744+
f"Signature algorithm '{signature_algorithm}' not "
752745
"supported, please verify that your gpg configuration is creating "
753746
"either DSA, RSA, or EdDSA signatures (see RFC4880 9.1. Public-Key "
754-
"Algorithms).".format(signature_algorithm)
747+
"Algorithms)."
755748
)
756749

757750
key_type = SUPPORTED_SIGNATURE_ALGORITHMS[signature_algorithm]["type"]
@@ -762,10 +755,9 @@ def parse_signature_packet(
762755

763756
if hash_algorithm not in supported_hash_algorithms:
764757
raise ValueError(
765-
"Hash algorithm '{}' not supported, must be one of {}"
766-
" (see RFC4880 9.4. Hash Algorithms).".format(
767-
hash_algorithm, supported_hash_algorithms
768-
)
758+
f"Hash algorithm '{hash_algorithm}' not supported, "
759+
f"must be one of {supported_hash_algorithms} "
760+
"(see RFC4880 9.4. Hash Algorithms)."
769761
)
770762

771763
# Obtain the hashed octets
@@ -863,11 +855,10 @@ def parse_signature_packet(
863855
if keyid and not keyid.endswith(short_keyid): # pragma: no cover
864856
raise ValueError(
865857
"This signature packet seems to be corrupted. The key ID "
866-
"'{}' of the 'Issuer' subpacket must match the lower 64 bits of the "
867-
"fingerprint '{}' of the 'Issuer Fingerprint' subpacket (see RFC4880 "
868-
"and rfc4880bis-06 5.2.3.28. Issuer Fingerprint).".format(
869-
short_keyid, keyid
870-
)
858+
f"'{short_keyid}' of the 'Issuer' subpacket must match the "
859+
f"lower 64 bits of the fingerprint '{keyid}' of the 'Issuer "
860+
"Fingerprint' subpacket (see RFC4880 and rfc4880bis-06 5.2.3.28. "
861+
"Issuer Fingerprint)."
871862
)
872863

873864
if not info["creation_time"]: # pragma: no cover
@@ -886,7 +877,7 @@ def parse_signature_packet(
886877
signature = handler.get_signature_params(data[ptr:])
887878

888879
signature_data = {
889-
"keyid": "{}".format(keyid),
880+
"keyid": keyid,
890881
"other_headers": binascii.hexlify(data[:other_headers_ptr]).decode(
891882
"ascii"
892883
),

securesystemslib/_gpg/eddsa.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,8 @@ def get_pubkey_params(data):
7979
# See 9.2. ECC Curve OID
8080
if curve_oid != ED25519_PUBLIC_KEY_OID:
8181
raise PacketParsingError(
82-
"bad ed25519 curve OID '{}', expected {}'".format(
83-
curve_oid, ED25519_PUBLIC_KEY_OID
84-
)
82+
f"bad ed25519 curve OID '{curve_oid}', "
83+
f"expected {ED25519_PUBLIC_KEY_OID}'"
8584
)
8685

8786
# See 13.3. EdDSA Point Format
@@ -90,19 +89,17 @@ def get_pubkey_params(data):
9089

9190
if public_key_len != ED25519_PUBLIC_KEY_LENGTH:
9291
raise PacketParsingError(
93-
"bad ed25519 MPI length '{}', expected {}'".format(
94-
public_key_len, ED25519_PUBLIC_KEY_LENGTH
95-
)
92+
f"bad ed25519 MPI length '{public_key_len}', "
93+
f"expected {ED25519_PUBLIC_KEY_LENGTH}'"
9694
)
9795

9896
public_key_prefix = data[ptr]
9997
ptr += 1
10098

10199
if public_key_prefix != ED25519_PUBLIC_KEY_PREFIX:
102100
raise PacketParsingError(
103-
"bad ed25519 MPI prefix '{}', expected '{}'".format(
104-
public_key_prefix, ED25519_PUBLIC_KEY_PREFIX
105-
)
101+
f"bad ed25519 MPI prefix '{public_key_prefix}', "
102+
f"expected '{ED25519_PUBLIC_KEY_PREFIX}'"
106103
)
107104

108105
public_key = data[ptr : ptr + public_key_len - 1]

securesystemslib/_gpg/exceptions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ class SignatureAlgorithmNotSupportedError(Exception):
4040

4141
class KeyExpirationError(Exception):
4242
def __init__(self, key):
43-
super(KeyExpirationError, self).__init__()
43+
super().__init__()
4444
self.key = key
4545

4646
def __str__(self):

securesystemslib/_gpg/functions.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -104,11 +104,11 @@ def create_signature(content, keyid=None, homedir=None, timeout=GPG_TIMEOUT):
104104

105105
keyarg = ""
106106
if keyid:
107-
keyarg = "--local-user {}".format(keyid)
107+
keyarg = f"--local-user {keyid}"
108108

109109
homearg = ""
110110
if homedir:
111-
homearg = "--homedir {}".format(homedir).replace("\\", "/")
111+
homearg = f"--homedir {homedir}".replace("\\", "/")
112112

113113
command = gpg_sign_command(keyarg=keyarg, homearg=homearg)
114114

@@ -125,12 +125,9 @@ def create_signature(content, keyid=None, homedir=None, timeout=GPG_TIMEOUT):
125125
# https://lists.gnupg.org/pipermail/gnupg-devel/2005-December/022559.html
126126
if gpg_process.returncode != 0:
127127
raise OSError(
128-
"Command '{}' returned "
129-
"non-zero exit status '{}', stderr was:\n{}.".format(
130-
gpg_process.args,
131-
gpg_process.returncode,
132-
gpg_process.stderr.decode(),
133-
)
128+
f"Command '{gpg_process.args}' returned "
129+
f"non-zero exit status '{gpg_process.returncode}', "
130+
f"stderr was:\n{gpg_process.stderr.decode()}."
134131
)
135132

136133
signature_data = gpg_process.stdout
@@ -146,9 +143,10 @@ def create_signature(content, keyid=None, homedir=None, timeout=GPG_TIMEOUT):
146143
if not signature["keyid"]: # pragma: no cover
147144
log.warning(
148145
"The created signature does not include the hashed subpacket"
149-
" '33' (full keyid). You probably have a gpg version <{}."
146+
" '33' (full keyid). You probably have a gpg version"
147+
f" <{FULLY_SUPPORTED_MIN_VERSION}."
150148
" We will export the public keys associated with the short keyid to"
151-
" compute the full keyid.".format(FULLY_SUPPORTED_MIN_VERSION)
149+
" compute the full keyid."
152150
)
153151

154152
short_keyid = signature["short_keyid"]
@@ -173,9 +171,7 @@ def create_signature(content, keyid=None, homedir=None, timeout=GPG_TIMEOUT):
173171
# If there is still no full keyid something went wrong
174172
if not signature["keyid"]: # pragma: no cover
175173
raise ValueError(
176-
"Full keyid could not be determined for signature '{}'".format(
177-
signature
178-
)
174+
f"Full keyid could not be determined for signature '{signature}'"
179175
)
180176

181177
# It is okay now to remove the optional short keyid to save space
@@ -275,7 +271,7 @@ def export_pubkey(keyid, homedir=None, timeout=GPG_TIMEOUT):
275271

276272
homearg = ""
277273
if homedir:
278-
homearg = "--homedir {}".format(homedir).replace("\\", "/")
274+
homearg = f"--homedir {homedir}".replace("\\", "/")
279275

280276
# TODO: Consider adopting command error handling from `create_signature`
281277
# above, e.g. in a common 'run gpg command' utility function

securesystemslib/_gpg/util.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -207,9 +207,7 @@ def parse_packet_header(data, expected_type=None): # noqa: PLR0912
207207

208208
if expected_type is not None and packet_type != expected_type:
209209
raise PacketParsingError(
210-
"Expected packet " "{}, but got {} instead!".format(
211-
expected_type, packet_type
212-
)
210+
f"Expected packet {expected_type}, but got {packet_type} instead!"
213211
)
214212

215213
return packet_type, header_len, body_len, header_len + body_len
@@ -349,8 +347,7 @@ def get_hashing_class(hash_algorithm_id):
349347

350348
except KeyError:
351349
raise ValueError(
352-
"Hash algorithm '{}' not supported, must be one of '{}' "
353-
"(see RFC4880 9.4. Hash Algorithms).".format(
354-
hash_algorithm_id, supported_hashing_algorithms
355-
)
350+
f"Hash algorithm '{hash_algorithm_id}' not supported, "
351+
f"must be one of '{supported_hashing_algorithms}' "
352+
"(see RFC4880 9.4. Hash Algorithms)."
356353
)

securesystemslib/formats.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def _canonical_string_encoder(string):
4242
A string with the canonical-encoded 'string' embedded.
4343
"""
4444

45-
string = '"%s"' % string.replace("\\", "\\\\").replace('"', '\\"')
45+
string = '"{}"'.format(string.replace("\\", "\\\\").replace('"', '\\"'))
4646

4747
return string
4848

securesystemslib/hash.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@
4949

5050
SUPPORTED_LIBRARIES.append("pyca_crypto")
5151

52-
class PycaDiggestWrapper(object):
52+
class PycaDiggestWrapper:
5353
"""
5454
<Purpose>
5555
A wrapper around `cryptography.hazmat.primitives.hashes.Hash` which adds

securesystemslib/storage.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ def get(self, filepath: str) -> Iterator[BinaryIO]:
200200
file_object = open(filepath, "rb")
201201
yield file_object
202202
except OSError:
203-
raise exceptions.StorageError("Can't open %s" % filepath)
203+
raise exceptions.StorageError(f"Can't open {filepath}")
204204
finally:
205205
if file_object is not None:
206206
file_object.close()
@@ -244,7 +244,7 @@ def put(
244244
destination_file.flush()
245245
os.fsync(destination_file.fileno())
246246
except OSError:
247-
raise exceptions.StorageError("Can't write file %s" % filepath)
247+
raise exceptions.StorageError(f"Can't write file {filepath}")
248248

249249
def remove(self, filepath: str) -> None:
250250
try:
@@ -254,13 +254,13 @@ def remove(self, filepath: str) -> None:
254254
PermissionError,
255255
OSError,
256256
): # pragma: no cover
257-
raise exceptions.StorageError("Can't remove file %s" % filepath)
257+
raise exceptions.StorageError(f"Can't remove file {filepath}")
258258

259259
def getsize(self, filepath: str) -> int:
260260
try:
261261
return os.path.getsize(filepath)
262262
except OSError:
263-
raise exceptions.StorageError("Can't access file %s" % filepath)
263+
raise exceptions.StorageError(f"Can't access file {filepath}")
264264

265265
def create_folder(self, filepath: str) -> None:
266266
try:
@@ -277,11 +277,11 @@ def create_folder(self, filepath: str) -> None:
277277
)
278278
else:
279279
raise exceptions.StorageError(
280-
"Can't create folder at %s" % filepath
280+
f"Can't create folder at {filepath}"
281281
)
282282

283283
def list_folder(self, filepath: str) -> List[str]:
284284
try:
285285
return os.listdir(filepath)
286286
except FileNotFoundError:
287-
raise exceptions.StorageError("Can't list folder at %s" % filepath)
287+
raise exceptions.StorageError(f"Can't list folder at {filepath}")

tests/check_azure_signer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def test_azure_sign(self):
3939
Note that this test requires valid credentials available.
4040
"""
4141

42-
data = "data".encode("utf-8")
42+
data = b"data"
4343

4444
signer = Signer.from_priv_key_uri(self.azure_id, self.azure_pubkey)
4545
sig = signer.sign(data)

0 commit comments

Comments
 (0)