# Atomic file writing helper.

import os

def replace_file(filename, content):
    """Attempt to atomically and durably replace the filename with the
    given contents.  This is intended to be 'pretty good on most
    OSes', but not necessarily bulletproof."""

    newfilename = filename + ".new"

    # Write to new file, flush it
    with open(newfilename, "wb") as f:
        f.write(content)
        f.flush()
        os.fsync(f.fileno())

    # Move new file over old one
    try:
        os.rename(newfilename, filename)
    except OSError: # pragma: no cover
        # Some OSes might not support renaming over an existing file.
        # This is definitely NOT atomic!
        os.remove(filename)
        os.rename(newfilename, filename)

