/
pex_info.py
336 lines (272 loc) · 11.3 KB
/
pex_info.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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import
import json
import os
from pex import pex_warnings
from pex.common import open_zip
from pex.compatibility import PY2
from pex.compatibility import string as compatibility_string
from pex.orderedset import OrderedSet
from pex.variables import ENV
from pex.version import __version__ as pex_version
# TODO(wickman) Split this into a PexInfoBuilder/PexInfo to ensure immutability.
# Issue #92.
class PexInfo(object):
"""PEX metadata.
# Build metadata:
build_properties: BuildProperties # (key-value information about the build system)
code_hash: str # sha1 hash of all names/code in the archive
distributions: {dist_name: str} # map from distribution name (i.e. path in
# the internal cache) to its cache key (sha1)
requirements: list # list of requirements for this environment
# Environment options
pex_root: string # root of all pex-related files eg: ~/.pex
entry_point: string # entry point into this pex
script: string # script to execute in this pex environment
# at most one of script/entry_point can be specified
zip_safe: True, default False # is this pex zip safe?
inherit_path: false/fallback/prefer # should this pex inherit site-packages + user site-packages
# + PYTHONPATH?
ignore_errors: True, default False # should we ignore inability to resolve dependencies?
always_write_cache: False # should we always write the internal cache to disk first?
# this is useful if you have very large dependencies that
# do not fit in RAM constrained environments
.. versionchanged:: 0.8
Removed the ``repositories`` and ``indices`` information, as they were never
implemented.
"""
PATH = 'PEX-INFO'
INSTALL_CACHE = 'installed_wheels'
@classmethod
def make_build_properties(cls, interpreter=None):
from .interpreter import PythonInterpreter
from .platforms import Platform
pi = interpreter or PythonInterpreter.get()
plat = Platform.current()
platform_name = plat.platform
return {
'pex_version': pex_version,
'class': pi.identity.interpreter,
'version': pi.identity.version,
'platform': platform_name,
}
@classmethod
def default(cls, interpreter=None):
pex_info = {
'requirements': [],
'distributions': {},
'build_properties': cls.make_build_properties(interpreter),
}
return cls(info=pex_info)
@classmethod
def from_pex(cls, pex):
if os.path.isfile(pex):
with open_zip(pex) as zf:
pex_info = zf.read(cls.PATH)
else:
with open(os.path.join(pex, cls.PATH)) as fp:
pex_info = fp.read()
return cls.from_json(pex_info)
@classmethod
def from_json(cls, content):
if isinstance(content, bytes):
content = content.decode('utf-8')
return cls(info=json.loads(content))
@classmethod
def from_env(cls, env=ENV):
supplied_env = env.strip_defaults()
zip_safe = None if supplied_env.PEX_FORCE_LOCAL is None else not supplied_env.PEX_FORCE_LOCAL
pex_info = {
'pex_root': supplied_env.PEX_ROOT,
'entry_point': supplied_env.PEX_MODULE,
'script': supplied_env.PEX_SCRIPT,
'zip_safe': zip_safe,
'inherit_path': supplied_env.PEX_INHERIT_PATH,
'ignore_errors': supplied_env.PEX_IGNORE_ERRORS,
'always_write_cache': supplied_env.PEX_ALWAYS_CACHE,
}
# Filter out empty entries not explicitly set in the environment.
return cls(info=dict((k, v) for (k, v) in pex_info.items() if v is not None))
@classmethod
def _parse_requirement_tuple(cls, requirement_tuple):
if isinstance(requirement_tuple, (tuple, list)):
if len(requirement_tuple) != 3:
raise ValueError('Malformed PEX requirement: %r' % (requirement_tuple,))
# pre 0.8.x requirement type:
pex_warnings.warn('Attempting to use deprecated PEX feature. Please upgrade past PEX 0.8.x.')
return requirement_tuple[0]
elif isinstance(requirement_tuple, compatibility_string):
return requirement_tuple
raise ValueError('Malformed PEX requirement: %r' % (requirement_tuple,))
def __init__(self, info=None):
"""Construct a new PexInfo. This should not be used directly."""
if info is not None and not isinstance(info, dict):
raise ValueError('PexInfo can only be seeded with a dict, got: '
'%s of type %s' % (info, type(info)))
self._pex_info = info or {}
if 'inherit_path' in self._pex_info:
self.inherit_path = self._pex_info['inherit_path']
self._distributions = self._pex_info.get('distributions', {})
# cast as set because pex info from json must store interpreter_constraints as a list
self._interpreter_constraints = set(self._pex_info.get('interpreter_constraints', set()))
requirements = self._pex_info.get('requirements', [])
if not isinstance(requirements, (list, tuple)):
raise ValueError('Expected requirements to be a list, got %s' % type(requirements))
self._requirements = OrderedSet(self._parse_requirement_tuple(req) for req in requirements)
def _get_safe(self, key):
if key not in self._pex_info:
return None
value = self._pex_info[key]
return value.encode('utf-8') if PY2 else value
@property
def build_properties(self):
"""Information about the system on which this PEX was generated.
:returns: A dictionary containing metadata about the environment used to build this PEX.
"""
return self._pex_info.get('build_properties', {})
@build_properties.setter
def build_properties(self, value):
if not isinstance(value, dict):
raise TypeError('build_properties must be a dictionary!')
self._pex_info['build_properties'] = self.make_build_properties()
self._pex_info['build_properties'].update(value)
@property
def zip_safe(self):
"""Whether or not this PEX should be treated as zip-safe.
If set to false and the PEX is zipped, the contents of the PEX will be unpacked into a
directory within the PEX_ROOT prior to execution. This allows code and frameworks depending
upon __file__ existing on disk to operate normally.
By default zip_safe is True. May be overridden at runtime by the $PEX_FORCE_LOCAL environment
variable.
"""
return self._pex_info.get('zip_safe', True)
@zip_safe.setter
def zip_safe(self, value):
self._pex_info['zip_safe'] = bool(value)
@property
def pex_path(self):
"""A colon separated list of other pex files to merge into the runtime environment.
This pex info property is used to persist the PEX_PATH environment variable into the pex info
metadata for reuse within a built pex.
"""
return self._pex_info.get('pex_path')
@pex_path.setter
def pex_path(self, value):
self._pex_info['pex_path'] = value
@property
def inherit_path(self):
"""Whether or not this PEX should be allowed to inherit system dependencies.
By default, PEX environments are scrubbed of all system distributions prior to execution.
This means that PEX files cannot rely upon preexisting system libraries.
By default inherit_path is false. This may be overridden at runtime by the $PEX_INHERIT_PATH
environment variable.
"""
return self._pex_info.get('inherit_path', 'false')
@inherit_path.setter
def inherit_path(self, value):
if value is False:
value = 'false'
elif value is True:
value = 'prefer'
self._pex_info['inherit_path'] = value
@property
def interpreter_constraints(self):
"""A list of constraints that determine the interpreter compatibility for this
pex, using the Requirement-style format, e.g. ``'CPython>=3', or just '>=2.7,<3'``
for requirements agnostic to interpreter class.
This property will be used at exec time when bootstrapping a pex to search PEX_PYTHON_PATH
for a list of compatible interpreters.
"""
return list(self._interpreter_constraints)
def add_interpreter_constraint(self, value):
self._interpreter_constraints.add(str(value))
@property
def ignore_errors(self):
return self._pex_info.get('ignore_errors', False)
@ignore_errors.setter
def ignore_errors(self, value):
self._pex_info['ignore_errors'] = bool(value)
@property
def emit_warnings(self):
return self._pex_info.get('emit_warnings', True)
@emit_warnings.setter
def emit_warnings(self, value):
self._pex_info['emit_warnings'] = bool(value)
@property
def code_hash(self):
return self._pex_info.get('code_hash')
@code_hash.setter
def code_hash(self, value):
self._pex_info['code_hash'] = value
@property
def entry_point(self):
return self._get_safe('entry_point')
@entry_point.setter
def entry_point(self, value):
self._pex_info['entry_point'] = value
@property
def script(self):
return self._get_safe('script')
@script.setter
def script(self, value):
self._pex_info['script'] = value
def add_requirement(self, requirement):
self._requirements.add(str(requirement))
@property
def requirements(self):
return self._requirements
def add_distribution(self, location, sha):
self._distributions[location] = sha
@property
def distributions(self):
return self._distributions
@property
def always_write_cache(self):
return self._pex_info.get('always_write_cache', False)
@always_write_cache.setter
def always_write_cache(self, value):
self._pex_info['always_write_cache'] = bool(value)
@property
def pex_root(self):
return os.path.expanduser(self._pex_info.get('pex_root', os.path.join('~', '.pex')))
@pex_root.setter
def pex_root(self, value):
self._pex_info['pex_root'] = value
@property
def internal_cache(self):
return '.deps'
@property
def install_cache(self):
return os.path.join(self.pex_root, self.INSTALL_CACHE)
@property
def zip_unsafe_cache(self):
return os.path.join(self.pex_root, 'code')
def update(self, other):
if not isinstance(other, PexInfo):
raise TypeError('Cannot merge a %r with PexInfo' % type(other))
self._pex_info.update(other._pex_info)
self._distributions.update(other.distributions)
self._interpreter_constraints.update(other.interpreter_constraints)
self._requirements.update(other.requirements)
def dump(self, **kwargs):
pex_info_copy = self._pex_info.copy()
pex_info_copy['requirements'] = sorted(self._requirements)
pex_info_copy['interpreter_constraints'] = sorted(self._interpreter_constraints)
pex_info_copy['distributions'] = self._distributions.copy()
return json.dumps(pex_info_copy, **kwargs)
def copy(self):
return self.from_json(self.dump())
@staticmethod
def _merge_split(*paths):
filtered_paths = filter(None, paths)
return [p for p in ':'.join(filtered_paths).split(':') if p]
def merge_pex_path(self, pex_path):
"""Merges a new PEX_PATH definition into the existing one (if any).
:param str pex_path: The PEX_PATH to merge.
"""
if not pex_path:
return
self.pex_path = ':'.join(self._merge_split(self.pex_path, pex_path))
def __repr__(self):
return '{}({!r})'.format(type(self).__name__, self._pex_info)