forked from pypa/build
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
160 lines (118 loc) · 4.74 KB
/
__init__.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
# SPDX-License-Identifier: MIT
'''
python-build - A simple, correct PEP517 package builder
'''
__version__ = '0.0.3.1'
import importlib
import os
import sys
from typing import Dict, List, Optional, Set, Union
import pep517.wrappers
import toml
import toml.decoder
if sys.version_info < (3,):
FileNotFoundError = IOError
PermissionError = OSError
ConfigSettings = Dict[str, Union[str, List[str]]]
_DEFAULT_BACKEND = {
'build-backend': 'setuptools.build_meta:__legacy__',
'requires': [
'setuptools >= 40.8.0',
'wheel'
]
}
class BuildException(Exception):
'''
Exception raised by ProjectBuilder
'''
class BuildBackendException(Exception):
'''
Exception raised when the backend fails
'''
def check_version(requirement_string, extra=''): # type: (str, str) -> bool
'''
:param requirement_string: Requirement string
:param extra: Extra (eg. test in myproject[test])
'''
import packaging.requirements
if sys.version_info >= (3, 8):
from importlib import metadata as importlib_metadata
else:
import importlib_metadata
req = packaging.requirements.Requirement(requirement_string)
env = {
'extra': extra
}
if req.marker and not req.marker.evaluate(env):
return True
try:
version = importlib_metadata.version(req.name)
metadata = importlib_metadata.metadata(req.name)
except importlib_metadata.PackageNotFoundError:
return False
for extra in req.extras:
if extra not in (metadata.get_all('Provides-Extra') or []):
return False
if req.specifier:
return req.specifier.contains(version)
return True
class ProjectBuilder(object):
def __init__(self, srcdir='.', config_settings=None): # type: (str, Optional[ConfigSettings]) -> None
'''
:param srcdir: Source directory
'''
self.srcdir = srcdir
self.config_settings = config_settings if config_settings else {}
spec_file = os.path.join(srcdir, 'pyproject.toml')
try:
with open(spec_file) as f:
self._spec = toml.load(f)
except FileNotFoundError:
self._spec = {}
except PermissionError as e:
raise BuildException("{}: '{}' ".format(e.strerror, e.filename))
except toml.decoder.TomlDecodeError as e:
raise BuildException("Failed to parse pyproject.toml: {} ".format(e))
self._build_system = self._spec.get('build-system', _DEFAULT_BACKEND)
if 'build-backend' not in self._build_system:
self._build_system['build-backend'] = _DEFAULT_BACKEND['build-backend']
self._build_system['requires'] = self._build_system.get('requires', []) + _DEFAULT_BACKEND['requires']
if 'requires' not in self._build_system:
raise BuildException("Missing 'build-system.requires' in pyproject.yml")
self._backend = self._build_system['build-backend']
try:
importlib.import_module(self._backend.split(':')[0])
except ImportError: # can't mock importlib.import_module # pragma: no cover
raise BuildException("Backend '{}' is not available".format(self._backend))
self.hook = pep517.wrappers.Pep517HookCaller(self.srcdir, self._backend,
backend_path=self._build_system.get('backend-path'))
@property
def build_dependencies(self): # type: () -> Set[str]
return set(self._build_system['requires'])
def get_dependencies(self, distribution): # type: (str) -> Set[str]
'''
Returns a set of dependencies
'''
get_requires = getattr(self.hook, 'get_requires_for_build_{}'.format(distribution))
try:
return set(get_requires(self.config_settings))
except Exception as e: # noqa: E722
raise BuildBackendException('Backend operation failed: {}'.format(e))
def check_dependencies(self, distribution): # type: (str) -> Set[str]
'''
Returns a set of the missing dependencies
:param distribution: Distribution to build (sdist or wheel)
'''
dependencies = self.get_dependencies(distribution)
return {dep for dep in dependencies if not check_version(dep)}
def build(self, distribution, outdir): # type: (str, str) -> None
'''
Builds a distribution
:param distribution: Distribution to build (sdist or wheel)
:param outdir: Outpur directory
'''
build = getattr(self.hook, 'build_{}'.format(distribution))
try:
build(outdir, self.config_settings)
except Exception as e: # noqa: E722
raise BuildBackendException('Backend operation failed: {}'.format(e))