-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathvenv.py
146 lines (123 loc) · 4.9 KB
/
venv.py
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
from __future__ import absolute_import
import compileall
import shutil
import sysconfig
import textwrap
import six
import virtualenv as _virtualenv
from .path import Path
if six.PY3:
import venv as _venv
class VirtualEnvironment(object):
"""
An abstraction around virtual environments, currently it only uses
virtualenv but in the future it could use pyvenv.
"""
def __init__(self, location, template=None, venv_type=None):
assert template is None or venv_type is None
assert venv_type in (None, 'virtualenv', 'venv')
self.location = Path(location)
self._venv_type = venv_type or template._venv_type or 'virtualenv'
self._user_site_packages = False
self._template = template
self._sitecustomize = None
self._update_paths()
self._create()
def _update_paths(self):
paths = sysconfig.get_paths(vars={
"installed_base": self.location,
"installed_platbase": self.location,
"base": self.location,
"platbase": self.location,
})
self.bin = Path(paths["scripts"])
self.site = Path(paths["purelib"])
self.lib = Path(paths["stdlib"])
def __repr__(self):
return "<VirtualEnvironment {}>".format(self.location)
def _create(self, clear=False):
if clear:
shutil.rmtree(self.location)
if self._template:
# Clone virtual environment from template.
shutil.copytree(
self._template.location, self.location, symlinks=True
)
self._sitecustomize = self._template.sitecustomize
self._user_site_packages = self._template.user_site_packages
else:
# Create a new virtual environment.
if self._venv_type == 'virtualenv':
_virtualenv.cli_run([
self.location,
"--no-pip",
"--no-wheel",
"--no-setuptools",
])
elif self._venv_type == 'venv':
builder = _venv.EnvBuilder()
context = builder.ensure_directories(self.location)
builder.create_configuration(context)
builder.setup_python(context)
self.site.mkdir(parents=True, exist_ok=True)
else:
raise ValueError("venv type must be 'virtualenv' or 'venv'")
self.sitecustomize = self._sitecustomize
self.user_site_packages = self._user_site_packages
def _customize_site(self):
# Enable user site (before system).
contents = textwrap.dedent(
'''
import os, site, sys
if not os.environ.get('PYTHONNOUSERSITE', False):
site.ENABLE_USER_SITE = True
# First, drop system-sites related paths.
original_sys_path = sys.path[:]
known_paths = set()
for path in site.getsitepackages():
site.addsitedir(path, known_paths=known_paths)
system_paths = sys.path[len(original_sys_path):]
for path in system_paths:
if path in original_sys_path:
original_sys_path.remove(path)
sys.path = original_sys_path
# Second, add user-site.
site.addsitedir(site.getusersitepackages())
# Third, add back system-sites related paths.
for path in site.getsitepackages():
site.addsitedir(path)
''').strip()
if self._sitecustomize is not None:
contents += '\n' + self._sitecustomize
sitecustomize = self.site / "sitecustomize.py"
sitecustomize.write_text(contents)
# Make sure bytecode is up-to-date too.
assert compileall.compile_file(str(sitecustomize), quiet=1, force=True)
def clear(self):
self._create(clear=True)
def move(self, location):
shutil.move(self.location, location)
self.location = Path(location)
self._update_paths()
@property
def sitecustomize(self):
return self._sitecustomize
@sitecustomize.setter
def sitecustomize(self, value):
self._sitecustomize = value
self._customize_site()
@property
def user_site_packages(self):
return self._user_site_packages
@user_site_packages.setter
def user_site_packages(self, value):
self._user_site_packages = value
self._customize_site()
pyvenv_cfg = self.location.joinpath("pyvenv.cfg")
modified_lines = []
for line in pyvenv_cfg.read_text().splitlines():
k, v = line.split("=", 1)
if k.strip() == "include-system-site-packages":
line = "{}= {}".format(k, "true" if value else "false")
modified_lines.append(line)
pyvenv_cfg.write_text("\n".join(modified_lines))