cli
cli copied to clipboard
config: Add context manager support for combining load() and save()
From @tsibley on the topic of improvements to config
One thing that might be nice in the future is context manager support for combining
load()andsave(), e.g. something like:with config.open(path = …) as c: c.set("docker", "image", "foo/bar")
where c is the return value of
load(…)(called when the context manager enters) andsave(c, …)is called when the context manager exits.
Wrote this on the back of the napkin, so to speak, while doing something else. Going to stay focused on the task at hand, but this is the gist of it.
@contextmanager
def load_for_update(path: Path = CONFIG) -> ConfigParser:
"""
XXX FIXME
"""
with write_lock():
config = load(path)
try:
yield config
except:
warn(f"Error occurred; changes to {path} not saved!")
raise
else:
debug(f"Saving changes to {path}")
save(config, path)