diff options
Diffstat (limited to 'openstack')
| -rw-r--r-- | openstack/common/fileutils.py | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/openstack/common/fileutils.py b/openstack/common/fileutils.py index bb2ef61..0c967da 100644 --- a/openstack/common/fileutils.py +++ b/openstack/common/fileutils.py @@ -16,9 +16,11 @@ # under the License. +import contextlib import errno import os +from openstack.common import excutils from openstack.common.gettextutils import _ from openstack.common import log as logging @@ -65,3 +67,32 @@ def read_cached_file(filename, force_reload=False): cache_info['mtime'] = mtime reloaded = True return (reloaded, cache_info['data']) + + +def delete_if_exists(path): + """Delete a file, but ignore file not found error. + + :param path: File to delete + """ + + try: + os.unlink(path) + except OSError as e: + if e.errno == errno.ENOENT: + return + else: + raise + + +@contextlib.contextmanager +def remove_path_on_error(path): + """Protect code that wants to operate on PATH atomically. + Any exception will cause PATH to be removed. + + :param path: File to work with + """ + try: + yield + except Exception: + with excutils.save_and_reraise_exception(): + delete_if_exists(path) |
