Skip to content

Commit 0d6ebf8

Browse files
committed
Add missing type annotations to updater
Add missing annotations and partially resolve mypy errors in updater.py and trusted_metadata_set.py Signed-off-by: Teodora Sechkova <[email protected]>
1 parent 9202242 commit 0d6ebf8

File tree

2 files changed

+35
-31
lines changed

2 files changed

+35
-31
lines changed

tuf/ngclient/_internal/trusted_metadata_set.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ def __init__(self, root_data: bytes):
9797
RepositoryError: Metadata failed to load or verify. The actual
9898
error type and content will contain more details.
9999
"""
100-
self._trusted_set = {} # type: Dict[str: Metadata]
100+
self._trusted_set: Dict[str, Metadata] = {}
101101
self.reference_time = datetime.utcnow()
102102
self._root_update_finished = False
103103

@@ -116,7 +116,7 @@ def __len__(self) -> int:
116116

117117
def __iter__(self) -> Iterator[Metadata]:
118118
"""Returns iterator over all Metadata objects in TrustedMetadataSet"""
119-
return iter(self._trusted_set)
119+
return iter(self._trusted_set.values())
120120

121121
# Helper properties for top level metadata
122122
@property
@@ -140,7 +140,7 @@ def targets(self) -> Optional[Metadata]:
140140
return self._trusted_set.get("targets")
141141

142142
# Methods for updating metadata
143-
def update_root(self, data: bytes):
143+
def update_root(self, data: bytes) -> None:
144144
"""Verifies and loads 'data' as new root metadata.
145145
146146
Note that an expired intermediate root is considered valid: expiry is
@@ -183,7 +183,7 @@ def update_root(self, data: bytes):
183183
self._trusted_set["root"] = new_root
184184
logger.debug("Updated root")
185185

186-
def root_update_finished(self):
186+
def root_update_finished(self) -> None:
187187
"""Marks root metadata as final and verifies it is not expired
188188
189189
Raises:
@@ -203,7 +203,7 @@ def root_update_finished(self):
203203
self._root_update_finished = True
204204
logger.debug("Verified final root.json")
205205

206-
def update_timestamp(self, data: bytes):
206+
def update_timestamp(self, data: bytes) -> None:
207207
"""Verifies and loads 'data' as new timestamp metadata.
208208
209209
Args:
@@ -257,7 +257,7 @@ def update_timestamp(self, data: bytes):
257257
self._trusted_set["timestamp"] = new_timestamp
258258
logger.debug("Updated timestamp")
259259

260-
def update_snapshot(self, data: bytes):
260+
def update_snapshot(self, data: bytes) -> None:
261261
"""Verifies and loads 'data' as new snapshot metadata.
262262
263263
Args:
@@ -331,7 +331,7 @@ def update_snapshot(self, data: bytes):
331331
self._trusted_set["snapshot"] = new_snapshot
332332
logger.debug("Updated snapshot")
333333

334-
def update_targets(self, data: bytes):
334+
def update_targets(self, data: bytes) -> None:
335335
"""Verifies and loads 'data' as new top-level targets metadata.
336336
337337
Args:
@@ -345,7 +345,7 @@ def update_targets(self, data: bytes):
345345

346346
def update_delegated_targets(
347347
self, data: bytes, role_name: str, delegator_name: str
348-
):
348+
) -> None:
349349
"""Verifies and loads 'data' as new metadata for target 'role_name'.
350350
351351
Args:

tuf/ngclient/updater.py

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
from securesystemslib import util as sslib_util
6969

7070
from tuf import exceptions
71+
from tuf.api.metadata import DelegatedRole, TargetFile, Targets
7172
from tuf.ngclient._internal import requests_fetcher, trusted_metadata_set
7273
from tuf.ngclient.config import UpdaterConfig
7374
from tuf.ngclient.fetcher import FetcherInterface
@@ -111,12 +112,7 @@ def __init__(
111112
# Read trusted local root metadata
112113
data = self._load_local_metadata("root")
113114
self._trusted_set = trusted_metadata_set.TrustedMetadataSet(data)
114-
115-
if fetcher is None:
116-
self._fetcher = requests_fetcher.RequestsFetcher()
117-
else:
118-
self._fetcher = fetcher
119-
115+
self._fetcher = fetcher or requests_fetcher.RequestsFetcher()
120116
self.config = config or UpdaterConfig()
121117

122118
def refresh(self) -> None:
@@ -143,7 +139,7 @@ def refresh(self) -> None:
143139
self._load_snapshot()
144140
self._load_targets("targets", "root")
145141

146-
def get_one_valid_targetinfo(self, target_path: str) -> Dict:
142+
def get_one_valid_targetinfo(self, target_path: str) -> Dict[str, Any]:
147143
"""Returns target information for 'target_path'.
148144
149145
The return value can be used as an argument to
@@ -199,7 +195,7 @@ def updated_targets(
199195
# 'destination_directory' if 'filepath' contains a leading path
200196
# separator (i.e., is treated as an absolute path).
201197
filepath = target["filepath"]
202-
target_fileinfo: "TargetFile" = target["fileinfo"]
198+
target_fileinfo: TargetFile = target["fileinfo"]
203199

204200
target_filepath = os.path.join(destination_directory, filepath)
205201

@@ -219,10 +215,10 @@ def updated_targets(
219215

220216
def download_target(
221217
self,
222-
targetinfo: Dict,
218+
targetinfo: Dict[str, Any],
223219
destination_directory: str,
224220
target_base_url: Optional[str] = None,
225-
):
221+
) -> None:
226222
"""Downloads the target file specified by 'targetinfo'.
227223
228224
Args:
@@ -238,18 +234,20 @@ def download_target(
238234
TODO: download-related errors
239235
TODO: file write errors
240236
"""
241-
if target_base_url is None and self._target_base_url is None:
242-
raise ValueError(
243-
"target_base_url must be set in either download_target() or "
244-
"constructor"
245-
)
237+
246238
if target_base_url is None:
239+
if self._target_base_url is None:
240+
raise ValueError(
241+
"target_base_url must be set in either "
242+
"download_target() or constructor"
243+
)
244+
247245
target_base_url = self._target_base_url
248246
else:
249247
target_base_url = _ensure_trailing_slash(target_base_url)
250248

251-
target_filepath = targetinfo["filepath"]
252-
target_fileinfo: "TargetFile" = targetinfo["fileinfo"]
249+
target_filepath: str = targetinfo["filepath"]
250+
target_fileinfo: TargetFile = targetinfo["fileinfo"]
253251
full_url = parse.urljoin(target_base_url, target_filepath)
254252

255253
with self._fetcher.download_file(
@@ -280,7 +278,7 @@ def _load_local_metadata(self, rolename: str) -> bytes:
280278
with open(os.path.join(self._dir, f"{rolename}.json"), "rb") as f:
281279
return f.read()
282280

283-
def _persist_metadata(self, rolename: str, data: bytes):
281+
def _persist_metadata(self, rolename: str, data: bytes) -> None:
284282
with open(os.path.join(self._dir, f"{rolename}.json"), "wb") as f:
285283
f.write(data)
286284

@@ -368,7 +366,9 @@ def _load_targets(self, role: str, parent_role: str) -> None:
368366
self._trusted_set.update_delegated_targets(data, role, parent_role)
369367
self._persist_metadata(role, data)
370368

371-
def _preorder_depth_first_walk(self, target_filepath) -> Dict:
369+
def _preorder_depth_first_walk(
370+
self, target_filepath: str
371+
) -> Dict[str, Any]:
372372
"""
373373
Interrogates the tree of target delegations in order of appearance
374374
(which implicitly order trustworthiness), and returns the matching
@@ -396,7 +396,7 @@ def _preorder_depth_first_walk(self, target_filepath) -> Dict:
396396
# The metadata for 'role_name' must be downloaded/updated before
397397
# its targets, delegations, and child roles can be inspected.
398398

399-
role_metadata = self._trusted_set[role_name].signed
399+
role_metadata: Targets = self._trusted_set[role_name].signed
400400
target = role_metadata.targets.get(target_filepath)
401401

402402
# After preorder check, add current role to set of visited roles.
@@ -463,7 +463,9 @@ def _preorder_depth_first_walk(self, target_filepath) -> Dict:
463463
return {"filepath": target_filepath, "fileinfo": target}
464464

465465

466-
def _visit_child_role(child_role: Dict, target_filepath: str) -> str:
466+
def _visit_child_role(
467+
child_role: DelegatedRole, target_filepath: str
468+
) -> Optional[str]:
467469
"""
468470
<Purpose>
469471
Non-public method that determines whether the given 'target_filepath'
@@ -559,7 +561,9 @@ def _visit_child_role(child_role: Dict, target_filepath: str) -> str:
559561
return None
560562

561563

562-
def _get_filepath_hash(target_filepath, hash_function="sha256"):
564+
def _get_filepath_hash(
565+
target_filepath: str, hash_function: str = "sha256"
566+
) -> str:
563567
"""
564568
Calculate the hash of the filepath to determine which bin to find the
565569
target.
@@ -574,6 +578,6 @@ def _get_filepath_hash(target_filepath, hash_function="sha256"):
574578
return target_filepath_hash
575579

576580

577-
def _ensure_trailing_slash(url: str):
581+
def _ensure_trailing_slash(url: str) -> str:
578582
"""Return url guaranteed to end in a slash"""
579583
return url if url.endswith("/") else f"{url}/"

0 commit comments

Comments
 (0)