aides-spec/aides_spec/replacers/checksums_replacer.py

92 lines
3.3 KiB
Python
Raw Normal View History

2025-01-05 08:37:11 +00:00
from aides_spec.replacers.arch_replacer import ArchReplacer
from aides_spec.replacers.base import BaseReplacer
class ChecksumsReplacer(BaseReplacer):
CHECKSUMS_REPLACEMENTS = {
"b2sums": "blake2b-512",
"sha512sums": "sha512",
"sha384sums": "sha384",
"sha256sums": "sha256",
"sha224sums": "sha224",
"sha1sums": "sha1",
"md5sums": "md5",
}
def process(self):
root_node = self.tree.root_node
sums = self.CHECKSUMS_REPLACEMENTS.keys()
arches = ArchReplacer.ARCH_MAPPING.keys()
checksums = dict()
combinations = {(s, a) for s in sums for a in arches}.union(
{(s, None) for s in sums}
)
def find_replacements(node):
if node.type == "variable_assignment":
var_node = node.child_by_field_name("name")
value_node = node.child_by_field_name("value")
if var_node and value_node:
var_name = self._node_text(var_node)
for sum_part, arch_part in combinations:
if (
sum_part == var_name
if arch_part is None
else f"{sum_part}_{arch_part}" == var_name
):
checksums[(sum_part, arch_part)] = []
for item in value_node.children:
if item.type == "raw_string":
element_text = self._node_text(item)
if (
element_text.startswith("'")
and element_text.endswith("'")
) or (
element_text.startswith('"')
and element_text.endswith('"')
):
# quote_char = element_text[0]
hash = element_text[1:-1]
else:
hash = element_text
chcksm = self.CHECKSUMS_REPLACEMENTS[
sum_part
]
checksums[(sum_part, arch_part)].append(
f"{chcksm}:{hash}"
)
self.replaces.append({"node": node, "content": ""})
for child in node.children:
find_replacements(child)
find_replacements(root_node)
result = dict()
content = ""
for (sum_part, arch_part), hashes in checksums.items():
key = (
f"checksums_{ArchReplacer.ARCH_MAPPING[arch_part]}"
if arch_part
else "checksums"
)
result.setdefault(key, []).extend(hashes)
for key, value in result.items():
content += f"""{key}=(
'{"',\n '".join(value)}'
)"""
self.appends.append({"node": root_node, "content": content})
print(result)
return self._apply_replacements()