From 56f16534dd1a0a63f3a5069ca13fe5d5aa7df691 Mon Sep 17 00:00:00 2001 From: Jon Turney Date: Fri, 9 Dec 2022 14:35:37 +0000 Subject: Add a simple wrapper for caching a parsed file until mtime changes --- calm/utils.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/calm/utils.py b/calm/utils.py index fb95cc6..9f75813 100644 --- a/calm/utils.py +++ b/calm/utils.py @@ -125,3 +125,36 @@ def system(args): else: for l in output.decode().splitlines(): logging.info(l) + + +# +# This provides a simple wrapper around a function which takes a pathname as +# it's only parameter. The result is cached as long as the mtime of the +# pathname is unchanged. +# +def mtime_cache(user_function): + sentinel = object() # unique object used to signal cache misses + cache = {} + + def wrapper(key): + # make sure path is absolute + key = os.path.abspath(key) + + (result, mtime) = cache.get(key, (sentinel, 0)) + + new_mtime = os.path.getmtime(key) + + # cache hit + if result is not sentinel: + # cache valid + if new_mtime == mtime: + return result + else: + logging.debug('%s cache invalidated by mtime change' % key) + + # cache miss + result = user_function(key) + cache[key] = (result, new_mtime) + return result + + return wrapper -- cgit v1.2.3