pax_global_header00006660000000000000000000000064137443545250014526gustar00rootroot0000000000000052 comment=cdec4a3cf85ccdf661e47dd56282ca19c1536ca3 python-volatile-2.1.0/000077500000000000000000000000001374435452500146645ustar00rootroot00000000000000python-volatile-2.1.0/.travis.yml000066400000000000000000000001771374435452500170020ustar00rootroot00000000000000language: python env: - TOXENV=py26 - TOXENV=py27 - TOXENV=py33 - TOXENV=py34 install: pip install tox script: tox sudo: false python-volatile-2.1.0/LICENSE000066400000000000000000000020421374435452500156670ustar00rootroot00000000000000Copyright (c) 2015 Marc Brinkmann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. python-volatile-2.1.0/README.rst000066400000000000000000000027761374435452500163670ustar00rootroot00000000000000volatile ======== Temporary files and directories. Contains replacement for ``tempfile.NamedTemporaryFile`` that does not delete the file on ``close()``, but still unlinks it after the context manager ends, as well as a ``mkdtemp``-based temporary directory implementation. * Mostly reuses the stdlib implementations, supporting the same signatures. * Due to that, uses the OS's built-in temporary file facilities, no custom schemes. * Tested on Python 2.6+ and 3.3+ Usage ----- A typical use-case that is not possible with the regular ``NamedTemporaryFile``: .. code-block:: python import volatile with volatile.file() as tmp: # tmp behaves like a regular NamedTemporaryFile here, except for that # it gets unlinked at the end of the context manager, instead of when # close() is called. tmp.close() # run the users $EDITOR run_editor(tmp.name) buf = open(tmp.name).read() # ... Temporary directories: .. code-block:: python import volatile with volatile.dir(): as dtmp: pass # ... can use directory here # a missing dtmp will not throw an exception! Unix domain sockets: .. code-block:: python import volatile with volatile.unix_socket(): as (sock, addr): # sock is the bound socket, addr its address on the filesystem pass # ... can use directory here The source is fairly short and contains `API docs in the comments `_. python-volatile-2.1.0/setup.py000066400000000000000000000012271374435452500164000ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='volatile', version='2.1.0', description='A small extension for the tempfile module.', long_description=read('README.rst'), author='Marc Brinkmann', author_email='git@marcbrinkmann.de', url='https://github.com/mbr/volatile', license='MIT', packages=find_packages(exclude=['tests']), classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ]) python-volatile-2.1.0/tests/000077500000000000000000000000001374435452500160265ustar00rootroot00000000000000python-volatile-2.1.0/tests/test_volatile.py000066400000000000000000000050351374435452500212610ustar00rootroot00000000000000import os import pytest import volatile def test_ntf_simple_persistance(): with volatile.file() as tmp: assert os.path.exists(tmp.name) tmp.close() assert os.path.exists(tmp.name) assert not os.path.exists(tmp.name) def test_keeps_content(): with volatile.file() as tmp: tmp.write(b'foo') tmp.close() assert b'foo' == open(tmp.name, 'rb').read() def test_unlink_raises(): with pytest.raises(OSError): with volatile.file() as tmp: os.unlink(tmp.name) def test_can_ignore_missing(): with volatile.file(ignore_missing=True) as tmp: os.unlink(tmp.name) def test_temp_dir(): with volatile.dir() as dtmp: assert os.path.exists(dtmp) assert os.path.isdir(dtmp) assert not os.path.exists(dtmp) def test_can_remove_dir_without_error(): with volatile.dir() as dtmp: os.rmdir(dtmp) def test_socket(): with volatile.unix_socket() as (sock, addr): assert hasattr(sock, 'close') assert os.path.exists(addr) assert not os.path.exists(addr) def test_file_cleanup_after_exception(): try: with volatile.file() as tmp: name = tmp.name assert os.path.exists(name) raise RuntimeError() pass except RuntimeError: pass assert not os.path.exists(name) def test_dir_cleanup_after_exception(): try: with volatile.dir() as dtmp: name = dtmp assert os.path.exists(name) raise RuntimeError() pass except RuntimeError: pass assert not os.path.exists(name) def test_socket_cleanup_after_exception(): try: with volatile.unix_socket() as (_, addr): name = addr assert os.path.exists(name) raise RuntimeError() pass except RuntimeError: pass assert not os.path.exists(name) def test_force_false_is_gentle(): try: with pytest.raises(OSError): with volatile.dir(force=False) as dtmp: blocking_path = os.path.join(dtmp, 'blocking') with open(blocking_path, 'w') as f: f.write('hello') finally: assert os.path.exists(blocking_path) os.unlink(blocking_path) os.rmdir(os.path.dirname(blocking_path)) def test_umask(): current_umask = os.umask(0o022) os.umask(current_umask) with volatile.umask(0o456): assert os.umask(0o123) == 0o456 assert os.umask(current_umask) == current_umask python-volatile-2.1.0/tox.ini000066400000000000000000000001201374435452500161700ustar00rootroot00000000000000[tox] envlist = py26,py27,py33,py34 [testenv] deps=pytest commands=py.test -rs python-volatile-2.1.0/volatile/000077500000000000000000000000001374435452500165035ustar00rootroot00000000000000python-volatile-2.1.0/volatile/__init__.py000066400000000000000000000105031374435452500206130ustar00rootroot00000000000000from contextlib import contextmanager from errno import ENOENT import os import shutil import socket import tempfile @contextmanager def dir(suffix='', prefix='tmp', dir=None, force=True): """Create a temporary directory. A contextmanager that creates and returns a temporary directory, cleaning it up on exit. The force option specifies whether or not the directory is removed recursively. If set to `False` (the default is `True`), only an empty temporary directory will be removed. This is helpful to create temporary directories for things like mountpoints; otherwise a failing unmount would result in all files on the mounted volume to be deleted. :param suffix: Passed on to :func:`tempfile.mkdtemp`. :param prefix: Passed on to :func:`tempfile.mkdtemp`. :param dir: Passed on to :func:`tempfile.mkdtemp`. :param force: If true, recursively removes directory, otherwise just removes if empty. If directory isn't empty and `force` is `False`, :class:`OSError` is raised. :return: Path to the newly created temporary directory. """ name = tempfile.mkdtemp(suffix, prefix, dir) try: yield name finally: try: if force: shutil.rmtree(name) else: os.rmdir(name) except OSError as e: if e.errno != 2: # not found raise @contextmanager def file(mode='w+b', suffix='', prefix='tmp', dir=None, ignore_missing=False): """Create a temporary file. A contextmanager that creates and returns a named temporary file and removes it on exit. Differs from temporary file functions in :mod:`tempfile` by not deleting the file once it is closed, making it safe to write and close the file and then processing it with an external program. If the temporary file is moved elsewhere later on, `ignore_missing` should be set to `True`. :param mode: Passed on to :func:`tempfile.NamedTemporaryFile`. :param suffix: Passed on to :func:`tempfile.NamedTemporaryFile`. :param prefix: Passed on to :func:`tempfile.NamedTemporaryFile`. :param dir: Passed on to :func:`tempfile.NamedTemporaryFile`. :param ignore_missing: If set to `True`, no exception will be raised if the temporary file has been deleted when trying to clean it up. :return: A file object with a `.name`. """ # note: bufsize is not supported in Python3, try to prevent problems # stemming from incorrect api usage if isinstance(suffix, int): raise ValueError('Passed an integer as suffix. Did you want to ' 'specify the deprecated parameter `bufsize`?') fp = tempfile.NamedTemporaryFile(mode=mode, suffix=suffix, prefix=prefix, dir=dir, delete=False) try: yield fp finally: try: os.unlink(fp.name) except OSError as e: # if the file does not exist anymore, ignore if e.errno != ENOENT or ignore_missing is False: raise @contextmanager def unix_socket(sock=None, socket_name='tmp.socket', close=True): """Create temporary unix socket. Creates and binds a temporary unix socket that will be closed and removed on exit. :param sock: If not `None`, will not created a new unix socket, but bind the passed in one instead. :param socket_name: The name for the socket file (will be placed in a temporary directory). Do not pass in an absolute path! :param close: If `False`, does not close the socket before removing the temporary directory. :return: A tuple of `(socket, addr)`, where `addr` is the location of the bound socket on the filesystem. """ sock = sock or socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) with dir() as dtmp: addr = os.path.join(dtmp, socket_name) sock.bind(addr) try: yield sock, addr finally: if close: sock.close() @contextmanager def umask(new_umask): prev_umask = os.umask(new_umask) yield prev_umask os.umask(prev_umask)