Skip to content

Commit 41fe57f

Browse files
committed
Add generic read_from_json class method to Metadata (WIP)
TODO: Add tests
1 parent 14d455f commit 41fe57f

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

tuf/api/metadata.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,49 @@ def __update_signature(self, signatures, keyid, signature):
117117

118118
# return len(verified_keyids) >= key_ring.threshold.least
119119

120+
def read_from_json(
121+
cls, filename: str,
122+
storage_backend: Optional[StorageBackendInterface] = None
123+
) -> Metadata:
124+
"""Loads json-formatted TUF metadata from a file storage.
125+
126+
Arguments:
127+
filename: The path to read the file from.
128+
storage_backend: An object that implements
129+
securesystemslib.storage.StorageBackendInterface. Per default
130+
a (local) FilesystemBackend is used.
131+
132+
Raises:
133+
IOError: The file cannot be read.
134+
securesystemslib.exceptions.Error, ValueError: The metadata cannot
135+
be parsed.
136+
137+
Returns:
138+
A TUF Metadata object.
139+
140+
"""
141+
signable = load_json_file(filename, storage_backend)
142+
143+
# TODO: Should we use constants?
144+
# And/or maybe a dispatch table? (<-- maybe too much magic)
145+
_type = signable['signed']['_type']
146+
147+
if _type == 'targets':
148+
inner_cls = Targets
149+
elif _type == 'snapshot':
150+
inner_cls = Snapshot
151+
elif _type == 'timestamp':
152+
inner_cls = Timestamp
153+
elif _type == 'root':
154+
# TODO: implement Root class
155+
raise NotImplementedError('Root not yet implemented')
156+
else:
157+
raise ValueError(f'unrecognized metadata type "{_type}"')
158+
159+
return Metadata(
160+
signed=inner_cls(**signable['signed']),
161+
signatures=signable['signatures'])
162+
120163
def write_to_json(
121164
self, filename: str,
122165
storage_backend: StorageBackendInterface = None) -> None:

0 commit comments

Comments
 (0)