Commit 20567bef authored by Jason R. Coombs's avatar Jason R. Coombs

Implement AbstractSandbox as a context manager.

parent d48cb39b
...@@ -249,11 +249,9 @@ def run_setup(setup_script, args): ...@@ -249,11 +249,9 @@ def run_setup(setup_script, args):
setup_script.encode(sys.getfilesystemencoding()) setup_script.encode(sys.getfilesystemencoding())
) )
def runner(): with DirectorySandbox(setup_dir):
ns = dict(__file__=dunder_file, __name__='__main__') ns = dict(__file__=dunder_file, __name__='__main__')
_execfile(setup_script, ns) _execfile(setup_script, ns)
DirectorySandbox(setup_dir).run(runner)
except SystemExit as v: except SystemExit as v:
if v.args and v.args[0]: if v.args and v.args[0]:
raise raise
...@@ -275,21 +273,24 @@ class AbstractSandbox: ...@@ -275,21 +273,24 @@ class AbstractSandbox:
for name in self._attrs: for name in self._attrs:
setattr(os, name, getattr(source, name)) setattr(os, name, getattr(source, name))
def __enter__(self):
self._copy(self)
if _file:
builtins.file = self._file
builtins.open = self._open
self._active = True
def __exit__(self, exc_type, exc_value, traceback):
self._active = False
if _file:
builtins.file = _file
builtins.open = _open
self._copy(_os)
def run(self, func): def run(self, func):
"""Run 'func' under os sandboxing""" """Run 'func' under os sandboxing"""
try: with self:
self._copy(self)
if _file:
builtins.file = self._file
builtins.open = self._open
self._active = True
return func() return func()
finally:
self._active = False
if _file:
builtins.file = _file
builtins.open = _open
self._copy(_os)
def _mk_dual_path_wrapper(name): def _mk_dual_path_wrapper(name):
original = getattr(_os, name) original = getattr(_os, name)
......
...@@ -12,8 +12,8 @@ from setuptools.sandbox import DirectorySandbox ...@@ -12,8 +12,8 @@ from setuptools.sandbox import DirectorySandbox
class TestSandbox: class TestSandbox:
def test_devnull(self, tmpdir): def test_devnull(self, tmpdir):
sandbox = DirectorySandbox(str(tmpdir)) with DirectorySandbox(str(tmpdir)):
sandbox.run(self._file_writer(os.devnull)) self._file_writer(os.devnull)
@staticmethod @staticmethod
def _file_writer(path): def _file_writer(path):
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment