from Daisy.Daisy import Daisy import os import msgpack from watchdog.observers import Observer # TODO: Dumping to cacheFile class Cache: """ In memory collection of Daisy records """ def __init__( self, filepaths=None, cacheFile=None, path: str = "daisy", walk: bool = False, isCatch: bool = False, ): """ Parameters ---------- filepaths Either a list of filepaths to load or None cacheFile Path to a cache file which is a collection of paths to load path: str Path prefix to load records from walk: bool Whether to automatically walk the path and load records isCatch: bool Whether this cache is for catchs """ self.data = {} self.path = path if filepaths != None: for fp in filepaths: fp = path + "/" + fp if os.path.isfile(fp): self.data[fp] = Daisy(fp) elif cacheFile != None: with open(cacheFile, "r") as f: for fp in f.read().split("\n"): self.data[fp] = Daisy(fp) elif walk: for root, dirs, files in os.walk(self.path): for p in dirs + files: if not (".json" in p): if not (".md" in p): tpath = root + "/" + p self.data[tpath] = Daisy(tpath) def create(self, path: str, data: dict): """ Create new record Parameters ---------- path: str Path to create record at data: dict Data to populate record with """ with open(self.path + "/" + path, "wb") as f: f.write(msgpack.dumps(data)) # logging.log(10, "Done creating record") self.data[path] = Daisy(self.path + "/" + path) # logging.log(10, "Done loading to Daisy") return self.data[path] def get(self, path: str): """ Get record at path, else return False path: str Path of record """ if path in self.data.keys(): return self.data[path] else: if os.path.exists(self.path + "/" + path): self.data[path] = Daisy(self.path + "/" + path) return self.data[path] else: # logging.log(10, "File does not exist") return False def refresh(self): """ Reload from disk to memory """ for key in self.data.keys(): self.data[key].read() def search(self, keydict: dict, strict: bool = True): """ Search cache for record for records with values keydict: dict Values to search for strict: bool Whether to require values match """ results = [] for key, val in self.data.items(): val = val.get() if strict and type(val) != str: addcheck = False for k, v in keydict.items(): if k in val.keys(): if v in val[k]: addcheck = True else: addcheck = False break if addcheck: results.append([key, val]) elif type(val) != str: for k, v in keydict.items(): if k in val.keys(): if v in val[k]: results.append([key, val]) return results