- Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathproject.py
894 lines (685 loc) · 32.6 KB
/
project.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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c) 2025 Phil Thompson <phil@riverbankcomputing.com>
importcollections
importos
importpackaging
importshutil
importsubprocess
importsys
importsysconfig
importtempfile
importwarnings
from .abstract_builderimportAbstractBuilder
from .abstract_projectimportAbstractProject
from .bindingsimportBindings
from .buildableimportBuildableFromSources
from .configurableimportConfigurable, Option
from .exceptionsimportUserException
from .moduleimportget_source_version_range, parse_abi_version
from .py_versionsimportOLDEST_SUPPORTED_MINOR
from .pyprojectimportPyProjectException, PyProjectOptionException
# The macOS minimum version of the latest supported version of Python. v10.13
# is the minimum version required by Python v3.13.
MACOS_MIN_OS_MAJOR=10
MACOS_MIN_OS_MINOR=13
classProject(AbstractProject, Configurable):
""" Encapsulate a project containing one or more sets of bindings. """
# The configurable options.
_options= (
# The callable that will return an Bindings instance. This is used for
# bindings implicitly defined in the .toml file.
Option('bindings_factory'),
# The callable that will return an AbstractBuilder instance.
Option('builder_factory'),
# The list of console script entry points.
Option('console_scripts', option_type=list),
# Set if an __init__.py should be installed.
Option('dunder_init', option_type=bool, default=False),
# The list of GUI script entry points.
Option('gui_scripts', option_type=list),
# The minimum macOS version required by the project. This is used to
# determine the correct platform tag to use for macOS wheels.
Option('minimum_macos_version'),
# Set if building for a debug version of Python.
Option('py_debug', option_type=bool),
# The name of the directory containing Python.h.
Option('py_include_dir', default=sysconfig.get_path('include')),
# The name of the target Python platform.
Option('py_platform'),
# The major version number of the target Python installation.
Option('py_major_version', option_type=int),
# The minor version number of the target Python installation.
Option('py_minor_version', option_type=int),
# The name of the directory containing the .sip files. If the sip
# module is shared then each set of bindings is in its own
# sub-directory.
Option('sip_files_dir', default='.'),
# The list of files and directories, specified as glob patterns
# relative to the project directory, that should be excluded from an
# sdist.
Option('sdist_excludes', option_type=list),
# The list of additional directories to search for .sip files.
Option('sip_include_dirs', option_type=list),
# The fully qualified name of the sip module.
Option('sip_module'),
# The list of files and directories, specified as glob patterns, that
# should be included in a wheel. If a pattern is relative then it is
# taken as being relative to the project directory. If an element of
# the list is a string then it is a pattern and files and directories
# are installed in the target directory. If an element is a 2-tuple
# then the first part is the pattern and the second part is the name of
# a sub-directory relative to the target directory where the files and
# directories are installed.
Option('wheel_includes', option_type=list),
# The user-configurable options.
Option('quiet', option_type=bool,
help="disable all progress messages"),
Option('verbose', option_type=bool,
help="enable verbose progress messages"),
Option('name', help="the name used in sdist and wheel file names",
metavar="NAME", tools=['sdist', 'wheel']),
Option('abi_version', help="The ABI to generate code for",
metavar="M[.N]"),
Option('build_dir', help="the build directory", metavar="DIR"),
Option('build_tag', help="the build tag to be used in the wheel name",
metavar="TAG", tools=['wheel']),
Option('distinfo', option_type=bool, inverted=True,
help="don't create a .dist-info directory", tools=['install']),
Option('manylinux', option_type=bool, inverted=True,
help="disable the use of manylinux in the platform tag used "
"in the wheel name",
tools=['wheel']),
Option('minimum_glibc_version',
help="the minimum GLIBC version to be used in the platform "
"tag of Linux wheels",
metavar="M.N", tools=['wheel']),
Option('scripts_dir', default=os.path.dirname(sys.executable),
help="the scripts installation directory", metavar="DIR",
tools=['build', 'install']),
Option('target_dir', default=sysconfig.get_path('platlib'),
help="the target installation directory", metavar="DIR",
tools=['build', 'install']),
Option('api_dir', help="generate a QScintilla .api file in DIR",
metavar="DIR"),
Option('compile', option_type=bool, inverted=True,
help="disable the compilation of the generated code",
tools=['build']),
Option('version_info', option_type=bool, inverted=True,
help="disable any reference to the SIP version number in "
"generated code",
tools=['build']),
)
# The configurable options for multiple bindings.
_multibindings_options= (
Option('disable', option_type=list, help="disable the NAME bindings",
metavar="NAME"),
Option('enable', option_type=list, help="enable the NAME bindings",
metavar="NAME"),
)
def__init__(self, **kwargs):
""" Initialise the project. """
super().__init__()
# The current directory should contain the .toml file.
self.root_dir=os.getcwd()
self.arguments=None
self.bindings=collections.OrderedDict()
self.bindings_factories= []
self.builder=None
self.buildables= []
self.installables= []
# The provisional target ABI is that specified by abi-version in
# pyproject.toml (or on the command line). Note that, for historical
# reasons, we may not have the source of the older minor versions in
# which case we will build against the oldest we do have.
self.target_abi=None
self._build_abi=None
self._metadata_overrides=None
self._temp_build_dir=None
self.initialise_options(kwargs)
@property
defall_modules_use_limited_abi(self):
""" True if all modules in the project use the limited ABI. """
forbuildableinself.buildables:
ifisinstance(buildable, BuildableFromSources):
ifnotbuildable.uses_limited_api:
returnFalse
returnTrue
defapply_nonuser_defaults(self, tool):
""" Set default values for non-user options that haven't been set yet.
"""
ifself.bindings_factoryisNone:
self.bindings_factory=Bindings
elifisinstance(self.bindings_factory, str):
# Convert the name to a callable.
self.bindings_factory=self.import_callable(self.bindings_factory,
Bindings)
ifself.py_major_versionisNoneorself.py_minor_versionisNone:
self.py_major_version=sys.hexversion>>24
self.py_minor_version= (sys.hexversion>>16) &0x0ff
ifself.builder_factoryisNone:
if (self.py_major_version, self.py_minor_version) >= (3, 10):
from .setuptools_builderimportSetuptoolsBuilder
self.builder_factory=SetuptoolsBuilder
else:
from .distutils_builderimportDistutilsBuilder
self.builder_factory=DistutilsBuilder
elifisinstance(self.builder_factory, str):
# Convert the name to a callable.
self.builder_factory=self.import_callable(self.builder_factory,
AbstractBuilder)
ifself.py_platformisNone:
self.py_platform=sys.platform
ifself.py_debugisNone:
self.py_debug=hasattr(sys, 'gettotalrefcount')
super().apply_nonuser_defaults(tool)
defapply_user_defaults(self, tool):
""" Set default values for user options that haven't been set yet. """
# This is only used when creating sdist and wheel files.
ifself.nameisNone:
self.name=self.metadata['name']
# For the build tool we want build_dir to default to a local 'build'
# directory (which we won't remove). However, for other tools (and for
# PEP 517 frontends) we want to use a temporary directory in case the
# current directory is read-only.
ifself.build_dirisNone:
iftool=='build':
self.build_dir='build'
else:
self._temp_build_dir=tempfile.TemporaryDirectory()
self.build_dir=self._temp_build_dir.name
super().apply_user_defaults(tool)
# Adjust the list of bindings according to what has been explicitly
# enabled and disabled.
self._enable_disable_bindings()
# Set the user defaults for the builder and bindings.
self.builder.apply_user_defaults(tool)
forbindingsinself.bindings.values():
bindings.apply_user_defaults(tool)
defbuild(self):
""" Build the project in-situ. """
self.builder.build()
defbuild_sdist(self, sdist_directory):
""" Build an sdist for the project and return the name of the sdist
file.
"""
sdist_file=self.builder.build_sdist(sdist_directory)
self._remove_build_dir()
returnsdist_file
defbuild_wheel(self, wheel_directory):
""" Build a wheel for the project and return the name of the wheel
file.
"""
wheel_file=self.builder.build_wheel(wheel_directory)
self._remove_build_dir()
returnwheel_file
@property
defbuild_abi(self):
""" The ABI version to use to build against. This may be later than
the target version if we don't have the source of the target version.
It must not be called before the target ABI has been finalised.
"""
ifself._build_abiisNone:
major_version, minor_version=self.target_abi
oldest_source, _=get_source_version_range(major_version)
self._build_abi= (major_version, max(minor_version, oldest_source))
returnself._build_abi
defget_bindings_dir(self):
""" Return the name of the 'bindings' directory relative to the
eventual target directory.
"""
returnos.path.join(self.get_package_dir(), 'bindings')
defget_distinfo_dir(self, target_dir):
""" Return the name of the .dist-info directory for a target directory.
"""
returnos.path.join(target_dir,
'{}-{}.dist-info'.format(self.name.replace('-', '_'),
self.version_str))
defget_dunder_init(self):
""" Return the contents of the __init__.py to install. """
# This default implementation will create an empty file.
return''
defget_metadata_overrides(self):
""" Return a mapping of PEP 566 metadata names and values that will
override any corresponding values defined in the pyproject.toml file.
A typical use is to determine a project's version dynamically.
"""
# This default implementation does not override any metadata.
return {}
defget_options(self):
""" Return the list of configurable options. """
options=super().get_options()
options.extend(self._options)
options.extend(self._multibindings_options)
returnoptions
defget_package_dir(self):
""" Return the name of the package directory relative to the eventual
target directory. This is the directory containing the shared sip
module (if there is one) or the target directory (if not). It will
normally be where the individual bindings are installed.
"""
ifself.sip_module:
name_parts=self.sip_module.split('.')
delname_parts[-1]
returnos.path.join(*name_parts)
return''
defget_platform_tag(self):
""" Return the platform tag to use in a wheel name. This default
implementation uses the platform name and applies PEP defined
conventions depending on OS version and GLIBC version as appropriate.
"""
platform_tag=sysconfig.get_platform()
ifself.py_platform=='darwin':
# We expect a three part tag so leave anything else unchanged.
parts=platform_tag.split('-')
iflen(parts) ==3:
version=parts[1]
if'.'inversion:
min_major, min_minor=version.split('.')
min_major=int(min_major)
min_minor=int(min_minor)
else:
min_major=int(version)
min_minor=0
# Use the user supplied value if it is later than the platform
# value.
ifself.minimum_macos_version:
user_min_major=int(self.minimum_macos_version[0])
user_min_minor=int(self.minimum_macos_version[1])
if (min_major, min_minor) < (user_min_major, user_min_minor):
min_major=user_min_major
min_minor=user_min_minor
# Enforce a minimum macOS version for limited ABI projects.
ifself.all_modules_use_limited_abiand (min_major, min_minor) < (MACOS_MIN_OS_MAJOR, MACOS_MIN_OS_MINOR):
min_major=MACOS_MIN_OS_MAJOR
min_minor=MACOS_MIN_OS_MINOR
# Enforce a minimum macOS version for arm64 binaries.
ifparts[2] =='arm64'andmin_major<11:
min_major=11
min_minor=0
# Reassemble the tag.
parts[1] =f'{min_major}.{min_minor}'
platform_tag='-'.join(parts)
elifself.py_platform=='linux'andself.manylinux:
# We expect a two part tag so leave anything else unchanged.
parts=platform_tag.split('-')
iflen(parts) ==2:
ifself.minimum_glibc_version:
major, minor=self.minimum_glibc_version
else:
major, minor=2, 5
parts[0] ='manylinux'
parts.insert(1, f'{major}.{minor}')
platform_tag='-'.join(parts)
returnplatform_tag.replace('.', '_').replace('-', '_')
defget_requires_dists(self):
""" Return any 'Requires-Dist' to add to the project's meta-data. """
# The only requirement is for the sip module.
ifnotself.sip_module:
return []
requires_dist=self.metadata.get('requires-dist')
ifrequires_distisNone:
requires_dist= []
elifisinstance(requires_dist, str):
requires_dist= [requires_dist]
# Ignore if the module is already defined.
sip_project_name=self.sip_module.replace('.', '-')
forrdinrequires_dist:
ifrd.split()[0] ==sip_project_name:
return []
abi_major, abi_minor=self.target_abi
next_abi_major=abi_major+1
return [f'{sip_project_name} (>={abi_major}.{abi_minor}, <{next_abi_major})']
defget_sip_distinfo_command_line(self, sip_distinfo, inventory,
generator=None, wheel_tag=None, generator_version=None):
""" Return a sequence of command line arguments to invoke sip-distinfo.
"""
args= [
sip_distinfo,
'--inventory',
inventory,
'--project-root',
self.root_dir,
'--prefix',
'\\"$(INSTALL_ROOT)\\"',
]
ifgeneratorisnotNone:
args.append('--generator')
args.append(generator)
ifgenerator_versionisnotNone:
args.append('--generator-version')
args.append(generator_version)
ifwheel_tagisnotNone:
args.append('--wheel-tag')
args.append(wheel_tag)
forepinself.console_scripts:
args.append('--console-script')
args.append(ep.replace(' ', ''))
forepinself.gui_scripts:
args.append('--gui-script')
args.append(ep.replace(' ', ''))
forrdinself.get_requires_dists():
args.append('--requires-dist')
args.append('\\"{}\\"'.format(rd))
formetadata, valueinself._metadata_overrides.items():
ifvalue:
metadata+='='+value
if' 'inmetadata:
metadata='\\"'+metadata+'\\"'
args.append('--metadata')
args.append(metadata)
returnargs
definstall(self):
""" Install the project. """
self.builder.install()
self._remove_build_dir()
@property
defminimum_glibc_version(self):
""" The getter for the minimum GLIBC version. """
returnself._minimum_glibc_version
@minimum_glibc_version.setter
defminimum_glibc_version(self, value):
""" The setter for the minimum GLIBC version. """
# Handle the initial creation of the option value.
ifvalueisNoneandnothasattr(self, '_minimum_glibc_version'):
self._minimum_glibc_version=None
return
# Make sure any minimum GLIBC version is valid and convert it to a
# 2-tuple.
ifvalue:
try:
value=self._convert_major_minor(value)
exceptValueError:
raisePyProjectOptionException('minimum-glibc-version',
"'{0}' is an invalid GLIBC version number".format(
value),
section_name='tool.sip.project')
self._minimum_glibc_version=value
@property
defminimum_macos_version(self):
""" The getter for the minimum macOS version. """
returnself._minimum_macos_version
@minimum_macos_version.setter
defminimum_macos_version(self, value):
""" The setter for the minimum macOS version. """
# Handle the initial creation of the option value.
ifvalueisNoneandnothasattr(self, '_minimum_macos_version'):
self._minimum_macos_version=None
return
# Make sure any minimum macOS version is valid and convert it to a
# 2-tuple.
ifvalue:
try:
value=self._convert_major_minor(value)
exceptValueError:
raisePyProjectOptionException('minimum-macos-version',
"'{0}' is an invalid macOS version number".format(
value),
section_name='tool.sip.project')
self._minimum_macos_version=value
@staticmethod
defopen_for_writing(fname):
""" Open a file for writing while handling any errors. """
try:
returnopen(fname, 'w')
exceptIOErrorase:
raiseUserException(
"There was an error creating '{0}' - make sure you have "
" write permission on the parent directory".format(fname),
detail=str(e))
defprogress(self, message):
""" Print a progress message unless they are disabled. """
ifnotself.quiet:
ifmessage[-1] !='.':
message+='...'
print(message, flush=True)
defproject_path(self, path, relative_to=None):
""" Return a normalised version of a path. A relative path is assumed
to be relate to the project directory or some other provided directory.
"""
path=os.path.normpath(path)
ifos.path.isabs(path):
returnpath
ifrelative_toisNone:
relative_to=self.root_dir
returnos.path.normpath(os.path.join(relative_to, path))
defread_command_pipe(self, args, *, and_stderr=False, fatal=True):
""" A generator for each line of a pipe from a command's stdout. """
cmd=' '.join(args)
ifself.verbose:
print(cmd, flush=True)
stderr=subprocess.STDOUTifand_stderrelsesubprocess.PIPE
withsubprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=stderr) aspipe:
forlineinpipe.stdout:
yieldstr(line, encoding=sys.stdout.encoding)
ifpipe.returncode!=0andfatal:
raiseUserException(
"'{0}' failed returning {1}".format(cmd, pipe.returncode))
defrun_command(self, args, *, fatal=True):
""" Run a command and display the output if requested. """
# Read stdout and stderr until there is no more output.
forlineinself.read_command_pipe(args, and_stderr=True, fatal=fatal):
ifself.verbose:
sys.stdout.write(line)
defsetup(self, pyproject, tool, tool_description):
""" Complete the configuration of the project. """
# Create any programmatically defined bindings.
forbindings_factoryinself.bindings_factories:
bindings=bindings_factory(self)
self.bindings[bindings.name] =bindings
# Set the initial configuration from the pyproject.toml file.
self._set_initial_configuration(pyproject, tool)
# Add any tool-specific command line arguments for (so far unspecified)
# parts of the configuration.
self._configure_from_arguments(tool, tool_description)
# Now that any help has been given we can report a missing
# pyproject.toml file.
ifpyproject.pyprojectisNone:
raisePyProjectException(
"there is no such file in the current directory")
# Make sure the configuration is complete.
self.apply_user_defaults(tool)
# Configure the warnings module.
ifnotself.verbose:
warnings.simplefilter('ignore', UserWarning)
# Make sure we have a clean build directory and make it current.
ifself._temp_build_dirisNone:
self.build_dir=os.path.abspath(self.build_dir)
shutil.rmtree(self.build_dir, ignore_errors=True)
os.mkdir(self.build_dir)
os.chdir(self.build_dir)
# Allow a sub-class (in a user supplied script) to make any updates to
# the configuration.
self.update(tool)
os.chdir(self.root_dir)
# Make sure the configuration is correct after any user supplied script
# has messed with it.
self.verify_configuration(tool)
iftoolinOption.BUILD_TOOLSandself.bindings:
self.progress(
"These bindings will be built: {}.".format(
', '.join(self.bindings.keys())))
defupdate(self, tool):
""" This should be re-implemented by any user supplied sub-class to
carry out any updates to the configuration as required. The current
directory will be the temporary build directory.
"""
# This default implementation calls update_buildable_bindings().
iftoolinOption.BUILD_TOOLS:
self.update_buildable_bindings()
defupdate_buildable_bindings(self):
""" Update the list of bindings to ensure they are either buildable or
have been explicitly enabled.
"""
# Explicitly enabled bindings are assumed to be buildable.
ifself.enable:
return
forbinlist(self.bindings.values()):
ifnotb.is_buildable():
delself.bindings[b.name]
iflen(self.bindings) ==0:
raiseUserException("There are no bindings that can be built")
defverify_configuration(self, tool):
""" Verify that the configuration is complete and consistent. """
# Make sure any build tag is valid.
ifself.build_tagandnotself.build_tag[0].isdigit():
raisePyProjectOptionException('build-tag',
"'{0}' must begin with a digit".format(self.build_tag),
section_name='tool.sip.project')
# Make sure relevent paths are absolute and use native separators.
self.sip_files_dir=self.project_path(self.sip_files_dir)
self.sip_include_dirs= [self.project_path(d)
fordinself.sip_include_dirs]
# Check that the targeted version of Python isn't too old. We hope
# that we will support newer versions automatically, but it's not
# guaranteed.
py_version= (self.py_major_version, self.py_minor_version)
first_version= (3, OLDEST_SUPPORTED_MINOR)
ifpy_version<first_versionorself.py_major_version>3:
raiseUserException(
"Python v{}.{} is not supported".format(
self.py_major_version, self.py_minor_version))
# Get the provisional ABI version to target.
ifself.abi_version:
self.target_abi=parse_abi_version(self.abi_version)
# Checks for standalone projects.
iftoolinOption.BUILD_TOOLSandnotself.sip_module:
# Check there is only one set of bindings.
iflen(self.bindings) >1:
raisePyProjectOptionException('sip-module',
"must be defined when the project contains multiple "
"sets of bindings")
# Make sure __init__.py is disabled.
self.dunder_init=False
# Check any wheel includes are valid and make sure all elements are
# 2-tuples.
normalised= []
forwheel_includeinself.wheel_includes:
ifisinstance(wheel_include, str):
normalised.append((wheel_include, None))
else:
try:
wheel_include, subdir=wheel_include
exceptTypeError:
wheel_include=subdir=None
ifisinstance(wheel_include, str) andisinstance(subdir, str):
normalised.append((wheel_include, subdir))
else:
raisePyProjectOptionException('wheel-includes',
"elements must be strings or 2-tuples of strings")
self.wheel_includes=normalised
# Make sure that any .api directory is relative when building a wheel.
iftool=='wheel'andself.api_dir:
ifos.path.isabs(self.api_dir) oros.path.dirname(self.api_dir) =='..':
raisePyProjectOptionException('api-dir',
"must be relative when building a wheel")
# Verify the configuration of the builder and bindings.
self.builder.verify_configuration(tool)
forbindingsinself.bindings.values():
bindings.verify_configuration(tool)
def_configure_from_arguments(self, tool, tool_description):
""" Update the configuration from any user supplied arguments. """
fromargparseimportSUPPRESS
from .argument_parserimportArgumentParser
parser=ArgumentParser(tool_description, build_tool=True,
argument_default=SUPPRESS)
# Add the user configurable options to the parser.
all_options= {}
options=self.get_options()
iflen(self.bindings) <2:
# Remove the options that only make sense where the project has
# multiple bindings.
formultiinself._multibindings_options:
options.remove(multi)
self.add_command_line_options(parser, tool, all_options,
options=options)
self.builder.add_command_line_options(parser, tool, all_options)
forbindingsinself.bindings.values():
bindings.add_command_line_options(parser, tool, all_options)
# Parse the arguments and update the corresponding configurables.
args=parser.parse_args(self.arguments)
foroption, configurablesinall_options.items():
forconfigurableinconfigurables:
ifhasattr(args, option.dest):
setattr(configurable, option.name,
getattr(args, option.dest))
@staticmethod
def_convert_major_minor(value):
""" Convert a 'major.minor' version number to a 2-tuple of integers.
Raise a ValueError exception if it is invalid.
"""
parts=value.split('.')
iflen(parts) !=2:
raiseValueError()
returnint(parts[0]), int(parts[1])
def_enable_disable_bindings(self):
""" Check the enabled bindings are valid and remove any disabled ones.
"""
names=list(self.bindings.keys())
# Check that any explicitly enabled bindings are valid.
ifself.enable:
forenabledinself.enable:
ifenablednotinnames:
raiseUserException(
"Unknown enabled bindings '{0}'".format(enabled))
# Only include explicitly enabled bindings.
forbinlist(self.bindings.values()):
ifb.namenotinself.enable:
delself.bindings[b.name]
# Check that any explicitly disabled bindings are valid.
ifself.disable:
fordisabledinself.disable:
ifdisablednotinnames:
raiseUserException(
"Unknown disabled bindings '{0}'".format(disabled))
# Remove any explicitly disabled bindings.
forbinlist(self.bindings.values()):
ifb.nameinself.disable:
delself.bindings[b.name]
def_remove_build_dir(self):
""" Remove the build directory. """
self._temp_build_dir=None
def_set_initial_configuration(self, pyproject, tool):
""" Set the project's initial configuration. """
# Get the metadata and extract the version.
self.metadata=pyproject.get_metadata()
self._metadata_overrides=self.get_metadata_overrides()
self.metadata.update(self._metadata_overrides)
self.version_str=self.metadata['version']
# Convert the version as a string to number.
base_version=packaging.version.parse(self.version_str).base_version
base_version=base_version.split('.')
whilelen(base_version) <3:
base_version.append('0')
version=0
forpartinbase_version:
version<<=8
try:
version+=int(part)
exceptValueError:
raisePyProjectOptionException('version',
"'{0}' is an invalid version number".format(
self.version_str),
section_name='tool.sip.metadata')
self.version=version
# Configure the project.
self.configure(pyproject, 'tool.sip.project', tool)
# Create and configure the builder.
self.builder=self.builder_factory(self)
self.builder.configure(pyproject, 'tool.sip.builder', tool)
# For each set of bindings configuration make sure a bindings object
# exists, creating it if necessary.
bindings_sections=pyproject.get_section('tool.sip.bindings')
ifbindings_sectionsisnotNone:
fornameinbindings_sections.keys():
ifnamenotinself.bindings:
bindings=self.bindings_factory(self, name)
self.bindings[bindings.name] =bindings
# Add a default set of bindings if none were defined.
ifnotself.bindings:
bindings=self.bindings_factory(self, self.metadata['name'])
self.bindings[bindings.name] =bindings
# Now configure each set of bindings.
forbindingsinself.bindings.values():
bindings.configure(pyproject, 'tool.sip.bindings.'+bindings.name,
tool)