forked from pymupdf/PyMuPDF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipcl.py
2246 lines (1943 loc) · 79.2 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 setuptools
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'),
... (f'build/{so_leaf}', f'foo/'),
... ('README', '$dist-info/'),
... ]
...
... def sdist():
... return [
... 'foo.i',
... 'bar.i',
... 'setup.py',
... 'pipcl.py',
... 'wdev.py',
... 'README',
... ]
...
... p = pipcl.Package(
... name = 'foo',
... version = '1.2.3',
... fn_build = build,
... fn_sdist = sdist,
... )
...
... 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.
... """))
>>> 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
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,
root = None,
fn_build = None,
fn_clean = None,
fn_sdist = None,
tag_python = None,
tag_abi = None,
tag_platform = 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, a 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.
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 of
two strings `(from_, to_)`, or a single string `path` which is
treated as the tuple `(path, path)`.
`from_` should be the path to a file; if a relative path it is
assumed to be relative to `root`.
`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.
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 paths for
files that should be copied into the sdist. Each item in the
list can also be a tuple `(from_, to_)`, where `from_` is the
path of a file and `to_` is its name within the sdist.
Relative paths are interpreted as relative to `root`. It is an
error if a path does not exist or is not a file.
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 `setuptools.distutils.util.get_platform()` (was
`distutils.util.get_platform()` as specified in the PEP), e.g.
`openbsd_7_0_amd64`.
For pure python packages use: `tag_platform=any`
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}'
# PEP-440.
assert re.match(
r'^([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*((a|b|rc)(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))?(\.dev(0|[1-9][0-9]*))?$',
version,
), \
f'Bad version: {version!r}.'
# 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.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.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}'
)
# Get two-digit python version, e.g. 'cp3.8' for python-3.8.6.
#
if self.tag_python:
tag_python = self.tag_python
else:
tag_python = 'cp' + ''.join(platform.python_version().split('.')[:2])
# ABI tag.
if self.tag_abi:
tag_abi = self.tag_abi
else:
tag_abi = 'none'
# Find platform tag used in wheel filename.
#
tag_platform = None
if not tag_platform:
tag_platform = self.tag_platform
if not tag_platform:
# 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
tag_platform = os.environ.get( 'AUDITWHEEL_PLAT')
if not tag_platform:
# PEP-425. On Linux gives `linux_x86_64` which is rejected by
# pypi.org.
#
tag_platform = setuptools.distutils.util.get_platform().replace('-', '_').replace('.', '_')
# 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].+)$', tag_platform)
if m:
tag_platform2 = f'{m.group(1)}_0{m.group(2)}'
log2( f'Changing from {tag_platform!r} to {tag_platform2!r}')
tag_platform = tag_platform2
# Final tag is, for example, 'cp39-none-win32', 'cp39-none-win_amd64'
# or 'cp38-none-openbsd_6_8_amd64'.
#
tag = f'{tag_python}-{tag_abi}-{tag_platform}'
path = f'{wheel_directory}/{self.name}-{self.version}-{tag}.whl'
# 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_file(from_, to_):
z.write(from_, to_)
record.add_file(from_, to_)
def add_str(content, to_):
z.writestr(to_, content)
record.add_content(content, to_)
dist_info_dir = self._dist_info_dir()
# Add the files returned by fn_build().
#
for item in items:
(from_abs, from_rel), (to_abs, to_rel) = self._fromto(item)
add_file(from_abs, 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: {tag}\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')
# 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()
manifest = []
names_in_tar = []
def check_name(name):
if name in names_in_tar:
raise Exception(f'Name specified twice: {name}')
names_in_tar.append(name)
prefix = f'{self.name}-{self.version}'
def add_content(tar, name, contents):
'''
Adds item called `name` to `tarfile.TarInfo` `tar`, containing
`contents`. If contents is a string, it is encoded using utf8.
'''
log2( f'Adding: {name}')
if isinstance(contents, str):
contents = contents.encode('utf8')
check_name(name)
ti = tarfile.TarInfo(f'{prefix}/{name}')
ti.size = len(contents)
ti.mtime = time.time()
tar.addfile(ti, io.BytesIO(contents))
def add_file(tar, path_abs, name):
log2( f'Adding file: {os.path.relpath(path_abs)} => {name}')
check_name(name)
tar.add( path_abs, f'{prefix}/{name}', recursive=False)
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:
found_pyproject_toml = False
for item in items:
(from_abs, from_rel), (to_abs, to_rel) = self._fromto(item)
if from_abs.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_abs!r}'
assert os.path.exists(from_abs), f'Path does not exist: {from_abs!r}'
assert os.path.isfile(from_abs), f'Path is not a file: {from_abs!r}'
if to_rel == 'pyproject.toml':
found_pyproject_toml = True
add_file( tar, from_abs, to_rel)
manifest.append(to_rel)
if not found_pyproject_toml:
log0(f'Warning: no pyproject.toml specified.')
# Always add a PKG-INFO file.
add_content(tar, f'PKG-INFO', self._metainfo())
if self.license:
if 'COPYING' in names_in_tar:
log2(f'Not writing .license because file already in sdist: COPYING')
else:
add_content(tar, f'COPYING', self.license)
log1( f'Have created sdist: {tarpath}')
return os.path.basename(tarpath)
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_abs, from_rel, to_abs, to_rel):
log2(f'Copying from {from_rel} to {to_abs}')
os.makedirs( os.path.dirname( to_abs), exist_ok=True)
shutil.copy2( from_abs, to_abs)
record.add_file(from_rel, 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_abs, from_rel), (to_abs, to_rel) = self._fromto(item)
to_abs2 = f'{root2}/{to_rel}'
add_file( from_abs, from_rel, to_abs2, to_rel)
add_str( self._metainfo(), f'{root2}/{dist_info_dir}/METADATA', f'{dist_info_dir}/METADATA')
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()`.
'''
if egg_base is None:
egg_base = '.'
self._write_info(f'{egg_base}/.egg-info')
def _write_info(self, dirpath=None):
'''
Writes egg/dist info to files in directory `dirpath` or `self.root` if
`None`.
'''
if dirpath is None:
dirpath = self.root
log2(f'Creating files in directory {dirpath}')
os.makedirs(dirpath, exist_ok=True)
with open(os.path.join(dirpath, 'PKG-INFO'), 'w') as f:
f.write(self._metainfo())
# These don't seem to be required?
#
#with open(os.path.join(dirpath, 'SOURCES.txt', 'w') as f:
# pass
#with open(os.path.join(dirpath, 'dependency_links.txt', 'w') as f:
# pass
#with open(os.path.join(dirpath, 'top_level.txt', 'w') as f:
# f.write(f'{self.name}\n')
#with open(os.path.join(dirpath, 'METADATA', 'w') as f:
# f.write(self._metainfo())
def handle_argv(self, argv):
'''
Attempt to handles old-style (pre PEP-517) command line passed by
old releases of pip to a `setup.py` script, and manual running of
`setup.py`.
This is partial support at best.
'''
global g_verbose
#log2(f'argv: {argv}')
class ArgsRaise:
pass
class Args:
'''
Iterates over argv items.
'''
def __init__( self, argv):
self.items = iter( argv)
def next( self, eof=ArgsRaise):
'''
Returns next arg. If no more args, we return <eof> or raise an
exception if <eof> is ArgsRaise.
'''
try:
return next( self.items)
except StopIteration:
if eof is ArgsRaise:
raise Exception('Not enough args')
return eof
command = None
opt_all = None
opt_dist_dir = 'dist'
opt_egg_base = None
opt_formats = None
opt_install_headers = None
opt_record = None
opt_root = None
args = Args(argv[1:])
while 1:
arg = args.next(None)
if arg is None:
break
elif arg in ('-h', '--help', '--help-commands'):
log0(textwrap.dedent('''
Usage:
[<options>...] <command> [<options>...]
Commands:
bdist_wheel
Creates a wheel called
<dist-dir>/<name>-<version>-<details>.whl, where
<dist-dir> is "dist" or as specified by --dist-dir,
and <details> encodes ABI and platform etc.
clean
Cleans build files.
dist_info
Creates files in <name>-<version>.dist-info/ or
directory specified by --egg-base.
egg_info
Creates files in .egg-info/ or directory
directory specified by --egg-base.
install
Builds and installs. Writes installation
information to <record> if --record was
specified.
sdist
Make a source distribution:
<dist-dir>/<name>-<version>.tar.gz
Options:
--all
Used by "clean".
--compile
Ignored.
--dist-dir | -d <dist-dir>
Default is "dist".
--egg-base <egg-base>
Used by "egg_info".
--formats <formats>
Used by "sdist".
--install-headers <directory>
Ignored.
--python-tag <python-tag>
Ignored.
--record <record>
Used by "install".
--root <path>
Used by "install".
--single-version-externally-managed
Ignored.
--verbose -v
Extra diagnostics.
Other:
windows-vs [-y <year>] [-v <version>] [-g <grade] [--verbose]
Windows only; looks for matching Visual Studio.
windows-python [-v <version>] [--verbose]
Windows only; looks for matching Python.
'''))
return
elif arg in ('bdist_wheel', 'clean', 'dist_info', 'egg_info', 'install', 'sdist'):
assert command is None, 'Two commands specified: {command} and {arg}.'
command = arg
elif arg == '--all': opt_all = True
elif arg == '--compile': pass
elif arg == '--dist-dir' or arg == '-d': opt_dist_dir = args.next()
elif arg == '--egg-base': opt_egg_base = args.next()
elif arg == '--formats': opt_formats = args.next()
elif arg == '--install-headers': opt_install_headers = args.next()
elif arg == '--python-tag': pass
elif arg == '--record': opt_record = args.next()
elif arg == '--root': opt_root = args.next()
elif arg == '--single-version-externally-managed': pass
elif arg == '--verbose' or arg == '-v': g_verbose += 1
elif arg == 'windows-vs':
command = arg
break
elif arg == 'windows-python':
command = arg
break
else:
raise Exception(f'Unrecognised arg: {arg}')
assert command, 'No command specified'
log1(f'Handling command={command}')
if 0: pass
elif command == 'bdist_wheel': self.build_wheel(opt_dist_dir)
elif command == 'clean': self._argv_clean(opt_all)
elif command == 'dist_info': self._argv_dist_info(opt_egg_base)
elif command == 'egg_info': self._argv_egg_info(opt_egg_base)
elif command == 'install': self.install(opt_record, opt_root)
elif command == 'sdist': self.build_sdist(opt_dist_dir, opt_formats)
elif command == 'windows-python':
version = None
while 1:
arg = args.next(None)
if arg is None: