diff options
Diffstat (limited to 'cloudinit/atomic_helper.py')
| -rw-r--r-- | cloudinit/atomic_helper.py | 25 | 
1 files changed, 25 insertions, 0 deletions
| diff --git a/cloudinit/atomic_helper.py b/cloudinit/atomic_helper.py new file mode 100644 index 00000000..15319f71 --- /dev/null +++ b/cloudinit/atomic_helper.py @@ -0,0 +1,25 @@ +#!/usr/bin/python +# vi: ts=4 expandtab + +import json +import os +import tempfile + + +def atomic_write_file(path, content, mode='w'): +    tf = None +    try: +        tf = tempfile.NamedTemporaryFile(dir=os.path.dirname(path), +                                         delete=False, mode=mode) +        tf.write(content) +        tf.close() +        os.rename(tf.name, path) +    except Exception as e: +        if tf is not None: +            os.unlink(tf.name) +        raise e + + +def atomic_write_json(path, data): +    return atomic_write_file(path, json.dumps(data, indent=1, +                                              sort_keys=True) + "\n") | 
