Refactors utils.load_cached_file
* adds a boolean return representing whether file was reloaded * ensures file is actually closed by using a context manager Change-Id: I4d998c34caa6dde65aaf780c188778477b7f6753
This commit is contained in:
@@ -1176,18 +1176,24 @@ def sanitize_hostname(hostname):
|
|||||||
return hostname
|
return hostname
|
||||||
|
|
||||||
|
|
||||||
def read_cached_file(filename, cache_info):
|
def read_cached_file(filename, cache_info, reload_func=None):
|
||||||
"""Return the contents of a file. If the file hasn't changed since the
|
"""Read from a file if it has been modified.
|
||||||
last invocation, a cached version will be returned.
|
|
||||||
|
:param cache_info: dictionary to hold opaque cache.
|
||||||
|
:param reload_func: optional function to be called with data when
|
||||||
|
file is reloaded due to a modification.
|
||||||
|
|
||||||
|
:returns: data from file
|
||||||
|
|
||||||
"""
|
"""
|
||||||
mtime = os.path.getmtime(filename)
|
mtime = os.path.getmtime(filename)
|
||||||
if cache_info and mtime == cache_info.get('mtime', None):
|
if not cache_info or mtime != cache_info.get('mtime'):
|
||||||
return cache_info['data']
|
with open(filename) as fap:
|
||||||
|
cache_info['data'] = fap.read()
|
||||||
data = open(filename).read()
|
cache_info['mtime'] = mtime
|
||||||
cache_info['data'] = data
|
if reload_func:
|
||||||
cache_info['mtime'] = mtime
|
reload_func(cache_info['data'])
|
||||||
return data
|
return cache_info['data']
|
||||||
|
|
||||||
|
|
||||||
@contextlib.contextmanager
|
@contextlib.contextmanager
|
||||||
|
Reference in New Issue
Block a user