Coverage for hdl_registers/parser/json.py: 91%

22 statements  

« prev     ^ index     » next       coverage.py v7.6.8, created at 2024-12-01 20:50 +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# -------------------------------------------------------------------------------------------------- 

9 

10# Standard libraries 

11import json 

12from pathlib import Path 

13from typing import TYPE_CHECKING, Any, Optional 

14 

15# Third party libraries 

16from tsfpga.system_utils import read_file 

17 

18# Local folder libraries 

19from .parser import RegisterParser 

20 

21if TYPE_CHECKING: 

22 # First party libraries 

23 from hdl_registers.register import Register 

24 from hdl_registers.register_list import RegisterList 

25 

26 

27def from_json( 

28 name: str, json_file: Path, default_registers: Optional[list["Register"]] = None 

29) -> "RegisterList": 

30 """ 

31 Parse a JSON file with register data. 

32 

33 Arguments: 

34 name: The name of the register list. 

35 json_file: The JSON file path. 

36 default_registers: List of default registers. 

37 

38 Return: 

39 The resulting register list. 

40 """ 

41 parser = RegisterParser( 

42 name=name, source_definition_file=json_file, default_registers=default_registers 

43 ) 

44 json_data = _load_json_file(file_path=json_file) 

45 

46 return parser.parse(register_data=json_data) 

47 

48 

49def _load_json_file(file_path: Path) -> dict[str, Any]: 

50 """ 

51 Load and parse the JSON data into a dictionary. Raise exceptions if things dont work. 

52 """ 

53 if not file_path.exists(): 

54 raise FileNotFoundError(f"Requested JSON file does not exist: {file_path}") 

55 

56 raw_json = read_file(file_path) 

57 try: 

58 json_dict: dict[str, Any] = json.loads(raw_json) 

59 return json_dict 

60 except Exception as exception_info: 

61 message = f"Error while parsing JSON file {file_path}:\n{exception_info}" 

62 raise ValueError(message) from exception_info