1
0
mirror of https://github.com/Mbed-TLS/mbedtls.git synced 2025-07-29 11:41:15 +03:00

refactored and addressed reviewer observations in generate_driver_wrappers.py

Signed-off-by: Asfandyar Orakzai <asfandyar.orakzai@silabs.com>
This commit is contained in:
Asfandyar Orakzai
2022-09-17 22:07:58 +02:00
parent b549776a23
commit de08803170

View File

@ -28,6 +28,7 @@ import argparse
import jsonschema import jsonschema
import jinja2 import jinja2
from mbedtls_dev import build_tree from mbedtls_dev import build_tree
from traceback import format_tb
JSONSchema = NewType('JSONSchema', object) JSONSchema = NewType('JSONSchema', object)
# The Driver is an Object, but practically it's indexable and can called a dictionary to # The Driver is an Object, but practically it's indexable and can called a dictionary to
@ -41,6 +42,12 @@ class JsonValidationException(Exception):
super().__init__(self.message) super().__init__(self.message)
class DriverReaderException(Exception):
def __init__(self, message="Driver Reader Failed"):
self.message = message
super().__init__(self.message)
def render(template_path: str, driver_jsoncontext: list) -> str: def render(template_path: str, driver_jsoncontext: list) -> str:
""" """
Render template from the input file and driver JSON. Render template from the input file and driver JSON.
@ -67,7 +74,7 @@ def generate_driver_wrapper_file(template_dir: str, \
out_file.write(result) out_file.write(result)
def validate_json(driverjson_data: Driver, driverschema_list: dict) -> bool: def validate_json(driverjson_data: Driver, driverschema_list: dict) -> None:
""" """
Validate the Driver JSON against an appropriate schema Validate the Driver JSON against an appropriate schema
the schema passed could be that matching an opaque/ transparent driver. the schema passed could be that matching an opaque/ transparent driver.
@ -77,16 +84,15 @@ def validate_json(driverjson_data: Driver, driverschema_list: dict) -> bool:
try: try:
_schema = driverschema_list[driver_type] _schema = driverschema_list[driver_type]
jsonschema.validate(instance=driverjson_data, schema=_schema) jsonschema.validate(instance=driverjson_data, schema=_schema)
except KeyError as err: except KeyError as err:
# This could happen if the driverjson_data.type does not exist in the passed in schema list # This could happen if the driverjson_data.type does not exist in the provided schema list
# schemas = {'transparent': transparent_driver_schema, 'opaque': opaque_driver_schema} # schemas = {'transparent': transparent_driver_schema, 'opaque': opaque_driver_schema}
# Print onto stdout and stderr. # Print onto stdout and stderr.
print("Unknown Driver type " + driver_type + print("Unknown Driver type " + driver_type +
" for driver " + driver_prefix, str(err)) " for driver " + driver_prefix, str(err))
print("Unknown Driver type " + driver_type + print("Unknown Driver type " + driver_type +
" for driver " + driver_prefix, str(err), file=sys.stderr) " for driver " + driver_prefix, str(err), file=sys.stderr)
return False raise JsonValidationException() from err
except jsonschema.exceptions.ValidationError as err: except jsonschema.exceptions.ValidationError as err:
# Print onto stdout and stderr. # Print onto stdout and stderr.
@ -96,51 +102,60 @@ def validate_json(driverjson_data: Driver, driverschema_list: dict) -> bool:
print("Error: Failed to validate data file: {} using schema: {}." print("Error: Failed to validate data file: {} using schema: {}."
"\n Exception Message: \"{}\"" "\n Exception Message: \"{}\""
" ".format(driverjson_data, _schema, str(err)), file=sys.stderr) " ".format(driverjson_data, _schema, str(err)), file=sys.stderr)
return False raise JsonValidationException() from err
return True
def load_driver(schemas: Dict[str, Any], driver_file: str) -> Any: def load_driver(schemas: Dict[str, Any], driver_file: str) -> Any:
with open(driver_file, 'r') as f: with open(driver_file, 'r') as f:
json_data = json.load(f) json_data = json.load(f)
if not validate_json(json_data, schemas): try:
raise JsonValidationException() validate_json(json_data, schemas)
except JsonValidationException as e:
raise DriverReaderException from e
return json_data return json_data
def read_driver_descriptions(mbedtls_root: str, json_directory: str, \ def load_schemas(mbedtls_root):
jsondriver_list: str) -> Tuple[bool, list]: schema_file_paths = {
'transparent': os.path.join(mbedtls_root,
'scripts',
'data_files',
'driver_jsons',
'driver_transparent_schema.json'),
'opaque': os.path.join(mbedtls_root,
'scripts',
'data_files',
'driver_jsons',
'driver_transparent_schema.json')
}
driver_schema = {}
for key, file_path in schema_file_paths.items():
with open(file_path, 'r') as file:
driver_schema[key] = json.load(file)
return driver_schema
def read_driver_descriptions(mbedtls_root: str,
json_directory: str,
jsondriver_list: str) -> list:
""" """
Merge driver JSON files into a single ordered JSON after validation. Merge driver JSON files into a single ordered JSON after validation.
""" """
result = [] result = []
with open(os.path.join(mbedtls_root, driver_schema = load_schemas(mbedtls_root)
'scripts',
'data_files',
'driver_jsons',
'driver_transparent_schema.json'), 'r') as file:
transparent_driver_schema = json.load(file)
with open(os.path.join(mbedtls_root,
'scripts',
'data_files',
'driver_jsons',
'driver_opaque_schema.json'), 'r') as file:
opaque_driver_schema = json.load(file)
driver_schema = {'transparent': transparent_driver_schema, with open(os.path.join(json_directory, jsondriver_list), 'r') as driver_list_file:
'opaque': opaque_driver_schema} driver_list = json.load(driver_list_file)
with open(os.path.join(json_directory, jsondriver_list), 'r') as driverlistfile:
driver_list = json.load(driverlistfile)
try: return [load_driver(schemas=driver_schema,
result = [load_driver(schemas=driver_schema, driver_file=os.path.join(json_directory, driver_file_name))
driver_file=os.path.join(json_directory, driver_file_name)) for driver_file_name in driver_list]
for driver_file_name in driver_list]
except JsonValidationException as _:
return False, []
return True, result
def trace_exception(e, file=sys.stderr):
print("Exception: type: %s, message: %s, trace: %s" % (
e.__class__, str(e), format_tb(e.__traceback__)
), file)
def main() -> int: def main() -> int:
@ -162,30 +177,29 @@ def main() -> int:
args = parser.parse_args() args = parser.parse_args()
mbedtls_root = os.path.abspath(args.mbedtls_root) mbedtls_root = os.path.abspath(args.mbedtls_root)
if args.template_dir is None:
args.template_dir = os.path.join(mbedtls_root,
'scripts',
'data_files',
'driver_templates')
if args.json_dir is None:
args.json_dir = os.path.join(mbedtls_root,
'scripts',
'data_files',
'driver_jsons')
if args.output_directory is None:
args.output_directory = os.path.join(mbedtls_root, 'library')
output_directory = args.output_directory output_directory = args.output_directory if args.output_directory is not None else \
template_directory = args.template_dir os.path.join(mbedtls_root, 'library')
json_directory = args.json_dir template_directory = args.template_dir if args.template_dir is not None else \
os.path.join(mbedtls_root,
'scripts',
'data_files',
'driver_templates')
json_directory = args.json_dir if args.json_dir is not None else \
os.path.join(mbedtls_root,
'scripts',
'data_files',
'driver_jsons')
# Read and validate list of driver jsons from driverlist.json try:
ret, merged_driver_json = read_driver_descriptions(mbedtls_root, json_directory, # Read and validate list of driver jsons from driverlist.json
'driverlist.json') merged_driver_json = read_driver_descriptions(mbedtls_root,
if ret is False: json_directory,
'driverlist.json')
except DriverReaderException as e:
trace_exception(e)
return 1 return 1
generate_driver_wrapper_file(template_directory, output_directory, merged_driver_json) generate_driver_wrapper_file(template_directory, output_directory, merged_driver_json)
return 0 return 0