1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
import dataclasses
import json
import re
from typing import Any, Callable, Dict, List, Union
from torch.onnx._internal.diagnostics.infra import sarif
# A list of types in the SARIF module to support pretty printing.
# This is solely for type annotation for the functions below.
_SarifClass = Union[
sarif.SarifLog,
sarif.Run,
sarif.ReportingDescriptor,
sarif.Result,
]
def _camel_case_to_snake_case(s: str) -> str:
return re.sub(r"([A-Z])", r"_\1", s).lower()
def kebab_case_to_snake_case(s: str) -> str:
return s.replace("-", "_")
def _convert_key(
object: Union[Dict[str, Any], Any], convert: Callable[[str], str]
) -> Union[Dict[str, Any], Any]:
"""Convert and update keys in a dictionary with "convert".
Any value that is a dictionary will be recursively updated.
Any value that is a list will be recursively searched.
Args:
object: The object to update.
convert: The function to convert the keys, e.g. `kebab_case_to_snake_case`.
Returns:
The updated object.
"""
if not isinstance(object, Dict):
return object
new_dict = {}
for k, v in object.items():
new_k = convert(k)
if isinstance(v, Dict):
new_v = _convert_key(v, convert)
elif isinstance(v, List):
new_v = [_convert_key(elem, convert) for elem in v]
else:
new_v = v
new_dict[new_k] = new_v
return new_dict
def sarif_to_json(attr_cls_obj: _SarifClass) -> str:
dict = dataclasses.asdict(attr_cls_obj)
dict = _convert_key(dict, _camel_case_to_snake_case)
return json.dumps(dict, indent=4)
|