Skip to content

Commit

Permalink
Merge pull request #1172 from effigies/rf/drop_custom_temporarydirectory
Browse files Browse the repository at this point in the history
RF: Rely on stdlib implementations for tmpdirs tools
  • Loading branch information
effigies authored Jan 3, 2023
2 parents 437d972 + 27b757b commit ea962d5
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 63 deletions.
6 changes: 6 additions & 0 deletions nibabel/tests/test_removalschedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@
]

OBJECT_SCHEDULE = [
(
'8.0.0',
[
('nibabel.tmpdirs', 'TemporaryDirectory'),
],
),
(
'7.0.0',
[
Expand Down
117 changes: 54 additions & 63 deletions nibabel/tmpdirs.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,46 +9,54 @@
"""Contexts for *with* statement providing temporary directories
"""
import os
import shutil
from tempfile import mkdtemp, template
import tempfile
from contextlib import contextmanager

try:
from contextlib import chdir as _chdir
except ImportError: # PY310

class TemporaryDirectory:
@contextmanager
def _chdir(path):
cwd = os.getcwd()
os.chdir(path)
yield
os.chdir(cwd)


from .deprecated import deprecate_with_version


class TemporaryDirectory(tempfile.TemporaryDirectory):
"""Create and return a temporary directory. This has the same
behavior as mkdtemp but can be used as a context manager.
Upon exiting the context, the directory and everything contained
in it are removed.
Examples
--------
>>> import os
>>> with TemporaryDirectory() as tmpdir:
... fname = os.path.join(tmpdir, 'example_file.txt')
... with open(fname, 'wt') as fobj:
... _ = fobj.write('a string\\n')
>>> os.path.exists(tmpdir)
False
"""

def __init__(self, suffix='', prefix=template, dir=None):
self.name = mkdtemp(suffix, prefix, dir)
self._closed = False

def __enter__(self):
return self.name

def cleanup(self):
if not self._closed:
shutil.rmtree(self.name)
self._closed = True

def __exit__(self, exc, value, tb):
self.cleanup()
return False
@deprecate_with_version(
'Please use the standard library tempfile.TemporaryDirectory',
'5.0',
'7.0',
)
def __init__(self, suffix='', prefix=tempfile.template, dir=None):
"""
Examples
--------
>>> import os
>>> with TemporaryDirectory() as tmpdir:
... fname = os.path.join(tmpdir, 'example_file.txt')
... with open(fname, 'wt') as fobj:
... _ = fobj.write('a string\\n')
>>> os.path.exists(tmpdir)
False
"""
return super().__init__(suffix, prefix, dir)


class InTemporaryDirectory(TemporaryDirectory):
@contextmanager
def InTemporaryDirectory():
"""Create, return, and change directory to a temporary directory
Notes
Expand All @@ -60,28 +68,23 @@ class InTemporaryDirectory(TemporaryDirectory):
Examples
--------
>>> import os
>>> from pathlib import Path
>>> my_cwd = os.getcwd()
>>> with InTemporaryDirectory() as tmpdir:
... _ = open('test.txt', 'wt').write('some text')
... _ = Path('test.txt').write_text('some text')
... assert os.path.isfile('test.txt')
... assert os.path.isfile(os.path.join(tmpdir, 'test.txt'))
>>> os.path.exists(tmpdir)
False
>>> os.getcwd() == my_cwd
True
"""
with tempfile.TemporaryDirectory() as tmpdir, _chdir(tmpdir):
yield tmpdir

def __enter__(self):
self._pwd = os.getcwd()
os.chdir(self.name)
return super().__enter__()

def __exit__(self, exc, value, tb):
os.chdir(self._pwd)
return super().__exit__(exc, value, tb)


class InGivenDirectory:
@contextmanager
def InGivenDirectory(path=None):
"""Change directory to given directory for duration of ``with`` block
Useful when you want to use `InTemporaryDirectory` for the final test, but
Expand All @@ -103,27 +106,15 @@ class InGivenDirectory:
You can then look at the temporary file outputs to debug what is happening,
fix, and finally replace ``InGivenDirectory`` with ``InTemporaryDirectory``
again.
"""

def __init__(self, path=None):
"""Initialize directory context manager
Parameters
----------
path : None or str, optional
path to change directory to, for duration of ``with`` block.
Defaults to ``os.getcwd()`` if None
"""
if path is None:
path = os.getcwd()
self.path = os.path.abspath(path)

def __enter__(self):
self._pwd = os.path.abspath(os.getcwd())
if not os.path.isdir(self.path):
os.mkdir(self.path)
os.chdir(self.path)
return self.path

def __exit__(self, exc, value, tb):
os.chdir(self._pwd)
Parameters
----------
path : None or str, optional
path to change directory to, for duration of ``with`` block.
Defaults to ``os.getcwd()`` if None
"""
if path is None:
path = os.getcwd()
os.makedirs(path, exist_ok=True)
with _chdir(path):
yield os.path.abspath(path)

0 comments on commit ea962d5

Please sign in to comment.