Coverage for mddb_workflow/utils/cache.py: 78%
27 statements
« prev ^ index » next coverage.py v7.11.0, created at 2025-10-29 15:48 +0000
« prev ^ index » next coverage.py v7.11.0, created at 2025-10-29 15:48 +0000
1from mddb_workflow.utils.auxiliar import load_json, save_json
2from mddb_workflow.utils.type_hints import *
4# The cache is used to store data to be reused between different runs
5class Cache:
6 def __init__ (self, cache_file : 'File'):
7 # Save the previous cache file
8 self.file = cache_file
9 # Set an auxiliar file which is used to not overwrite directly the previous cache
10 self._aux_file = cache_file.get_prefixed_file('.aux')
11 # Set a dict to store the actual cached data
12 self.data = {}
13 # Load data from the cache file, if it already exists
14 self.load()
15 # Save the entry for the first time
16 self.save()
18 # Read a value from the cache
19 def retrieve (self, key : str, fallback = None):
20 return self.data.get(key, fallback)
22 # Update the cache and save it to disk
23 def update (self, key : str, value):
24 self.data[key] = value
25 self.save()
27 # Delete a value in the cache
28 def delete (self, key : str):
29 if key not in self.data: return
30 del self.data[key]
31 self.save()
33 # Reset the cache
34 # This is called when some input files are modified
35 def reset (self):
36 self.data = {}
37 self.save()
39 # Load the cache to memory, as a dict
40 def load (self):
41 # Load data from the cache file, if it already exists
42 if not self.file.exists: return
43 # Read the cache in disk
44 self.data = load_json(self.file.path)
46 # Save the cache to disk, as a json file
47 def save (self):
48 # Write entries to disk
49 # Write to the auxiliar file, thus not overwritting the original cache yet
50 save_json(self.data, self._aux_file.path, indent = 4)
51 # If the new cache is successfully written then replace the old one
52 self._aux_file.rename_to(self.file)