22import ast
33import json
44import os
5- from typing import Any , Dict , Generator , List , Tuple
5+ from typing import Any , Generator
66
77
88from ocp_resources .resource import Resource # noqa
99
10+ # Cache for resources definitions to avoid reloading the large JSON file
11+ _RESOURCES_DEFINITIONS_CACHE : dict [str , Any ] = {}
12+
1013
1114def _get_api_value_by_type (api_value : str , api_type : str ) -> str :
1215 try :
@@ -23,9 +26,8 @@ def _get_api_value_by_type(api_value: str, api_type: str) -> str:
2326 return api_value
2427
2528
26- def _get_api_group_and_version (bodies : List [Any ]) -> Tuple [str , str ]:
29+ def _get_api_group_and_version (bodies : list [Any ]) -> tuple [str , str ]:
2730 for targets in bodies :
28- targets : ast .AnnAssign | ast .Attribute
2931 if isinstance (targets , ast .AnnAssign ):
3032 api_type = targets .target .id
3133 else :
@@ -39,11 +41,11 @@ def _get_api_group_and_version(bodies: List[Any]) -> Tuple[str, str]:
3941
4042def validate_resource (
4143 cls : ast .ClassDef ,
42- resource_list : List [ Dict [str , Any ]],
44+ resource_list : list [ dict [str , Any ]],
4345 api_value : str ,
4446 api_type : str ,
45- ) -> List [str ]:
46- errors : List [str ] = []
47+ ) -> list [str ]:
48+ errors : list [str ] = []
4749 resource_str : str = "Resource"
4850 namespaced_resource_str : str = "NamespacedResource"
4951 _base_class_error : str = f"Resource { cls .name } must have { resource_str } or { namespaced_resource_str } base class"
@@ -66,7 +68,7 @@ def validate_resource(
6668
6769 namespaced_based : bool = base_class_from [0 ].id == namespaced_resource_str
6870 api_value_name = _get_api_value_by_type (api_value = api_value , api_type = api_type )
69- matched_resource : Dict [str , Any ] = {}
71+ matched_resource : dict [str , Any ] = {}
7072
7173 for resource_dict in resource_list :
7274 _x_kind = resource_dict ["x-kubernetes-group-version-kind" ]
@@ -113,8 +115,8 @@ def resource_file() -> Generator[str, None, None]:
113115 yield os .path .join (root , _file )
114116
115117
116- def parse_resource_file_for_errors (data ) -> List [str ]:
117- errors : List [str ] = []
118+ def parse_resource_file_for_errors (data ) -> list [str ]:
119+ errors : list [str ] = []
118120 _resources_definitions = resources_definitions ()
119121
120122 if data .startswith (
@@ -147,6 +149,9 @@ def parse_resource_file_for_errors(data) -> List[str]:
147149 return errors
148150
149151
150- def resources_definitions () -> Dict [str , Any ]:
151- with open ("class_generator/schema/__resources-mappings.json" ) as fd :
152- return json .load (fd )
152+ def resources_definitions () -> dict [str , Any ]:
153+ global _RESOURCES_DEFINITIONS_CACHE
154+ if not _RESOURCES_DEFINITIONS_CACHE :
155+ with open ("class_generator/schema/__resources-mappings.json" ) as fd :
156+ _RESOURCES_DEFINITIONS_CACHE = json .load (fd )
157+ return _RESOURCES_DEFINITIONS_CACHE
0 commit comments