33# SPDX-License-Identifier: Apache-2.0
44
55# SPDX-FileContributor: Michael Meinel
6+ # SPDX-FileContributor: Michael Fritzsche
67
78import json
89import os .path
910from pathlib import Path
1011from types import TracebackType
11- from typing import Union
12+ from typing import Optional
1213from typing_extensions import Self
1314
1415from .error import HermesContextError
@@ -42,11 +43,14 @@ def __enter__(self: Self) -> None:
4243 Returns:
4344 None:
4445 """
46+ # check if the cache_dir exists
4547 if self ._cache_dir .is_dir ():
48+ # load all files from the cache dir and cache the contents
4649 for filepath in self ._cache_dir .glob ('*' ):
4750 basename , _ = os .path .splitext (filepath .name )
4851 self ._cached_data [basename ] = json .load (filepath .open ('r' ))
4952
53+ # return the cache object
5054 return self
5155
5256 def __getitem__ (self : Self , item : str ) -> dict :
@@ -59,11 +63,14 @@ def __getitem__(self: Self, item: str) -> dict:
5963 Returns:
6064 dict: The JSON value in the given file.
6165 """
66+ # check whether or not the given file was already loaded
6267 if item not in self ._cached_data :
68+ # construct the file path as well as load and cache the file
6369 filepath = self ._cache_dir / f'{ item } .json'
6470 if filepath .is_file ():
6571 self ._cached_data [item ] = json .load (filepath .open ('r' ))
6672
73+ # return the loaded json
6774 return self ._cached_data [item ]
6875
6976 def __setitem__ (self : Self , key : str , value : dict ) -> None :
@@ -78,13 +85,14 @@ def __setitem__(self: Self, key: str, value: dict) -> None:
7885 Returns:
7986 None:
8087 """
88+ # update the value of the cache
8189 self ._cached_data [key ] = value
8290
8391 def __exit__ (
8492 self : Self ,
85- exc_type : Union [type [BaseException ], None ],
86- exc_val : Union [BaseException , None ],
87- exc_tb : Union [TracebackType , None ]
93+ exc_type : Optional [type [BaseException ]],
94+ exc_val : Optional [BaseException ],
95+ exc_tb : Optional [TracebackType ]
8896 ) -> None :
8997 """
9098 Updates the files from the cache.
@@ -98,9 +106,12 @@ def __exit__(
98106 None:
99107 """
100108 if exc_type is None :
109+ # If the exit did not happen because of an exception:
110+ # create the cache dir (if necessary) and write the cached json data
101111 self ._cache_dir .mkdir (exist_ok = True , parents = True )
102112
103113 for basename , data in self ._cached_data .items ():
114+ # create complete file path and write the data
104115 cachefile = self ._cache_dir / f'{ basename } .json'
105116 json .dump (data , cachefile .open ('w' ))
106117
@@ -158,10 +169,12 @@ def finalize_step(self: Self, step: str) -> None:
158169 ValueError: If no step can be removed.
159170 ValueError: If the given step is not the last one.
160171 """
172+ # check if the given step was prepared last
161173 if len (self ._current_step ) < 1 :
162174 raise ValueError ("There is no step to end." )
163175 if self ._current_step [- 1 ] != step :
164176 raise ValueError (f"Cannot end step { step } while in { self ._current_step [- 1 ]} ." )
177+ # remove the last step (i.e. the given one)
165178 self ._current_step .pop ()
166179
167180 def __getitem__ (self : Self , source_name : str ) -> HermesCache :
@@ -177,7 +190,9 @@ def __getitem__(self: Self, source_name: str) -> HermesCache:
177190 Raises:
178191 HermesContextError: If no step has been prepared (i.e. no current cache dir is set).
179192 """
193+ # check if a step is prepared
180194 if len (self ._current_step ) < 1 :
181195 raise HermesContextError ("Prepare a step first." )
196+ # build the dir of the cache and return the HermesCache for it
182197 subdir = self .cache_dir / self ._current_step [- 1 ] / source_name
183198 return HermesCache (subdir )
0 commit comments