- Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathpyproject.py
456 lines (342 loc) · 15.8 KB
/
pyproject.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c) 2024 Phil Thompson <phil@riverbankcomputing.com>
from .exceptionsimportdeprecated, UserFileException
from .py_versionsimportOLDEST_SUPPORTED_MINOR
from .tomlimporttoml_loads
classPyProjectException(UserFileException):
""" An exception related to a pyproject.toml file. """
def__init__(self, text, *, detail=None):
""" Initialise the exception. """
super().__init__("pyproject.toml", text, detail=detail)
classPyProjectOptionException(PyProjectException):
""" An exception related to a specific option of a pyproject.toml file. """
def__init__(self, name, text, *, section_name=None, detail=None):
""" Initialise the exception. """
ifsection_nameisNone:
section_name='tool.sip.project'
super().__init__("'{0}.{1}': {2}".format(section_name, name, text),
detail=detail)
classPyProjectTypeOptionException(PyProjectOptionException):
""" An exception related to a badly typed option of a pyproject.toml file.
"""
def__init__(self, name, types, *, section_name=None):
""" Initialise the exception. """
super().__init__(name, "value must be "+types,
section_name=section_name)
classPyProjectUndefinedOptionException(PyProjectOptionException):
""" An exception related to an undefined option of a pyproject.toml file.
"""
def__init__(self, name, *, section_name=None):
""" Initialise the exception. """
super().__init__(name, "must be defined", section_name=section_name)
classPyProject:
""" Encapsulate a parsed pyproject.toml file. """
# The mapping of PEP 621 metadata to core metadata.
_PEP621_CORE_MAP= {
'name': 'name',
'version': 'version',
'description': 'summary',
'requires-python': 'requires-python',
'classifiers': 'classifier',
}
def__init__(self):
""" Initialise the object. """
try:
withopen('pyproject.toml', encoding='UTF-8') asf:
self._raw_toml=f.read()
self.pyproject=toml_loads(self._raw_toml)
exceptFileNotFoundError:
# Delay the exception in case the user is asking for help.
self.pyproject=None
exceptUnicodeDecodeErrorase:
raisePyProjectException("is not a UTF-8 encoded file",
details=str(e))
exceptExceptionase:
# Raise the exception now about a possibly badly formed file.
raisePyProjectException(str(e))
defget_metadata(self):
""" Return a dict containing the PEP 566 metadata. """
ifself.pyprojectisNone:
# Provide a minimal default.
returndict(name='unknown', version='0.1')
# See if PEP 621 project metadata is supplied. Make this required when
# support for the legacy metadata is removed.
metadata=self.get_section('project')
ifmetadataisNone:
core_metadata=self._get_legacy_metadata()
else:
# The main validation we do is to check that the keys are defined
# by PEP 621.
core_metadata= {'metadata-version': '2.1'}
formd_name, md_valueinmetadata.items():
md_name=md_name.lower()
# See if special handling is required.
ifmd_name=='readme':
self._handle_readme(md_value, core_metadata)
elifmd_name=='license':
self._handle_license(md_value, core_metadata)
elifmd_name=='authors':
self._handle_people(md_value, 'author', core_metadata)
elifmd_name=='maintainers':
self._handle_people(md_value, 'maintainer', core_metadata)
elifmd_name=='keywords':
self._handle_keywords(md_value, core_metadata)
elifmd_name=='urls':
self._handle_urls(md_value, core_metadata)
elifmd_name=='dependencies':
self._handle_dependencies(md_value, core_metadata)
elifmd_name=='optional-dependencies':
self._handle_optional_dependencies(md_value, core_metadata)
elifmd_namein ('scripts', 'gui-scripts', 'entry-points'):
# We ignore these for the moment and stick with using
# [tool.sip.project].
pass
else:
core_name=self._PEP621_CORE_MAP.get(md_name)
ifcore_nameisNone:
raisePyProjectOptionException(md_name,
"is an unsupported project key",
section_name='project')
core_metadata[core_name] =md_value
# Check that the name has been specified.
if'name'notincore_metadata:
raisePyProjectUndefinedOptionException('name',
section_name='project')
if'version'notincore_metadata:
core_metadata['version'] ='0.1'
if'requires-python'notincore_metadata:
# The minimal version of Python we support.
core_metadata['requires-python'] ='>=3.{}'.format(
OLDEST_SUPPORTED_MINOR)
returncore_metadata
defget_section(self, section_name, *, required=False):
""" Return a sub-section with a dotted name. """
ifself.pyprojectisNone:
returnNone
section=self.pyproject
forpartinsection_name.split('.'):
try:
section=section[part]
exceptKeyError:
ifrequired:
raisePyProjectException(
"the '[{0}]' section is missing".format(
section_name))
returnNone
ifnotself._is_section(section):
raisePyProjectException(
"'{0}' is not a section".format(section_name))
returnsection
def_get_legacy_metadata(self):
""" Return the pre-PEP 621 metadata. """
line_nr=self._get_line_nr('[tool.sip.metadata]')
ifline_nrisNone:
# There is no metadata specified.
raisePyProjectException("the '[project]' section is missing")
deprecated(
"using '[tool.sip.metadata]' to specify the project metadata",
instead="'[project]'", filename='pyproject.toml',
line_nr=line_nr)
core_metadata=dict()
name=None
version=None
core_metadata_version=None
formd_name, md_valueinself.get_section('tool.sip.metadata', required=True).items():
md_name=md_name.lower()
# Extract specific string values.
ifmd_namein ('name', 'metadata-version'):
ifnotisinstance(md_value, str):
raisePyProjectTypeOptionException(md_name, "a string",
section_name='tool.sip')
ifmd_name=='name':
ifnotmd_value.replace('-', '_').isidentifier():
raisePyProjectOptionException('name',
"'{0}' is an invalid project name".format(
md_value),
section_name='tool.sip')
name=md_value
elifmd_name=='metadata-version':
core_metadata_version=md_value
else:
# Any other value may be a string or a list of strings.
value_list=md_valueifisinstance(md_value, list) else [md_value]
forvalueinvalue_list:
ifnotisinstance(value, str):
raisePyProjectTypeOptionException(md_name,
"a string or a list of strings",
section_name='tool.sip')
core_metadata[md_name] =md_value
ifnameisNone:
raisePyProjectUndefinedOptionException('name',
section_name='tool.sip')
ifcore_metadata_versionisNone:
# Default to PEP 566.
core_metadata['metadata-version'] ='2.1'
returncore_metadata
def_get_line_nr(self, target):
""" Return the number of the line in pyproject.toml containing a target
string.
"""
forline_nr, lineinenumerate(self._raw_toml.split('\n')):
line=line.strip()
# Ignore comments.
ifline.startswith('#'):
continue
iftargetinline:
returnline_nr+1
# The target wasn't present.
returnNone
@classmethod
def_handle_dependencies(cls, value, core_metadata):
""" Handle the 'dependencies' key. """
ifnotisinstance(value, list):
raisePyProjectTypeOptionException('dependencies',
"an array of strings", section_name='project')
cls._update_requires_dist(value, core_metadata)
@staticmethod
def_handle_keywords(value, core_metadata):
""" Handle the 'keywords' key. """
ifnotisinstance(value, list):
raisePyProjectTypeOptionException('keywords',
"an array of strings", section_name='project')
core_metadata['keywords'] =', '.join(value)
@staticmethod
def_handle_license(value, core_metadata):
""" Handle the 'license' key. """
ifnotisinstance(value, dict):
raisePyProjectTypeOptionException('license', "a table",
section_name='project')
text=value.get('text')
file=value.get('file')
iftextisnotNone:
iffileisnotNone:
raisePyProjectOptionException('license',
"'file' and 'text' cannot both be specified",
section_name='project')
eliffileisnotNone:
try:
withopen(file, encoding='UTF-8') asf:
text=f.read()
exceptFileNotFoundError:
raisePyProjectOptionException('file',
f"unable to read '{file}'",
section_name='project.license')
else:
raisePyProjectOptionException('readme',
"either 'file' or 'text' must be specified",
section_name='project')
core_metadata['license'] =text
@classmethod
def_handle_optional_dependencies(cls, value, core_metadata):
""" Handle the 'optional-dependencies' key. """
ifnotisinstance(value, dict):
raisePyProjectTypeOptionException('optional-dependencies',
"a table", section_name='project')
provides_extra= []
requires_dist= []
forextra, extra_depsinvalue.items():
ifnotisinstance(extra_deps, list):
raisePyProjectOptionException('optional-dependencies',
"each table value must be a list of strings",
section_name='project')
provides_extra.append(extra)
fordepinextra_deps:
# Note that this is broken if the dependency is not a simple
# name.
requires_dist.append(f'{dep}[{extra}]')
core_metadata['provides-extra'] =provides_extra
cls._update_requires_dist(value, core_metadata)
@staticmethod
def_handle_people(value, role, core_metadata):
""" Handle the people-related keys. """
key=role+'s'
ifnotisinstance(value, list):
raisePyProjectTypeOptionException(key, "an array of tables",
section_name='project')
all_names= []
all_emails= []
fortableinvalue:
ifnotisinstance(table, dict):
raisePyProjectTypeOptionException(key, "an array of tables",
section_name='project')
name=table.get('name')
email=table.get('email')
ifnameisNoneandemailisNone:
raisePyProjectOptionException(key,
"each table must contain 'name' and/or 'email'",
section_name='project')
ifnameisnotNoneandnotisinstance(name, str):
raisePyProjectOptionException(key, "'name' must be a string",
section_name='project')
ifemailisnotNoneandnotisinstance(email, str):
raisePyProjectOptionException(key, "'email' must be a string",
section_name='project')
ifemailisnotNone:
ifnameisnotNone:
all_emails.append(f'{name} <{email}>')
else:
all_emails.append(email)
else:
all_names.append(name)
ifall_names:
core_metadata[role] =', '.join(all_names)
ifall_emails:
core_metadata[role+'-email'] =', '.join(all_emails)
@staticmethod
def_handle_readme(value, core_metadata):
""" Handle the 'readme' key. """
ifisinstance(value, str):
readme=value.lower()
ifreadme.endswith('.md'):
content_type='text/markdown'
elifreadme.endswith('.rst'):
content_type='text/x-rst'
else:
raisePyProjectOptionException('readme',
f"'{value}' has an unsupported file type",
section_name='project')
description_file=value
elifisinstance(value, dict):
content_type=value.get('content-type')
ifcontent_typeisNone:
raisePyProjectUndefinedOptionException('content-type',
section_name='project.readme')
description_text=value.get('text')
description_file=value.get('file')
ifdescription_textisnotNone:
ifdescription_fileisnotNone:
raisePyProjectOptionException('readme',
"'file' and 'text' cannot both be specified",
section_name='project')
core_metadata['description'] =text
elifdescription_fileisNone:
raisePyProjectOptionException('readme',
"either 'file' or 'text' must be specified",
section_name='project')
else:
raisePyProjectTypeOptionException('readme', "a string or a table",
section_name='project')
core_metadata['description-content-type'] =content_type
ifdescription_fileisnotNone:
# This is a local, internal extension.
core_metadata['description-file'] =description_file
@staticmethod
def_handle_urls(value, core_metadata):
""" Handle the 'urls' key. """
ifnotisinstance(value, dict):
raisePyProjectTypeOptionException(key, "a table",
section_name='project')
core_metadata['project-url'] = [f'{label}, {url}'forlabel, urlinvalue.items()]
@staticmethod
def_is_section(value):
""" Returns True if a section value is itself a section. """
returnisinstance(value, (dict, list))
@staticmethod
def_update_requires_dist(value, core_metadata):
""" Update 'requires-dist' in the core metadata. """
try:
requires_dist=core_metadata['requires-dist']
exceptKeyError:
requires_dist= []
requires_dist.extend(value)
core_metadata['requires-dist'] =requires_dist