Coverage for hdl_registers/parser/yaml.py: 90%
21 statements
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-19 20:51 +0000
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-19 20:51 +0000
1# --------------------------------------------------------------------------------------------------
2# Copyright (c) Lukas Vik. All rights reserved.
3#
4# This file is part of the hdl-registers project, an HDL register generator fast enough to run
5# in real time.
6# https://hdl-registers.com
7# https://github.com/hdl-registers/hdl-registers
8# --------------------------------------------------------------------------------------------------
10# Standard libraries
11from pathlib import Path
12from typing import TYPE_CHECKING, Any, Optional
14# Third party libraries
15import yaml
17# Local folder libraries
18from .parser import RegisterParser
20if TYPE_CHECKING:
21 # First party libraries
22 from hdl_registers.register import Register
23 from hdl_registers.register_list import RegisterList
26def from_yaml(
27 name: str, yaml_file: Path, default_registers: Optional[list["Register"]] = None
28) -> "RegisterList":
29 """
30 Parse a YAML file with register data.
32 Arguments:
33 name: The name of the register list.
34 yaml_file: The YAML file path.
35 default_registers: List of default registers.
37 Return:
38 The resulting register list.
39 """
40 parser = RegisterParser(
41 name=name, source_definition_file=yaml_file, default_registers=default_registers
42 )
43 yaml_data = _load_yaml_file(file_path=yaml_file)
45 return parser.parse(register_data=yaml_data)
48def _load_yaml_file(file_path: Path) -> dict[str, Any]:
49 """
50 Load and parse the YAML data into a dictionary. Raise exceptions if things dont work.
51 """
52 if not file_path.exists():
53 raise FileNotFoundError(f"Requested YAML file does not exist: {file_path}")
55 with open(file_path, encoding="utf-8") as file_handle:
56 try:
57 yaml_dict: dict[str, Any] = yaml.safe_load(file_handle)
58 return yaml_dict
59 except Exception as exception_info:
60 message = f"Error while parsing YAML file {file_path}:\n{exception_info}"
61 raise ValueError(message) from exception_info