Skip to content

Commit

Permalink
Move _calculate_delegation inside HashDelegations
Browse files Browse the repository at this point in the history
Signed-off-by: Martin Vrachev <[email protected]>
  • Loading branch information
MVrachev committed Apr 15, 2022
1 parent f0e4410 commit 47f3de3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 22 deletions.
7 changes: 5 additions & 2 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -796,9 +796,12 @@ def test_find_delegation_with_succinct_hash_info(
expected_rolename = test_data.result
msg = f"Error for {hash_bits} expected {expected_rolename}"

# pylint: disable=protected-access
assert r.succinct_hash_info is not None
self.assertEqual(
r._calculate_delegation(hash_bits), expected_rolename, msg
# pylint: disable=protected-access
r.succinct_hash_info._calculate_delegation(hash_bits),
expected_rolename,
msg,
)


Expand Down
37 changes: 17 additions & 20 deletions tuf/api/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -1319,6 +1319,21 @@ def to_dict(self) -> Dict[str, Any]:
**self.unrecognized_fields,
}

def _calculate_delegation(self, hash_bits_representation: str) -> str:
"""Helper function for find_delegation calculating the actual rolename.
Args:
hash_bits_representation: binary bit representation of the target
hash.
"""

bit_length = self.hash_prefix_len
# Get the first bit_length of bits and then cast them to decimal.
bin_number = int(hash_bits_representation[:bit_length], 2)

name_prefix = self.bin_name_prefix
return f"{name_prefix}-{bin_number}"


class DelegatedRole(Role):
"""A container with information about a delegated role.
Expand Down Expand Up @@ -1475,25 +1490,6 @@ def _is_target_in_pathpattern(targetpath: str, pathpattern: str) -> bool:

return True

def _calculate_delegation(self, hash_bits_representation: str) -> str:
"""Helper function for find_delegation calculating the actual rolename.
Args:
hash_bits_representation: binary bit representation of the target
hash.
"""
if self.succinct_hash_info is None:
raise ValueError(
"succinct_hash_info must be set to calculate the delegation"
)

bit_length = self.succinct_hash_info.hash_prefix_len
# Get the first bit_length of bits and then cast them to decimal.
bin_number = int(hash_bits_representation[:bit_length], 2)

name_prefix = self.succinct_hash_info.bin_name_prefix
return f"{name_prefix}-{bin_number}"

def find_delegation(self, target_filepath: str) -> Optional[str]:
"""Find the delegated rolename based on the given ``target filepath``.
Expand All @@ -1518,7 +1514,8 @@ def find_delegation(self, target_filepath: str) -> Optional[str]:
f"{one_byte:08b}" for one_byte in hasher.digest()
)

return self._calculate_delegation(hash_bits)
# pylint: disable=protected-access
return self.succinct_hash_info._calculate_delegation(hash_bits)

return None

Expand Down

0 comments on commit 47f3de3

Please sign in to comment.