Skip to content

Commit 1d81a04

Browse files
committed
Use __future.annotations module
This allows using some more nice annotations from 3.10 while still being compatible with even Python 3.8. These are all annotation changes, should not modify any functionality. Signed-off-by: Jussi Kukkonen <[email protected]>
1 parent 0b351ef commit 1d81a04

26 files changed

+269
-212
lines changed

examples/manual_repo/basic_repo.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
2222
"""
2323

24+
from __future__ import annotations
25+
2426
import os
2527
import tempfile
2628
from datetime import datetime, timedelta, timezone

examples/manual_repo/hashed_bin_delegation.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,14 @@
1616
1717
"""
1818

19+
from __future__ import annotations
20+
1921
import hashlib
2022
import os
2123
import tempfile
22-
from collections.abc import Iterator
2324
from datetime import datetime, timedelta, timezone
2425
from pathlib import Path
26+
from typing import TYPE_CHECKING
2527

2628
from securesystemslib.signer import CryptoSigner, Signer
2729

@@ -34,6 +36,9 @@
3436
)
3537
from tuf.api.serialization.json import JSONSerializer
3638

39+
if TYPE_CHECKING:
40+
from collections.abc import Iterator
41+
3742

3843
def _in(days: float) -> datetime:
3944
"""Adds 'days' to now and returns datetime object w/o microseconds."""

examples/manual_repo/succinct_hash_bin_delegations.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
NOTE: Metadata files will be written to a 'tmp*'-directory in CWD.
1919
"""
2020

21+
from __future__ import annotations
22+
2123
import math
2224
import os
2325
import tempfile

examples/repository/_simplerepo.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@
33

44
"""Simple example of using the repository library to build a repository"""
55

6+
from __future__ import annotations
7+
68
import copy
79
import json
810
import logging
911
from collections import defaultdict
1012
from datetime import datetime, timedelta, timezone
11-
from typing import Union
1213

1314
from securesystemslib.signer import CryptoSigner, Key, Signer
1415

@@ -93,7 +94,7 @@ def snapshot_info(self) -> MetaFile:
9394

9495
def _get_verification_result(
9596
self, role: str, md: Metadata
96-
) -> Union[VerificationResult, RootVerificationResult]:
97+
) -> VerificationResult | RootVerificationResult:
9798
"""Verify roles metadata using the existing repository metadata"""
9899
if role == Root.type:
99100
assert isinstance(md.signed, Root)

examples/uploader/_localrepo.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
"""A Repository implementation for maintainer and developer tools"""
55

6+
from __future__ import annotations
7+
68
import contextlib
79
import copy
810
import json

tests/generated_data/generate_md.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33
# Copyright New York University and the TUF contributors
44
# SPDX-License-Identifier: MIT OR Apache-2.0
55

6+
from __future__ import annotations
7+
68
import os
79
import sys
810
from datetime import datetime, timezone
9-
from typing import Optional
1011

1112
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
1213
from securesystemslib.signer import CryptoSigner, Signer, SSlibKey
@@ -80,7 +81,7 @@ def verify_generation(md: Metadata, path: str) -> None:
8081

8182

8283
def generate_all_files(
83-
dump: Optional[bool] = False, verify: Optional[bool] = False
84+
dump: bool | None = False, verify: bool | None = False
8485
) -> None:
8586
"""Generate a new repository and optionally verify it.
8687

tests/repository_simulator.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,14 @@
4242
updater.refresh()
4343
"""
4444

45+
from __future__ import annotations
46+
4547
import datetime
4648
import logging
4749
import os
4850
import tempfile
49-
from collections.abc import Iterator
5051
from dataclasses import dataclass, field
51-
from typing import Optional
52+
from typing import TYPE_CHECKING
5253
from urllib import parse
5354

5455
import securesystemslib.hash as sslib_hash
@@ -72,6 +73,9 @@
7273
from tuf.api.serialization.json import JSONSerializer
7374
from tuf.ngclient.fetcher import FetcherInterface
7475

76+
if TYPE_CHECKING:
77+
from collections.abc import Iterator
78+
7579
logger = logging.getLogger(__name__)
7680

7781
SPEC_VER = ".".join(SPECIFICATION_VERSION)
@@ -81,8 +85,8 @@
8185
class FetchTracker:
8286
"""Fetcher counter for metadata and targets."""
8387

84-
metadata: list[tuple[str, Optional[int]]] = field(default_factory=list)
85-
targets: list[tuple[str, Optional[str]]] = field(default_factory=list)
88+
metadata: list[tuple[str, int | None]] = field(default_factory=list)
89+
targets: list[tuple[str, str | None]] = field(default_factory=list)
8690

8791

8892
@dataclass
@@ -116,7 +120,7 @@ def __init__(self) -> None:
116120
# Enable hash-prefixed target file names
117121
self.prefix_targets_with_hash = True
118122

119-
self.dump_dir: Optional[str] = None
123+
self.dump_dir: str | None = None
120124
self.dump_version = 0
121125

122126
self.fetch_tracker = FetchTracker()
@@ -201,7 +205,7 @@ def _fetch(self, url: str) -> Iterator[bytes]:
201205
if role == Root.type or (
202206
self.root.consistent_snapshot and ver_and_name != Timestamp.type
203207
):
204-
version: Optional[int] = int(version_str)
208+
version: int | None = int(version_str)
205209
else:
206210
# the file is not version-prefixed
207211
role = ver_and_name
@@ -213,7 +217,7 @@ def _fetch(self, url: str) -> Iterator[bytes]:
213217
target_path = path[len("/targets/") :]
214218
dir_parts, sep, prefixed_filename = target_path.rpartition("/")
215219
# extract the hash prefix, if any
216-
prefix: Optional[str] = None
220+
prefix: str | None = None
217221
filename = prefixed_filename
218222
if self.root.consistent_snapshot and self.prefix_targets_with_hash:
219223
prefix, _, filename = prefixed_filename.partition(".")
@@ -223,9 +227,7 @@ def _fetch(self, url: str) -> Iterator[bytes]:
223227
else:
224228
raise DownloadHTTPError(f"Unknown path '{path}'", 404)
225229

226-
def fetch_target(
227-
self, target_path: str, target_hash: Optional[str]
228-
) -> bytes:
230+
def fetch_target(self, target_path: str, target_hash: str | None) -> bytes:
229231
"""Return data for 'target_path', checking 'target_hash' if it is given.
230232
231233
If hash is None, then consistent_snapshot is not used.
@@ -244,7 +246,7 @@ def fetch_target(
244246
logger.debug("fetched target %s", target_path)
245247
return repo_target.data
246248

247-
def fetch_metadata(self, role: str, version: Optional[int] = None) -> bytes:
249+
def fetch_metadata(self, role: str, version: int | None = None) -> bytes:
248250
"""Return signed metadata for 'role', using 'version' if it is given.
249251
250252
If version is None, non-versioned metadata is being requested.
@@ -261,7 +263,7 @@ def fetch_metadata(self, role: str, version: Optional[int] = None) -> bytes:
261263
return self.signed_roots[version - 1]
262264

263265
# sign and serialize the requested metadata
264-
md: Optional[Metadata]
266+
md: Metadata | None
265267
if role == Timestamp.type:
266268
md = self.md_timestamp
267269
elif role == Snapshot.type:

tests/test_api.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
# SPDX-License-Identifier: MIT OR Apache-2.0
33
"""Unit tests for api/metadata.py"""
44

5+
from __future__ import annotations
6+
57
import json
68
import logging
79
import os
@@ -12,7 +14,7 @@
1214
from copy import copy, deepcopy
1315
from datetime import datetime, timedelta, timezone
1416
from pathlib import Path
15-
from typing import ClassVar, Optional
17+
from typing import ClassVar
1618

1719
from securesystemslib import exceptions as sslib_exceptions
1820
from securesystemslib import hash as sslib_hash
@@ -245,8 +247,8 @@ def from_priv_key_uri(
245247
cls,
246248
priv_key_uri: str,
247249
public_key: Key,
248-
secrets_handler: Optional[SecretsHandler] = None,
249-
) -> "Signer":
250+
secrets_handler: SecretsHandler | None = None,
251+
) -> Signer:
250252
pass
251253

252254
@property

tests/test_examples.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
# SPDX-License-Identifier: MIT OR Apache-2.0
33
"""Unit tests for 'examples' scripts."""
44

5+
from __future__ import annotations
6+
57
import glob
68
import os
79
import shutil

tests/test_metadata_eq_.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
"""Test __eq__ implementations of classes inside tuf/api/metadata.py."""
55

6+
from __future__ import annotations
7+
68
import copy
79
import os
810
import sys
@@ -63,7 +65,7 @@ def setUpClass(cls) -> None:
6365

6466
# Keys are class names.
6567
# Values are dictionaries containing attribute names and their new values.
66-
classes_attributes_modifications: utils.DataSet = {
68+
classes_attributes_modifications = {
6769
"Metadata": {"signed": None, "signatures": None},
6870
"Signed": {"version": -1, "spec_version": "0.0.0"},
6971
"Key": {"keyid": "a", "keytype": "foo", "scheme": "b", "keyval": "b"},

0 commit comments

Comments
 (0)