Skip to content

Commit

Permalink
Feature/ncsdk 24519 type hinting (#70)
Browse files Browse the repository at this point in the history
refactor (type hinting): add type hinting for manifest.py and payloads.py
refactor (type hinting): add type hinting for envelope.py
refactor (type hinting): add type hinting for authentication.py
refactor (type hinting): add type hinting for common.py
refactor (type hinting): add type hinting for input_output.py

Signed-off-by: Robert Stypa <[email protected]>
  • Loading branch information
robertstypa authored Dec 11, 2023
1 parent 425d339 commit 4eff3f5
Show file tree
Hide file tree
Showing 6 changed files with 81 additions and 83 deletions.
20 changes: 10 additions & 10 deletions suit_generator/input_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def from_json_file(cls, file_name: str) -> dict:
return data

@classmethod
def parse_json_submanifests(cls, data):
def parse_json_submanifests(cls, data: dict) -> dict:
"""Parse sub-manifests."""
if suit_integrated_dependencies.name in data["SUIT_Envelope_Tagged"]:
for key in data["SUIT_Envelope_Tagged"][suit_integrated_dependencies.name]:
Expand All @@ -67,14 +67,14 @@ def to_json_file(cls, file_name: str, data: dict, parse_hierarchy: bool, *args)
json.dump(cls.parse_json_submanifests(data) if parse_hierarchy is True else data, fh, sort_keys=False)

@classmethod
def from_yaml_file(cls, file_name) -> dict:
def from_yaml_file(cls, file_name: str) -> dict:
"""Read yaml file and return dict."""
with open(file_name, "r", encoding=cls.DEFAULT_ENCODING) as fh:
data = yaml.load(fh, Loader=yaml.SafeLoader)
return data

@classmethod
def parse_yaml_submanifests(cls, data):
def parse_yaml_submanifests(cls, data: dict) -> dict:
"""Parse sub-manifest and store as yaml anchors."""
if suit_integrated_dependencies.name in data["SUIT_Envelope_Tagged"]:
if "SUIT_Dependent_Manifests" not in data:
Expand All @@ -92,48 +92,48 @@ def parse_yaml_submanifests(cls, data):
return data

@classmethod
def to_yaml_file(cls, file_name, data, parse_hierarchy: bool, *args) -> None:
def to_yaml_file(cls, file_name: str, data: dict, parse_hierarchy: bool, *args) -> None:
"""Write dict content into yaml file."""
with open(file_name, "w", encoding=cls.DEFAULT_ENCODING) as fh:
yaml.dump(cls.parse_yaml_submanifests(data) if parse_hierarchy is True else data, fh, sort_keys=False)

@classmethod
def to_stdout(cls, file_name, data, parse_hierarchy: bool, *args) -> None:
def to_stdout(cls, file_name: str, data: dict, parse_hierarchy: bool, *args) -> None:
"""Dump as yaml into STDOUT."""
print(
yaml.dump(cls.parse_yaml_submanifests(data) if parse_hierarchy is True else data, sort_keys=False), end=""
)

@classmethod
def from_suit_file(cls, file_name) -> dict:
def from_suit_file(cls, file_name: str) -> dict:
"""Read suit file and return dict."""
with open(file_name, "rb") as fh:
data = fh.read()
suit = SuitEnvelopeTagged.from_cbor(data)
return suit.to_obj()

@classmethod
def from_suit_file_simplified(cls, file_name) -> dict:
def from_suit_file_simplified(cls, file_name: str) -> dict:
"""Read suit file and return dict."""
with open(file_name, "rb") as fh:
data = fh.read()
suit = SuitEnvelopeTaggedSimplified.from_cbor(data)
return suit.to_obj()

@staticmethod
def prepare_suit_data(data) -> bytes:
def prepare_suit_data(data: dict) -> bytes:
"""Convert data to suit format."""
suit_obj = SuitEnvelopeTagged.from_obj(data)
suit_obj.update_severable_digests()
suit_obj.update_digest()
return suit_obj.to_cbor()

def to_suit_file(self, file_name, data, parse_hierarchy) -> None:
def to_suit_file(self, file_name: str, data: dict, parse_hierarchy: bool) -> None:
"""Write dict content into suit file."""
with open(file_name, "wb") as fh:
fh.write(self.prepare_suit_data(data))

def to_suit_file_simplified(self, file_name, data, parse_hierarchy: bool) -> None:
def to_suit_file_simplified(self, file_name: str, data: dict, parse_hierarchy: bool) -> None:
"""Write dict content into suit file."""
with open(file_name, "wb") as fh:
suit_obj = SuitEnvelopeTaggedSimplified.from_obj(data)
Expand Down
8 changes: 4 additions & 4 deletions suit_generator/suit/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,13 @@ class SuitHash:
"cose-alg-shake256": hashes.SHAKE256(32),
}

def __init__(self, hash_name):
def __init__(self, hash_name: str) -> None:
"""Initialize object."""
if hash_name not in self._hash_func.keys():
raise ValueError(f"Unsupported hash algorithm: {hash_name}")
self._hash_name = hash_name

def hash(self, bstr):
def hash(self, bstr: bytes) -> str:
"""Compute hash value."""
func = hashes.Hash(self._hash_func[self._hash_name], backend=default_backend())
func.update(bstr)
Expand Down Expand Up @@ -104,12 +104,12 @@ class SuitDigestExt:
"""Representation of SUIT digest ext."""

@classmethod
def from_cbor(cls, cbstr):
def from_cbor(cls, cbstr: bytes):
"""Restore SUIT representation from passed CBOR string."""
raise ValueError("The extended digest class can be used only with objects")

@classmethod
def from_obj(cls, obj):
def from_obj(cls, obj: dict) -> SuitDigestRaw:
"""Restore SUIT representation from passed object."""
# fixme: workaround to handle suit-text (SuitTextMap) in the manifest, without this workaround obj has
# additional suit-digest-bytes key which is not supported by suit-text (SuitTextMap)
Expand Down
2 changes: 1 addition & 1 deletion suit_generator/suit/envelope.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def update_severable_digests(self):
].value.SuitDigest.SuitDigestRaw[1].value = binascii.a2b_hex(hash_func.hash(object_data))

@classmethod
def return_processed_binary_data(cls, obj: dict | str):
def return_processed_binary_data(cls, obj: dict | str) -> bytes:
"""Return binary SUIT envelope with updated digests."""
if isinstance(obj, dict):
suit_obj = cls.from_obj(obj)
Expand Down
10 changes: 5 additions & 5 deletions suit_generator/suit/manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,15 +132,15 @@ class SuitUUID(SuitBstr):
"""Representation of SUIT UUID identifier."""

@classmethod
def from_cbor(cls, cbstr):
def from_cbor(cls, cbstr: bytes) -> SuitBstr:
"""Restore SUIT representation from passed CBOR."""
# The RFC4122 UUID consists of 16 bytes.
if len(cbstr) != 16:
raise ValueError(f"Unable to construct UUID from: {cbstr.hex()}")
return super().from_cbor(cbstr)

@classmethod
def from_obj(cls, obj):
def from_obj(cls, obj: dict) -> SuitBstr:
"""Restore SUIT representation from passed object."""
if not isinstance(obj, dict):
raise ValueError(f"Expected dict, received: {obj}")
Expand All @@ -165,20 +165,20 @@ def from_obj(cls, obj):
else:
raise ValueError(f"Unable to parse UUID: {obj}")

def to_obj(self):
def to_obj(self) -> dict:
"""Dump SUIT representation to object."""
return {"raw": super().to_obj()}


class SuitImageSize(SuitUint):
"""Representation of SUIT image size parameter."""

def to_obj(self):
def to_obj(self) -> dict:
"""Dump SUIT representation to object."""
return {"raw": super().to_obj()}

@classmethod
def from_obj(cls, obj):
def from_obj(cls, obj: dict) -> SuitUint:
"""Restore SUIT representation from passed object."""
if not isinstance(obj, dict):
raise ValueError(f"Expected dict, received: {obj}")
Expand Down
2 changes: 1 addition & 1 deletion suit_generator/suit/payloads.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class SuitIntegratedPayloadMap(SuitKeyValueUnnamed):
_metadata = Metadata(map={SuitTstr: SuitHex})

@classmethod
def from_obj(cls, obj):
def from_obj(cls, obj: dict) -> SuitKeyValueUnnamed:
"""Restore SUIT representation from passed object."""
ret = {}
for k, v in obj.items():
Expand Down
Loading

0 comments on commit 4eff3f5

Please sign in to comment.