cli icon indicating copy to clipboard operation
cli copied to clipboard

config: Add context manager support for combining load() and save()

Open kairstenfay opened this issue 5 years ago • 1 comments

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() and save() , 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) and save(c, …) is called when the context manager exits.

kairstenfay avatar Jul 07 '20 16:07 kairstenfay

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)

tsibley avatar Nov 16 '23 17:11 tsibley