Repository navigation
Expand file tree
/
Copy pathwheel_builder_utils.py
More file actions
93 lines (72 loc) · 2.49 KB
/
Copy pathwheel_builder_utils.py
File metadata and controls
93 lines (72 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""This module provides convenient function facilitating scripting.
These functions have been copied from scikit-build project.
See https://github.com/scikit-build/scikit-build
"""
import errno
import os
from contextlib import contextmanager
from functools import wraps
def mkdir_p(path):
"""Ensure directory ``path`` exists. If needed, parent directories
are created.
Adapted from https://stackoverflow.com/a/600612/1539918
"""
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else: # pragma: no cover
raise
@contextmanager
def push_env(**kwargs):
"""This context manager allow to set/unset environment variables."""
saved_env = dict(os.environ)
for var, value in kwargs.items():
if value is not None:
os.environ[var] = value
elif var in os.environ:
del os.environ[var]
yield
os.environ.clear()
for saved_var, saved_value in saved_env.items():
os.environ[saved_var] = saved_value
class ContextDecorator:
"""A base class or mixin that enables context managers to work as
decorators."""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __enter__(self):
# Note: Returning self means that in "with ... as x", x will be self
return self
def __exit__(self, typ, val, traceback):
pass
def __call__(self, func):
@wraps(func)
def inner(*args, **kwds): # pylint:disable=missing-docstring
with self:
return func(*args, **kwds)
return inner
class push_dir(ContextDecorator):
"""Context manager to change current directory."""
def __init__(self, directory=None, make_directory=False):
"""
:param directory:
Path to set as current working directory. If ``None``
is passed, ``os.getcwd()`` is used instead.
:param make_directory:
If True, ``directory`` is created.
"""
self.directory = None
self.make_directory = None
self.old_cwd = None
super().__init__(directory=directory, make_directory=make_directory)
def __enter__(self):
self.old_cwd = os.getcwd()
if self.directory:
if self.make_directory:
mkdir_p(self.directory)
os.chdir(self.directory)
return self
def __exit__(self, typ, val, traceback):
os.chdir(self.old_cwd)