view env/lib/python3.9/site-packages/galaxy/util/ @ 0:4f3585e2f14b draft default tip

"planemo upload commit 60cee0fc7c0cda8592644e1aad72851dec82c959"
author shellac
date Mon, 22 Mar 2021 18:12:50 +0000
line wrap: on
line source

"""Safely write file to temporary file and then move file into place."""
# Copied from
import os
import tempfile

class RenamedTemporaryFile:
    A temporary file object which will be renamed to the specified
    path on exit.
    def __init__(self, final_path, **kwargs):
        >>> dir = tempfile.mkdtemp()
        >>> with RenamedTemporaryFile(os.path.join(dir, 'test.txt'), mode="w") as out:
        ...     _ = out.write('bla')
        tmpfile_dir = kwargs.pop('dir', None)

        # Put temporary file in the same directory as the location for the
        # final file so that an atomic move into place can occur.

        if tmpfile_dir is None:
            tmpfile_dir = os.path.dirname(final_path)

        self.tmpfile = tempfile.NamedTemporaryFile(dir=tmpfile_dir, delete=False, **kwargs)
        self.final_path = final_path

    def __getattr__(self, attr):
        Delegate attribute access to the underlying temporary file object.
        return getattr(self.tmpfile, attr)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is None:
            result = self.tmpfile.__exit__(exc_type, exc_val, exc_tb)
            os.rename(, self.final_path)
            result = self.tmpfile.__exit__(exc_type, exc_val, exc_tb)

        return result