-
Notifications
You must be signed in to change notification settings - Fork 511
/
pipcl.py
2570 lines (2226 loc) · 91.6 KB
/
pipcl.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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Python packaging operations, including PEP-517 support, for use by a `setup.py`
script.
The intention is to take care of as many packaging details as possible so that
setup.py contains only project-specific information, while also giving as much
flexibility as possible.
For example we provide a function `build_extension()` that can be used to build
a SWIG extension, but we also give access to the located compiler/linker so
that a `setup.py` script can take over the details itself.
Run doctests with: `python -m doctest pipcl.py`
'''
import base64
import glob
import hashlib
import inspect
import io
import os
import platform
import re
import shutil
import site
import subprocess
import sys
import sysconfig
import tarfile
import textwrap
import time
import zipfile
import wdev
class Package:
'''
Our constructor takes a definition of a Python package similar to that
passed to `distutils.core.setup()` or `setuptools.setup()` (name, version,
summary etc) plus callbacks for building, getting a list of sdist
filenames, and cleaning.
We provide methods that can be used to implement a Python package's
`setup.py` supporting PEP-517.
We also support basic command line handling for use
with a legacy (pre-PEP-517) pip, as implemented
by legacy distutils/setuptools and described in:
https://pip.pypa.io/en/stable/reference/build-system/setup-py/
Here is a `doctest` example of using pipcl to create a SWIG extension
module. Requires `swig`.
Create an empty test directory:
>>> import os
>>> import shutil
>>> shutil.rmtree('pipcl_test', ignore_errors=1)
>>> os.mkdir('pipcl_test')
Create a `setup.py` which uses `pipcl` to define an extension module.
>>> import textwrap
>>> with open('pipcl_test/setup.py', 'w') as f:
... _ = f.write(textwrap.dedent("""
... import sys
... import pipcl
...
... def build():
... so_leaf = pipcl.build_extension(
... name = 'foo',
... path_i = 'foo.i',
... outdir = 'build',
... )
... return [
... ('build/foo.py', 'foo/__init__.py'),
... ('cli.py', 'foo/__main__.py'),
... (f'build/{so_leaf}', f'foo/'),
... ('README', '$dist-info/'),
... (b'Hello world', 'foo/hw.txt'),
... ]
...
... def sdist():
... return [
... 'foo.i',
... 'bar.i',
... 'setup.py',
... 'pipcl.py',
... 'wdev.py',
... 'README',
... (b'Hello word2', 'hw2.txt'),
... ]
...
... p = pipcl.Package(
... name = 'foo',
... version = '1.2.3',
... fn_build = build,
... fn_sdist = sdist,
... entry_points = (
... { 'console_scripts': [
... 'foo_cli = foo.__main__:main',
... ],
... }),
... )
...
... build_wheel = p.build_wheel
... build_sdist = p.build_sdist
...
... # Handle old-style setup.py command-line usage:
... if __name__ == '__main__':
... p.handle_argv(sys.argv)
... """))
Create the files required by the above `setup.py` - the SWIG `.i` input
file, the README file, and copies of `pipcl.py` and `wdev.py`.
>>> with open('pipcl_test/foo.i', 'w') as f:
... _ = f.write(textwrap.dedent("""
... %include bar.i
... %{
... #include <stdio.h>
... #include <string.h>
... int bar(const char* text)
... {
... printf("bar(): text: %s\\\\n", text);
... int len = (int) strlen(text);
... printf("bar(): len=%i\\\\n", len);
... fflush(stdout);
... return len;
... }
... %}
... int bar(const char* text);
... """))
>>> with open('pipcl_test/bar.i', 'w') as f:
... _ = f.write( '\\n')
>>> with open('pipcl_test/README', 'w') as f:
... _ = f.write(textwrap.dedent("""
... This is Foo.
... """))
>>> with open('pipcl_test/cli.py', 'w') as f:
... _ = f.write(textwrap.dedent("""
... def main():
... print('pipcl_test:main().')
... if __name__ == '__main__':
... main()
... """))
>>> root = os.path.dirname(__file__)
>>> _ = shutil.copy2(f'{root}/pipcl.py', 'pipcl_test/pipcl.py')
>>> _ = shutil.copy2(f'{root}/wdev.py', 'pipcl_test/wdev.py')
Use `setup.py`'s command-line interface to build and install the extension
module into root `pipcl_test/install`.
>>> _ = subprocess.run(
... f'cd pipcl_test && {sys.executable} setup.py --root install install',
... shell=1, check=1)
The actual install directory depends on `sysconfig.get_path('platlib')`:
>>> if windows():
... install_dir = 'pipcl_test/install'
... else:
... install_dir = f'pipcl_test/install/{sysconfig.get_path("platlib").lstrip(os.sep)}'
>>> assert os.path.isfile( f'{install_dir}/foo/__init__.py')
Create a test script which asserts that Python function call `foo.bar(s)`
returns the length of `s`, and run it with `PYTHONPATH` set to the install
directory:
>>> with open('pipcl_test/test.py', 'w') as f:
... _ = f.write(textwrap.dedent("""
... import sys
... import foo
... text = 'hello'
... print(f'test.py: calling foo.bar() with text={text!r}')
... sys.stdout.flush()
... l = foo.bar(text)
... print(f'test.py: foo.bar() returned: {l}')
... assert l == len(text)
... """))
>>> r = subprocess.run(
... f'{sys.executable} pipcl_test/test.py',
... shell=1, check=1, text=1,
... stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
... env=os.environ | dict(PYTHONPATH=install_dir),
... )
>>> print(r.stdout)
test.py: calling foo.bar() with text='hello'
bar(): text: hello
bar(): len=5
test.py: foo.bar() returned: 5
<BLANKLINE>
Check that building sdist and wheel succeeds. For now we don't attempt to
check that the sdist and wheel actually work.
>>> _ = subprocess.run(
... f'cd pipcl_test && {sys.executable} setup.py sdist',
... shell=1, check=1)
>>> _ = subprocess.run(
... f'cd pipcl_test && {sys.executable} setup.py bdist_wheel',
... shell=1, check=1)
Check that rebuild does nothing.
>>> t0 = os.path.getmtime('pipcl_test/build/foo.py')
>>> _ = subprocess.run(
... f'cd pipcl_test && {sys.executable} setup.py bdist_wheel',
... shell=1, check=1)
>>> t = os.path.getmtime('pipcl_test/build/foo.py')
>>> assert t == t0
Check that touching bar.i forces rebuild.
>>> os.utime('pipcl_test/bar.i')
>>> _ = subprocess.run(
... f'cd pipcl_test && {sys.executable} setup.py bdist_wheel',
... shell=1, check=1)
>>> t = os.path.getmtime('pipcl_test/build/foo.py')
>>> assert t > t0
Check that touching foo.i.cpp does not run swig, but does recompile/link.
>>> t0 = time.time()
>>> os.utime('pipcl_test/build/foo.i.cpp')
>>> _ = subprocess.run(
... f'cd pipcl_test && {sys.executable} setup.py bdist_wheel',
... shell=1, check=1)
>>> assert os.path.getmtime('pipcl_test/build/foo.py') <= t0
>>> so = glob.glob('pipcl_test/build/*.so')
>>> assert len(so) == 1
>>> so = so[0]
>>> assert os.path.getmtime(so) > t0
Check `entry_points` causes creation of command `foo_cli` when we install
from our wheel using pip. [As of 2024-02-24 using pipcl's CLI interface
directly with `setup.py install` does not support entry points.]
>>> print('Creating venv.', file=sys.stderr)
>>> _ = subprocess.run(
... f'cd pipcl_test && {sys.executable} -m venv pylocal',
... shell=1, check=1)
>>> print('Installing from wheel into venv using pip.', file=sys.stderr)
>>> _ = subprocess.run(
... f'. pipcl_test/pylocal/bin/activate && pip install pipcl_test/dist/*.whl',
... shell=1, check=1)
>>> print('Running foo_cli.', file=sys.stderr)
>>> _ = subprocess.run(
... f'. pipcl_test/pylocal/bin/activate && foo_cli',
... shell=1, check=1)
Wheels and sdists
Wheels:
We generate wheels according to:
https://packaging.python.org/specifications/binary-distribution-format/
* `{name}-{version}.dist-info/RECORD` uses sha256 hashes.
* We do not generate other `RECORD*` files such as
`RECORD.jws` or `RECORD.p7s`.
* `{name}-{version}.dist-info/WHEEL` has:
* `Wheel-Version: 1.0`
* `Root-Is-Purelib: false`
* No support for signed wheels.
Sdists:
We generate sdist's according to:
https://packaging.python.org/specifications/source-distribution-format/
'''
def __init__(self,
name,
version,
*,
platform = None,
supported_platform = None,
summary = None,
description = None,
description_content_type = None,
keywords = None,
home_page = None,
download_url = None,
author = None,
author_email = None,
maintainer = None,
maintainer_email = None,
license = None,
classifier = None,
requires_dist = None,
requires_python = None,
requires_external = None,
project_url = None,
provides_extra = None,
entry_points = None,
root = None,
fn_build = None,
fn_clean = None,
fn_sdist = None,
tag_python = None,
tag_abi = None,
tag_platform = None,
py_limited_api = None,
wheel_compression = zipfile.ZIP_DEFLATED,
wheel_compresslevel = None,
):
'''
The initial args before `root` define the package
metadata and closely follow the definitions in:
https://packaging.python.org/specifications/core-metadata/
Args:
name:
A string, the name of the Python package.
version:
A string, the version of the Python package. Also see PEP-440
`Version Identification and Dependency Specification`.
platform:
A string or list of strings.
supported_platform:
A string or list of strings.
summary:
A string, short description of the package.
description:
A string. If contains newlines, a detailed description of the
package. Otherwise the path of a file containing the detailed
description of the package.
description_content_type:
A string describing markup of `description` arg. For example
`text/markdown; variant=GFM`.
keywords:
A string containing comma-separated keywords.
home_page:
URL of home page.
download_url:
Where this version can be downloaded from.
author:
Author.
author_email:
Author email.
maintainer:
Maintainer.
maintainer_email:
Maintainer email.
license:
A string containing the license text. Written into metadata
file `COPYING`. Is also written into metadata itself if not
multi-line.
classifier:
A string or list of strings. Also see:
* https://pypi.org/pypi?%3Aaction=list_classifiers
* https://pypi.org/classifiers/
requires_dist:
A string or list of strings. Also see PEP-508.
requires_python:
A string or list of strings.
requires_external:
A string or list of strings.
project_url:
A string or list of strings, each of the form: `{name}, {url}`.
provides_extra:
A string or list of strings.
entry_points:
String or dict specifying *.dist-info/entry_points.txt, for
example:
```
[console_scripts]
foo_cli = foo.__main__:main
```
or:
{ 'console_scripts': [
'foo_cli = foo.__main__:main',
],
}
See: https://packaging.python.org/en/latest/specifications/entry-points/
root:
Root of package, defaults to current directory.
fn_build:
A function taking no args, or a single `config_settings` dict
arg (as described in PEP-517), that builds the package.
Should return a list of items; each item should be a tuple
`(from_, to_)`, or a single string `path` which is treated as
the tuple `(path, path)`.
`from_` can be a string or a `bytes`. If a string it should
be the path to a file; a relative path is treated as relative
to `root`. If a `bytes` it is the contents of the file to be
added.
`to_` identifies what the file should be called within a wheel
or when installing. If `to_` ends with `/`, the leaf of `from_`
is appended to it (and `from_` must not be a `bytes`).
Initial `$dist-info/` in `_to` is replaced by
`{name}-{version}.dist-info/`; this is useful for license files
etc.
Initial `$data/` in `_to` is replaced by
`{name}-{version}.data/`. We do not enforce particular
subdirectories, instead it is up to `fn_build()` to specify
specific subdirectories such as `purelib`, `headers`,
`scripts`, `data` etc.
If we are building a wheel (e.g. `python setup.py bdist_wheel`,
or PEP-517 pip calls `self.build_wheel()`), we add file `from_`
to the wheel archive with name `to_`.
If we are installing (e.g. `install` command in
the argv passed to `self.handle_argv()`), then
we copy `from_` to `{sitepackages}/{to_}`, where
`sitepackages` is the installation directory, the
default being `sysconfig.get_path('platlib')` e.g.
`myvenv/lib/python3.9/site-packages/`.
fn_clean:
A function taking a single arg `all_` that cleans generated
files. `all_` is true iff `--all` is in argv.
For safety and convenience, can also returns a list of
files/directory paths to be deleted. Relative paths are
interpreted as relative to `root`. All paths are asserted to be
within `root`.
fn_sdist:
A function taking no args, or a single `config_settings` dict
arg (as described in PEP517), that returns a list of items to
be copied into the sdist. The list should be in the same format
as returned by `fn_build`.
It can be convenient to use `pipcl.git_items()`.
The specification for sdists requires that the list contains
`pyproject.toml`; we enforce this with a diagnostic rather than
raising an exception, to allow legacy command-line usage.
tag_python:
First element of wheel tag defined in PEP-425. If None we use
`cp{version}`.
For example if code works with any Python version, one can use
'py3'.
tag_abi:
Second element of wheel tag defined in PEP-425. If None we use
`none`.
tag_platform:
Third element of wheel tag defined in PEP-425. Default
is `os.environ('AUDITWHEEL_PLAT')` if set, otherwise
derived from `sysconfig.get_platform()` (was
`setuptools.distutils.util.get_platform(), before that
`distutils.util.get_platform()` as specified in the PEP), e.g.
`openbsd_7_0_amd64`.
For pure python packages use: `tag_platform=any`
py_limited_api:
If true we build wheels that use the Python Limited API. We use
the version of `sys.executable` to define `Py_LIMITED_API` when
compiling extensions, and use ABI tag `abi3` in the wheel name
if argument `tag_abi` is None.
wheel_compression:
Used as `zipfile.ZipFile()`'s `compression` parameter when
creating wheels.
wheel_compresslevel:
Used as `zipfile.ZipFile()`'s `compresslevel` parameter when
creating wheels.
'''
assert name
assert version
def assert_str( v):
if v is not None:
assert isinstance( v, str), f'Not a string: {v!r}'
def assert_str_or_multi( v):
if v is not None:
assert isinstance( v, (str, tuple, list)), f'Not a string, tuple or list: {v!r}'
assert_str( name)
assert_str( version)
assert_str_or_multi( platform)
assert_str_or_multi( supported_platform)
assert_str( summary)
assert_str( description)
assert_str( description_content_type)
assert_str( keywords)
assert_str( home_page)
assert_str( download_url)
assert_str( author)
assert_str( author_email)
assert_str( maintainer)
assert_str( maintainer_email)
assert_str( license)
assert_str_or_multi( classifier)
assert_str_or_multi( requires_dist)
assert_str( requires_python)
assert_str_or_multi( requires_external)
assert_str_or_multi( project_url)
assert_str_or_multi( provides_extra)
# https://packaging.python.org/en/latest/specifications/core-metadata/.
assert re.match('([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$', name, re.IGNORECASE), \
f'Bad name: {name!r}'
_assert_version_pep_440(version)
# https://packaging.python.org/en/latest/specifications/binary-distribution-format/
if tag_python:
assert '-' not in tag_python
if tag_abi:
assert '-' not in tag_abi
if tag_platform:
assert '-' not in tag_platform
self.name = name
self.version = version
self.platform = platform
self.supported_platform = supported_platform
self.summary = summary
self.description = description
self.description_content_type = description_content_type
self.keywords = keywords
self.home_page = home_page
self.download_url = download_url
self.author = author
self.author_email = author_email
self.maintainer = maintainer
self.maintainer_email = maintainer_email
self.license = license
self.classifier = classifier
self.requires_dist = requires_dist
self.requires_python = requires_python
self.requires_external = requires_external
self.project_url = project_url
self.provides_extra = provides_extra
self.entry_points = entry_points
self.root = os.path.abspath(root if root else os.getcwd())
self.fn_build = fn_build
self.fn_clean = fn_clean
self.fn_sdist = fn_sdist
self.tag_python_ = tag_python
self.tag_abi_ = tag_abi
self.tag_platform_ = tag_platform
self.py_limited_api = py_limited_api
self.wheel_compression = wheel_compression
self.wheel_compresslevel = wheel_compresslevel
def build_wheel(self,
wheel_directory,
config_settings=None,
metadata_directory=None,
):
'''
A PEP-517 `build_wheel()` function.
Also called by `handle_argv()` to handle the `bdist_wheel` command.
Returns leafname of generated wheel within `wheel_directory`.
'''
log2(
f' wheel_directory={wheel_directory!r}'
f' config_settings={config_settings!r}'
f' metadata_directory={metadata_directory!r}'
)
wheel_name = self.wheel_name()
path = f'{wheel_directory}/{wheel_name}'
# Do a build and get list of files to copy into the wheel.
#
items = list()
if self.fn_build:
items = self._call_fn_build(config_settings)
log2(f'Creating wheel: {path}')
os.makedirs(wheel_directory, exist_ok=True)
record = _Record()
with zipfile.ZipFile(path, 'w', self.wheel_compression, self.wheel_compresslevel) as z:
def add(from_, to_):
if isinstance(from_, str):
z.write(from_, to_)
record.add_file(from_, to_)
elif isinstance(from_, bytes):
z.writestr(to_, from_)
record.add_content(from_, to_)
else:
assert 0
def add_str(content, to_):
add(content.encode('utf8'), to_)
dist_info_dir = self._dist_info_dir()
# Add the files returned by fn_build().
#
for item in items:
from_, (to_abs, to_rel) = self._fromto(item)
add(from_, to_rel)
# Add <name>-<version>.dist-info/WHEEL.
#
add_str(
f'Wheel-Version: 1.0\n'
f'Generator: pipcl\n'
f'Root-Is-Purelib: false\n'
f'Tag: {self.wheel_tag_string()}\n'
,
f'{dist_info_dir}/WHEEL',
)
# Add <name>-<version>.dist-info/METADATA.
#
add_str(self._metainfo(), f'{dist_info_dir}/METADATA')
# Add <name>-<version>.dist-info/COPYING.
if self.license:
add_str(self.license, f'{dist_info_dir}/COPYING')
# Add <name>-<version>.dist-info/entry_points.txt.
entry_points_text = self._entry_points_text()
if entry_points_text:
add_str(entry_points_text, f'{dist_info_dir}/entry_points.txt')
# Update <name>-<version>.dist-info/RECORD. This must be last.
#
z.writestr(f'{dist_info_dir}/RECORD', record.get(f'{dist_info_dir}/RECORD'))
st = os.stat(path)
log1( f'Have created wheel size={st.st_size}: {path}')
if g_verbose >= 2:
with zipfile.ZipFile(path, compression=self.wheel_compression) as z:
log2(f'Contents are:')
for zi in sorted(z.infolist(), key=lambda z: z.filename):
log2(f' {zi.file_size: 10d} {zi.filename}')
return os.path.basename(path)
def build_sdist(self,
sdist_directory,
formats,
config_settings=None,
):
'''
A PEP-517 `build_sdist()` function.
Also called by `handle_argv()` to handle the `sdist` command.
Returns leafname of generated archive within `sdist_directory`.
'''
log2(
f' sdist_directory={sdist_directory!r}'
f' formats={formats!r}'
f' config_settings={config_settings!r}'
)
if formats and formats != 'gztar':
raise Exception( f'Unsupported: formats={formats}')
items = list()
if self.fn_sdist:
if inspect.signature(self.fn_sdist).parameters:
items = self.fn_sdist(config_settings)
else:
items = self.fn_sdist()
prefix = f'{self.name}-{self.version}'
os.makedirs(sdist_directory, exist_ok=True)
tarpath = f'{sdist_directory}/{prefix}.tar.gz'
log2(f'Creating sdist: {tarpath}')
with tarfile.open(tarpath, 'w:gz') as tar:
names_in_tar = list()
def check_name(name):
if name in names_in_tar:
raise Exception(f'Name specified twice: {name}')
names_in_tar.append(name)
def add(from_, name):
check_name(name)
if isinstance(from_, str):
log2( f'Adding file: {os.path.relpath(from_)} => {name}')
tar.add( from_, f'{prefix}/{name}', recursive=False)
elif isinstance(from_, bytes):
log2( f'Adding: {name}')
ti = tarfile.TarInfo(f'{prefix}/{name}')
ti.size = len(from_)
ti.mtime = time.time()
tar.addfile(ti, io.BytesIO(from_))
else:
assert 0
def add_string(text, name):
textb = text.encode('utf8')
return add(textb, name)
found_pyproject_toml = False
for item in items:
from_, (to_abs, to_rel) = self._fromto(item)
if isinstance(from_, bytes):
add(from_, to_rel)
else:
if from_.startswith(f'{os.path.abspath(sdist_directory)}/'):
# Source files should not be inside <sdist_directory>.
assert 0, f'Path is inside sdist_directory={sdist_directory}: {from_!r}'
assert os.path.exists(from_), f'Path does not exist: {from_!r}'
assert os.path.isfile(from_), f'Path is not a file: {from_!r}'
if to_rel == 'pyproject.toml':
found_pyproject_toml = True
add(from_, to_rel)
if not found_pyproject_toml:
log0(f'Warning: no pyproject.toml specified.')
# Always add a PKG-INFO file.
add_string(self._metainfo(), 'PKG-INFO')
if self.license:
if 'COPYING' in names_in_tar:
log2(f'Not writing .license because file already in sdist: COPYING')
else:
add_string(self.license, 'COPYING')
log1( f'Have created sdist: {tarpath}')
return os.path.basename(tarpath)
def wheel_tag_string(self):
'''
Returns <tag_python>-<tag_abi>-<tag_platform>.
'''
return f'{self.tag_python()}-{self.tag_abi()}-{self.tag_platform()}'
def tag_python(self):
'''
Get two-digit python version, e.g. 'cp3.8' for python-3.8.6.
'''
if self.tag_python_:
return self.tag_python_
else:
return 'cp' + ''.join(platform.python_version().split('.')[:2])
def tag_abi(self):
'''
ABI tag.
'''
if self.tag_abi_:
return self.tag_abi_
elif self.py_limited_api:
return 'abi3'
else:
return 'none'
def tag_platform(self):
'''
Find platform tag used in wheel filename.
'''
ret = self.tag_platform_
log0(f'From self.tag_platform_: {ret=}.')
if not ret:
# Prefer this to PEP-425. Appears to be undocumented,
# but set in manylinux docker images and appears
# to be used by cibuildwheel and auditwheel, e.g.
# https://github.com/rapidsai/shared-action-workflows/issues/80
ret = os.environ.get( 'AUDITWHEEL_PLAT')
log0(f'From AUDITWHEEL_PLAT: {ret=}.')
if not ret:
# Notes:
#
# PEP-425. On Linux gives `linux_x86_64` which is rejected by
# pypi.org.
#
# On local MacOS/arm64 mac-mini have seen sysconfig.get_platform()
# unhelpfully return `macosx-10.9-universal2` if `python3` is the
# system Python /usr/bin/python3; this happens if we source `.
# /etc/profile`.
#
ret = sysconfig.get_platform()
ret = ret.replace('-', '_').replace('.', '_').lower()
log0(f'From sysconfig.get_platform(): {ret=}.')
# We need to patch things on MacOS.
#
# E.g. `foo-1.2.3-cp311-none-macosx_13_x86_64.whl`
# causes `pip` to fail with: `not a supported wheel on this
# platform`. We seem to need to add `_0` to the OS version.
#
m = re.match( '^(macosx_[0-9]+)(_[^0-9].+)$', ret)
if m:
ret2 = f'{m.group(1)}_0{m.group(2)}'
log0(f'After macos patch, changing from {ret!r} to {ret2!r}.')
ret = ret2
log0( f'tag_platform(): returning {ret=}.')
return ret
def wheel_name(self):
return f'{self.name}-{self.version}-{self.tag_python()}-{self.tag_abi()}-{self.tag_platform()}.whl'
def wheel_name_match(self, wheel):
'''
Returns true if `wheel` matches our wheel. We basically require the
name to be the same, except that we accept platform tags that contain
extra items (see pep-0600/), for example we return true with:
self: foo-cp38-none-manylinux2014_x86_64.whl
wheel: foo-cp38-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
'''
log2(f'{wheel=}')
assert wheel.endswith('.whl')
wheel2 = wheel[:-len('.whl')]
name, version, tag_python, tag_abi, tag_platform = wheel2.split('-')
py_limited_api_compatible = False
if self.py_limited_api and tag_abi == 'abi3':
# Allow lower tag_python number.
m = re.match('cp([0-9]+)', tag_python)
tag_python_int = int(m.group(1))
m = re.match('cp([0-9]+)', self.tag_python())
tag_python_int_self = int(m.group(1))
if tag_python_int <= tag_python_int_self:
# This wheel uses Python stable ABI same or older than ours, so
# we can use it.
log2(f'py_limited_api; {tag_python=} compatible with {self.tag_python()=}.')
py_limited_api_compatible = True
log2(f'{self.name == name=}')
log2(f'{self.version == version=}')
log2(f'{self.tag_python() == tag_python=} {self.tag_python()=} {tag_python=}')
log2(f'{py_limited_api_compatible=}')
log2(f'{self.tag_abi() == tag_abi=}')
log2(f'{self.tag_platform() in tag_platform.split(".")=}')
log2(f'{self.tag_platform()=}')
log2(f'{tag_platform.split(".")=}')
ret = (1
and self.name == name
and self.version == version
and (self.tag_python() == tag_python or py_limited_api_compatible)
and self.tag_abi() == tag_abi
and self.tag_platform() in tag_platform.split('.')
)
log2(f'Returning {ret=}.')
return ret
def _entry_points_text(self):
if self.entry_points:
if isinstance(self.entry_points, str):
return self.entry_points
ret = ''
for key, values in self.entry_points.items():
ret += f'[{key}]\n'
for value in values:
ret += f'{value}\n'
return ret
def _call_fn_build( self, config_settings=None):
assert self.fn_build
log2(f'calling self.fn_build={self.fn_build}')
if inspect.signature(self.fn_build).parameters:
ret = self.fn_build(config_settings)
else:
ret = self.fn_build()
assert isinstance( ret, (list, tuple)), \
f'Expected list/tuple from {self.fn_build} but got: {ret!r}'
return ret
def _argv_clean(self, all_):
'''
Called by `handle_argv()`.
'''
if not self.fn_clean:
return
paths = self.fn_clean(all_)
if paths:
if isinstance(paths, str):
paths = paths,
for path in paths:
if not os.path.isabs(path):
path = ps.path.join(self.root, path)
path = os.path.abspath(path)
assert path.startswith(self.root+os.sep), \
f'path={path!r} does not start with root={self.root+os.sep!r}'
log2(f'Removing: {path}')
shutil.rmtree(path, ignore_errors=True)
def install(self, record_path=None, root=None):
'''
Called by `handle_argv()` to handle `install` command..
'''
log2( f'{record_path=} {root=}')
# Do a build and get list of files to install.
#
items = list()
if self.fn_build:
items = self._call_fn_build( dict())
root2 = install_dir(root)
log2( f'{root2=}')
log1( f'Installing into: {root2!r}')
dist_info_dir = self._dist_info_dir()
if not record_path:
record_path = f'{root2}/{dist_info_dir}/RECORD'
record = _Record()
def add_file(from_, to_abs, to_rel):
os.makedirs( os.path.dirname( to_abs), exist_ok=True)
if isinstance(from_, bytes):
log2(f'Copying content into {to_abs}.')
with open(to_abs, 'wb') as f:
f.write(from_)
record.add_content(from_, to_rel)
else:
log0(f'{from_=}')
log2(f'Copying from {os.path.relpath(from_, self.root)} to {to_abs}')
shutil.copy2( from_, to_abs)
record.add_file(from_, to_rel)
def add_str(content, to_abs, to_rel):
log2( f'Writing to: {to_abs}')
os.makedirs( os.path.dirname( to_abs), exist_ok=True)
with open( to_abs, 'w') as f:
f.write( content)
record.add_content(content, to_rel)
for item in items:
from_, (to_abs, to_rel) = self._fromto(item)
log0(f'{from_=} {to_abs=} {to_rel=}')
to_abs2 = f'{root2}/{to_rel}'
add_file( from_, to_abs2, to_rel)
add_str( self._metainfo(), f'{root2}/{dist_info_dir}/METADATA', f'{dist_info_dir}/METADATA')
if self.license:
add_str( self.license, f'{root2}/{dist_info_dir}/COPYING', f'{dist_info_dir}/COPYING')
entry_points_text = self._entry_points_text()
if entry_points_text:
add_str(
entry_points_text,
f'{root2}/{dist_info_dir}/entry_points.txt',
f'{dist_info_dir}/entry_points.txt',
)
log2( f'Writing to: {record_path}')
with open(record_path, 'w') as f:
f.write(record.get())
log2(f'Finished.')
def _argv_dist_info(self, root):
'''
Called by `handle_argv()`. There doesn't seem to be any documentation
for `setup.py dist_info`, but it appears to be like `egg_info` except
it writes to a slightly different directory.
'''
if root is None:
root = f'{self.name}-{self.version}.dist-info'
self._write_info(f'{root}/METADATA')
if self.license:
with open( f'{root}/COPYING', 'w') as f:
f.write( self.license)
def _argv_egg_info(self, egg_base):
'''
Called by `handle_argv()`.
'''