-
Notifications
You must be signed in to change notification settings - Fork 6
/
pypi2pkgbuild.py
executable file
·1597 lines (1444 loc) · 62.2 KB
/
pypi2pkgbuild.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
#!/usr/bin/env python
"""Convert PyPI entries to Arch Linux packages."""
import abc
from abc import ABC
from argparse import (Action, ArgumentParser, ArgumentDefaultsHelpFormatter,
RawDescriptionHelpFormatter)
import ast
from collections import namedtuple
from contextlib import suppress
from functools import lru_cache
import hashlib
import importlib.metadata
from io import StringIO
import json
import logging
import os
from pathlib import Path
import re
import shlex
import shutil
import site
import subprocess
from subprocess import CalledProcessError, PIPE
import sys
from tempfile import NamedTemporaryFile, TemporaryDirectory
import textwrap
import urllib.request
try:
import setuptools_scm
__version__ = setuptools_scm.get_version( # xref setup.py
root=".", relative_to=__file__,
version_scheme="post-release", local_scheme="node-and-date")
except (ImportError, LookupError):
try:
__version__ = importlib.metadata.version("pypi2pkgbuild")
except ModuleNotFoundError:
__version__ = "(unknown version)"
LOGGER = logging.getLogger(Path(__file__).stem)
PKGTYPES = ["anywheel", "sdist", "manylinuxwheel"]
PY_TAGS = ["py{0.major}".format(sys.version_info),
"cp{0.major}".format(sys.version_info),
"py{0.major}{0.minor}".format(sys.version_info),
"cp{0.major}{0.minor}".format(sys.version_info)]
THIS_ARCH = ["i686", "x86_64"][sys.maxsize > 2 ** 32]
LICENSE_NAMES = ["LICENSE", "LICENSE.txt", "license.txt",
"COPYING", "COPYING.md", "COPYING.rst", "COPYING.txt",
"COPYRIGHT"]
TROVE_COMMON_LICENSES = { # Licenses provided by base `licenses` package.
"GNU Affero General Public License v3":
"AGPL3",
"GNU Affero General Public License v3 or later (AGPLv3+)":
"AGPL3",
"Apache Software License":
"Apache",
"Artistic License":
"Artistic2.0",
"Boost Software License 1.0 (BSL-1.0)":
"Boost",
# "CCPL",
"Common Development and Distribution License 1.0 (CDDL-1.0)":
"CDDL",
"Eclipse Public License 1.0 (EPL-1.0)":
"EPL",
# "FDL1.2", # See FDL1.3.
"GNU Free Documentation License (FDL)":
"FDL1.3",
"GNU General Public License (GPL)":
"GPL",
"GNU General Public License v2 (GPLv2)":
"GPL2",
"GNU General Public License v2 or later (GPLv2+)":
"GPL2",
"GNU General Public License v3 (GPLv3)":
"GPL3",
"GNU General Public License v3 or later (GPLv3+)":
"GPL3",
"GNU Library or Lesser General Public License (LGPL)":
"LGPL",
"GNU Lesser General Public License v2 (LGPLv2)":
"LGPL2.1",
"GNU Lesser General Public License v2 or later (LGPLv2+)":
"LGPL2.1",
"GNU Lesser General Public License v3 (LGPLv3)":
"LGPL3",
"GNU Lesser General Public License v3 or later (LGPLv3+)":
"LGPL3",
# "LPPL",
"Mozilla Public License 1.1 (MPL 1.1)":
"MPL",
"Mozilla Public License 2.0 (MPL 2.0)":
"MPL2",
# "PerlArtistic", # See Artistic2.0.
# "PHP",
"Python Software Foundation License":
"PSF",
# "RUBY",
"W3C License":
"W3C",
"Zope Public License":
"ZPL",
}
TROVE_SPECIAL_LICENSES = { # Standard licenses with specific line.
"BSD License":
"BSD",
"MIT License":
"MIT",
"zlib/libpng License":
"ZLIB",
"Python License (CNRI Python License)":
"Python",
}
PKGBUILD_HEADER = """\
# Maintainer: {config[PACKAGER]}
export PIP_CONFIG_FILE=/dev/null
export PIP_DISABLE_PIP_VERSION_CHECK=true
pkgname={pkg.pkgname}
epoch={pkg.epoch}
pkgver={pkg.pkgver}
pkgrel={pkg.pkgrel}
pkgdesc={pkg.pkgdesc}
arch=({pkg.arch})
url={pkg.url}
license=({pkg.license})
depends=(python {pkg.depends:{pkg.__class__.__name__}})
## EXTRA_DEPENDS ##
makedepends=({pkg.makedepends:{pkg.__class__.__name__}})
checkdepends=({pkg.checkdepends:{pkg.__class__.__name__}})
provides=({pkg.provides})
conflicts=(${{provides%=*}}) # No quotes, to avoid an empty entry.
source=(PKGBUILD_EXTRAS)
md5sums=(SKIP)
noextract=()
"""
SDIST_SOURCE = """\
source+=({url[url]})
md5sums+=({url[md5_digest]})
"""
WHEEL_ANY_SOURCE = """\
source+=({url[url]})
md5sums+=({url[md5_digest]})
noextract+=({name})
"""
WHEEL_ARCH_SOURCE = """\
source_{arch}=({url[url]})
md5sums_{arch}=({url[md5_digest]})
noextract+=({name})
"""
MORE_SOURCES = """\
source+=({names})
md5sums+=({md5s})
"""
PKGBUILD_CONTENTS = """\
_first_source() {
echo " ${source_i686[@]} ${source_x86_64[@]} ${source[@]}" |
tr ' ' '\\n' | grep -Pv '^(PKGBUILD_EXTRAS)?$' | head -1
}
_vcs="$(grep -Po '^[a-z]+(?=\\+)' <<< "$(_first_source)")"
if [[ "$_vcs" ]]; then
makedepends+=("$(pkgfile --quiet /usr/bin/$_vcs)")
provides+=("${pkgname%-$_vcs}")
conflicts+=("${pkgname%-$_vcs}")
fi
_is_wheel() {
[[ $(_first_source) =~ \\.whl$ ]]
}
if [[ _is_wheel &&
$(basename "$(_first_source)" | rev | cut -d- -f1 | rev) =~ ^manylinux ]]; then
options=(!strip) # https://github.com/pypa/manylinux/issues/119
fi
_dist_name() {
find "$srcdir" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' |
grep -v '^_tmpenv$'
}
if [[ $(_first_source) =~ ^git+ ]]; then
_pkgver() {
( set -o pipefail
cd "$srcdir/$(_dist_name)"
git describe --long --tags 2>/dev/null |
sed 's/^v//;s/\\([^-]*-g\\)/r\\1/;s/-/./g' ||
printf "r%s.%s" \\
"$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
)
}
pkgver() { _pkgver; }
fi
_build() {
if _is_wheel; then return; fi
cd "$srcdir"
# See Arch Wiki/PKGBUILD/license.
# Get the first filename that matches.
local test_name
if [[ ${license[0]} =~ ^(BSD|MIT|ZLIB|Python)$ ]]; then
for test_name in """ + " ".join(LICENSE_NAMES) + """; do
if cp "$srcdir/$(_dist_name)/$test_name" "$srcdir/LICENSE" 2>/dev/null; then
break
fi
done
fi
# Use the latest version of pip, as Arch's version is historically out of
# date(!) and newer versions do fix bugs (sometimes).
python -mvenv --clear --system-site-packages _tmpenv
_tmpenv/bin/pip --quiet install -U pip
# Build the wheel (which we allow to fail) only after fetching the license.
# In order to isolate from ~/.pydistutils.cfg, we need to set $HOME to a
# temporary directory, and thus first $XDG_CACHE_HOME back to its real
# location, so that pip inserts the wheel in the wheel cache. We cannot
# use --global-option=--no-user-cfg instead because that fully disables
# wheels, causing a from-source build of build dependencies such as
# numpy/scipy.
XDG_CACHE_HOME="${XDG_CACHE_HOME:-"$HOME/.cache"}" HOME=_tmpenv \\
_tmpenv/bin/pip wheel -v --no-deps --wheel-dir="$srcdir" \\
"./$(_dist_name)" || true
}
build() { _build; }
_check() {
# Define check(), possibly using _check as a helper, to run the tests.
# You may need to call `python setup.py build_ext -i` first.
if _is_wheel; then return; fi
cd "$srcdir/$(_dist_name)"
/usr/bin/python setup.py -q test
}
_package() {
cd "$srcdir"
# pypa/pip#3063: pip always checks for a globally installed version.
python -mvenv --clear --system-site-packages _tmpenv
_tmpenv/bin/pip install --prefix="$pkgdir/usr" \\
--no-deps --ignore-installed --no-warn-script-location \\
"$(ls ./*.whl 2>/dev/null || echo ./"$(_dist_name)")"
if [[ -d "$pkgdir/usr/bin" ]]; then # Fix entry points.
python="#!$(readlink -f _tmpenv)/bin/python"
for f in "$pkgdir/usr/bin/"*; do
# Like [[ "$(head -n1 "$f")" = "#!$(readlink -f _tmpenv)/bin/python" ]]
# but without bash warning on null bytes in "$f" (if it is actually
# a compiled executable, not an entry point).
if python -c 'import os, sys; sys.exit(not open(sys.argv[1], "rb").read().startswith(os.fsencode(sys.argv[2]) + b"\\n"))' "$f" "$python"; then
sed -i '1c#!/usr/bin/python' "$f"
fi
done
fi
if [[ -d "$pkgdir/usr/etc" ]]; then
mv "$pkgdir/usr/etc" "$pkgdir/etc"
fi
if [[ -f LICENSE ]]; then
install -D -m644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
fi
}
package() { _package; }
. "$(dirname "$BASH_SOURCE")/PKGBUILD_EXTRAS"
# Remove makedepends already in depends (which may have been listed for the
# first build, but autodetected on the second.
makedepends=($(printf '%s\\n' "${makedepends[@]}" |
grep -Pwv "^($(IFS='|'; echo "${depends[*]}"))$"))
: # Apparently ending with makedepends assignment sometimes fails.
"""
METAPKGBUILD_CONTENTS = """\
package() {
true
}
"""
def _run_shell(args, **kwargs):
"""
Logging wrapper for `subprocess.run`, with useful defaults.
Log at ``DEBUG`` level except if the *verbose* kwarg is set, in which case
log at ``INFO`` level.
"""
kwargs = {"shell": isinstance(args, str),
"env": {**os.environ,
# This should fallback to C if the locale is not present.
# We'd prefer C.utf8 but that doesn't exist. With other
# locales, outputs cannot be parsed.
"LC_ALL": "en_US.UTF-8",
# LANGUAGE is also needed for e.g. pacman which goes
# through gettext.
"LANGUAGE": "en_US.UTF-8",
"PYTHONNOUSERSITE": "1",
"PIP_CONFIG_FILE": "/dev/null",
"PIP_DISABLE_PIP_VERSION_CHECK": "1",
"COLOREDLOGS_AUTO_INSTALL": "", # Hide pip logging.
**kwargs.pop("env", {})},
"check": True,
"text": True,
**kwargs}
if "cwd" in kwargs:
kwargs["cwd"] = str(Path(kwargs["cwd"]))
level = logging.INFO if kwargs.pop("verbose", None) else logging.DEBUG
args_s = (args if isinstance(args, str)
else " ".join(shlex.quote(str(arg)) for arg in args))
if "cwd" in kwargs:
LOGGER.log(level,
"Running subprocess from %s:\n%s", kwargs["cwd"], args_s)
else:
LOGGER.log(level, "Running subprocess:\n%s", args_s)
cproc = subprocess.run(args, **kwargs)
# Stripping final newlines matches the behavior of `a=$(foo)`.
if isinstance(cproc.stdout, str):
cproc.stdout = cproc.stdout.rstrip("\n")
elif isinstance(cproc.stdout, bytes):
cproc.stdout = cproc.stdout.rstrip(b"\n")
return cproc
def _run_shell_stdout(args, **kwargs):
"""Run a shell command and return its stdout."""
return _run_shell(args, **kwargs, stdout=PIPE).stdout
@lru_cache()
def _get_readonly_clean_venv(): # "readonly" is an intent, but not enforced.
venv_dir = TemporaryDirectory()
_run_shell(["python", "-mvenv", venv_dir.name])
return venv_dir # Don't let venv_dir get GC'd.
def _run_python(args, **kwargs):
"""Run python from a temporary venv."""
venv_dir = _get_readonly_clean_venv().name
return _run_shell( # args must be a list; str is not supported.
[f"{venv_dir}/bin/python"] + args, **kwargs)
@lru_cache()
def get_makepkg_conf():
with TemporaryDirectory() as tmpdir:
mini_pkgbuild = textwrap.dedent(r"""
pkgname=_
pkgver=0
pkgrel=0
arch=(any)
prepare() {
printf "CFLAGS %s\0CXXFLAGS %s\0PACKAGER %s" \
"$CFLAGS" "$CXXFLAGS" "$PACKAGER" > log.txt
exit 0
}
""")
Path(tmpdir, "PKGBUILD").write_text(mini_pkgbuild)
try:
_run_shell("makepkg", cwd=tmpdir, stdout=PIPE, stderr=PIPE)
except CalledProcessError as e:
sys.stderr.write(e.stderr)
raise
out = Path(tmpdir, "src/log.txt").read_text()
return dict(pair.split(" ", 1) for pair in out.split("\0"))
class ArchVersion(namedtuple("_ArchVersion", "epoch pkgver pkgrel")):
@classmethod
def parse(cls, s):
epoch, pkgver, pkgrel = (
re.fullmatch(r"(?:(.*):)?(.*)-(.*)", s).groups())
return cls(epoch or "", pkgver, pkgrel)
def __str__(self):
return (f"{self.epoch}:{self.pkgver}-{self.pkgrel}" if self.epoch
else f"{self.pkgver}-{self.pkgrel}")
class WheelInfo(
namedtuple("_WheelInfo", "name version build pythons abi platform")):
@classmethod
def parse(cls, url):
parts = Path(urllib.parse.urlparse(url).path).stem.split("-")
if len(parts) == 5:
name, version, pythons, abi, platform = parts
build = ""
elif len(parts) == 6:
name, version, build, pythons, abi, platform = parts
else:
raise ValueError(f"Invalid wheel url: {url}")
return cls(
name, version, build, set(pythons.split(".")), abi, platform)
def get_arch_platforms(self):
# any -> any
# manylinuxXXX_{i686,x86_64}.manylinuxYYY_{...} -> {i686,x86_64}, {...}
# No other wheel tags (e.g. windows/macos) reach this point because
# they are first filtered away by _filter_and_sort_urls.
platforms = []
regex = (
"(any)"
# https://peps.python.org/pep-0600/#package-indexes
"|manylinux1_(x86_64|i686)"
"|manylinux2010_(x86_64|i686)"
"|manylinux2014_(x86_64|i686|aarch64|armv7l|ppc64|ppc64le|s390x)"
"|manylinux_[0-9]+_[0-9]+_(.*)")
for part in self.platform.split("."):
platform, = filter(None, re.fullmatch(regex, part).groups())
platforms.append(platform)
return platforms
# Copy-pasted from PEP503.
def pep503_normalize_name(name):
return re.sub(r"[-_.]+", "-", name).lower()
def to_wheel_name(pep503_name):
return pep503_name.replace("-", "_")
def gen_ver_cmp_operator(ver):
# Handle cases where only a post-release is available.
return f"=={ver}.*,<{ver}.1"
class PackagingError(Exception):
pass
def _get_vcs(name):
match = re.match(r"\A[a-z]+(?=\+)", name)
return match.group(0) if match else None
# Vendored from pip._internal.vcs.VersionControl.get_url_rev.
def _vcs_get_url_rev(url):
error_message = (
"Sorry, '%s' is a malformed VCS url. "
"The format is <vcs>+<protocol>://<url>, "
"e.g. svn+http://myrepo/svn/MyApp#egg=MyApp"
)
assert '+' in url, error_message % url
url = url.split('+', 1)[1]
scheme, netloc, path, query, frag = urllib.parse.urlsplit(url)
rev = None
if '@' in path:
path, rev = path.rsplit('@', 1)
url = urllib.parse.urlunsplit((scheme, netloc, path, query, ''))
return url, rev
@lru_cache()
def _get_url_impl(url):
cache_dir = TemporaryDirectory()
parsed = urllib.parse.urlparse(url)
if parsed.scheme.startswith("git+"):
_run_shell(["git", "clone", "--recursive", url[4:]],
cwd=cache_dir.name)
elif parsed.scheme == "pip":
try:
_run_python([
"-mpip", "download", "--no-deps", "-d", cache_dir.name,
*(parsed.fragment.split() if parsed.fragment else []),
parsed.netloc])
except CalledProcessError:
# pypa/pip#1884: download can "fail" due to buggy setup.py (e.g.
# astropy 1.3.3).
raise PackagingError(f"Failed to download {parsed.netloc}, "
"possibly due to a buggy setup.py")
else:
Path(cache_dir.name, Path(parsed.path).name).write_bytes(
urllib.request.urlopen(url).read())
packed_path, = (path for path in Path(cache_dir.name).iterdir())
return cache_dir, packed_path # Don't let cache_dir get GC'd.
def _get_url_packed_path(url):
cache_dir, packed_path = _get_url_impl(url)
return packed_path
@lru_cache()
def _get_url_unpacked_path_or_null(url):
parsed = urllib.parse.urlparse(url)
if parsed.scheme == "file" and parsed.path.endswith(".whl"):
return Path("/dev/null")
try:
cache_dir, packed_path = _get_url_impl(url)
except CalledProcessError:
return Path("/dev/null")
if packed_path.is_file(): # pip://
shutil.unpack_archive(str(packed_path), cache_dir.name)
unpacked_path, = (
path for path in Path(cache_dir.name).iterdir() if path.is_dir())
return unpacked_path
@lru_cache()
def _guess_url_makedepends(url, guess_makedepends):
makedepends = []
if ("swig" in guess_makedepends
and list(_get_url_unpacked_path_or_null(url).glob("**/*.i"))):
makedepends.append(NonPyPackageRef("swig"))
if ("cython" in guess_makedepends
and list(_get_url_unpacked_path_or_null(url).glob("**/*.pyx"))):
makedepends.append(PackageRef("Cython"))
return DependsTuple(makedepends)
@lru_cache()
def _get_metadata(name, setup_requires):
# Dependency resolution is done by installing the package in a venv and
# calling `pip show`; otherwise it would be necessary to parse environment
# markers (from "requires_dist"). The package name may get denormalized
# ("_" -> "-") during installation so we just look at whatever got
# installed.
#
# `entry_points` is a generator, thus not json-serializable.
#
# To handle sdists that depend on numpy, we just see whether installing in
# presence of numpy makes things better...
with TemporaryDirectory() as venv_dir, \
NamedTemporaryFile("r") as more_requires_log, \
NamedTemporaryFile("r") as log:
script = textwrap.dedent(r"""
set -e
python -mvenv {venv_dir}
# Leave the source directory, which may contain wheels/sdists/etc.
cd {venv_dir}
. '{venv_dir}/bin/activate'
if [[ -n '{setup_requires}' ]]; then
pip install --upgrade {setup_requires} >/dev/null
fi
install_cmd() {{
pip list --format=freeze | cut -d= -f1 | sort >'{venv_dir}/a'
if ! pip install --no-deps '{req}'; then
return 1
fi
pip list --format=freeze | cut -d= -f1 | sort >'{venv_dir}/b'
# installed name, or real name if it doesn't appear
# (setuptools, pip, Cython, numpy).
install_name="$(comm -13 '{venv_dir}/a' '{venv_dir}/b')"
# the requirement can be 'req_name==version', or a path name.
if [[ -z "$install_name" ]]; then
if [[ -e '{req}' ]]; then
install_name="$(basename '{req}' .git)"
else
install_name="$(echo '{req}' | cut -d= -f1 -)"
fi
fi
}}
show_cmd() {{
python - "$(pip show -v "$install_name")" <<EOF
from email.parser import Parser
import json
import sys
print(json.dumps(dict(Parser().parsestr(sys.argv[1]))))
EOF
}}
if install_cmd >{log.name}; then
show_cmd
else
pip install numpy >/dev/null
echo numpy >>{more_requires_log.name}
install_cmd >{log.name}
show_cmd
fi
""").format(
venv_dir=venv_dir,
setup_requires=" ".join(setup_requires),
req=(_get_url_unpacked_path_or_null(name)
if _get_vcs(name) else name),
more_requires_log=more_requires_log,
log=log)
try:
out = _run_shell_stdout(
script, env={
# Matters, as a built wheel would get cached.
"CFLAGS": get_makepkg_conf()["CFLAGS"],
# Not actually used, per pypa/setuptools#1192. Still
# relevant for packages that ship their own autoconf-based
# builds, e.g. wxPython.
"CXXFLAGS": get_makepkg_conf()["CXXFLAGS"],
})
except CalledProcessError:
sys.stderr.write(log.read())
raise PackagingError(f"Failed to obtain metadata for {name}.")
more_requires = more_requires_log.read().splitlines()
metadata = {k.lower(): v for k, v in json.loads(out).items()}
metadata["requires"] = [
*(metadata["requires"].split(", ") if metadata["requires"] else []),
*more_requires]
metadata["classifiers"] = metadata["classifiers"].split("\n ")[1:]
return {key.replace("-", "_"): value for key, value in metadata.items()}
@lru_cache()
def _get_info(name, *,
pre=False,
guess_makedepends=(),
_sources=("git", "local", "pypi"),
_version=""):
parsed = urllib.parse.urlparse(name)
def _get_info_git():
if not parsed.scheme.startswith("git+"):
return
url, rev = _vcs_get_url_rev(name)
if rev:
# FIXME pip guesses whether a name is a branch, a commit or a tag,
# whereas the fragment type must be specified in the PKGBUILD.
# FIXME fragment support.
raise PackagingError(
"No support for packaging specific revisions.")
metadata = _get_metadata(
name, _guess_url_makedepends(name, guess_makedepends).pep503_names)
try: # Normalize the name if available on PyPI.
metadata["name"] = _get_info(
metadata["name"], _sources=("pypi",))["info"]["name"]
except PackagingError:
pass
return {"info": {"download_url": url,
"home_page": url,
"package_url": url,
**metadata},
"urls": [{"packagetype": "sdist",
"path": parsed.path,
"url": name,
"md5_digest": "SKIP"}]}
def _get_info_local():
if not parsed.scheme == "file":
return
metadata = _get_metadata(
name, _guess_url_makedepends(name, guess_makedepends).pep503_names)
return {"info": {"download_url": name,
"home_page": name,
"package_url": name,
**metadata},
"urls": [{"packagetype":
"bdist_wheel" if parsed.path.endswith(".whl")
else "sdist",
"path": parsed.path,
"url": name,
"md5_digest": "SKIP"}]}
def _get_info_pypi():
try:
r = urllib.request.urlopen(
f"https://pypi.org/pypi/{name}/{_version}/json"
if _version else f"https://pypi.org/pypi/{name}/json")
except urllib.error.HTTPError:
return
request = json.loads(r.read())
if not _version:
if not request["releases"]:
raise PackagingError(f"No suitable release found for {name}.")
src = ("from sys import argv; "
"from pkg_resources import parse_version as pv; ")
src += (
"print(sorted(argv[1:], key=pv))" if pre else
"print(sorted([v for v in argv[1:] if not pv(v).is_prerelease],"
"key=pv))")
versions = ast.literal_eval(
_run_python(["-c", src, *request["releases"]], stdout=PIPE)
.stdout)
if not versions: # request only returned pre-releases.
raise PackagingError(
f"No suitable release found for {name}. Pre-releases are "
f"available, use --pre to use the latest one.")
max_version = versions[-1]
if max_version != request["info"]["version"]:
return _get_info(name, pre=pre, _version=max_version)
return request
for source in _sources:
info = locals()[f"_get_info_{source}"]()
if info:
return info
else:
raise PackagingError("Package {} not found.".format(
" ".join(filter(None, [name, _version]))))
# For _find_{installed,arch}_name_version:
# - first check for a matching `.{dist,egg}-info` file, ignoring case to
# handle e.g. `cycler` (pip) / `Cycler` (PyPI); also, there is usually a
# version number (separated by a dash) but not always, e.g. for PySide6 (in
# which case a dot comes next).
# - then check exact lowercase matches, to handle packages without a
# `.{dist,egg}-info`.
def _find_installed_name_version(pep503_name, *, ignore_vendored=False):
parts = (
_run_shell_stdout(
"find . -maxdepth 1 -iname '%s[.-]*-info' "
"-exec pacman -Qo '{}' \\; | rev | cut -d' ' -f1,2 | rev"
% (to_wheel_name(pep503_name)
# https://github.com/pypa/wheel/issues/440
.replace("-", "[-.]").replace("_", "[_.]")),
cwd=site.getsitepackages()[0]).split()
or _run_shell_stdout(
f"pacman -Q python-{pep503_name} 2>/dev/null",
check=False).split())
if parts:
pkgname, version = parts # This will raise if there is an ambiguity.
if pkgname.endswith("-git"):
expected_conflict = pkgname[:-len("-git")]
if _run_shell(
f"pacman -Qi {pkgname} 2>/dev/null | "
rf"grep -q 'Conflicts With *:.*\b{expected_conflict}\b'",
check=False).returncode == 0:
pkgname = pkgname[:-len("-git")]
else:
raise PackagingError(
f"Found installed package {pkgname} which does NOT "
f"conflict with {expected_conflict}; please uninstall it "
f"first.")
if ignore_vendored and pkgname.startswith("python--"):
return
else:
return pkgname, ArchVersion.parse(version)
else:
return
def _find_arch_name_version(pep503_name):
for standalone in [True, False]: # vendored into another Python package?
*candidates, = map(str.strip, _run_shell_stdout(
"pkgfile -riv "
"'^/usr/lib/python{version.major}\\.{version.minor}/{parent}"
"{wheel_name}-.*py{version.major}\\.{version.minor}\\.egg-info' | "
"cut -f1 | uniq | cut -d/ -f2".format(
parent="site-packages/" if standalone else "",
wheel_name=to_wheel_name(pep503_name),
version=sys.version_info)
).splitlines())
if len(candidates) > 1:
message = "Multiple candidates for {}: {}.".format(
pep503_name, ", ".join(candidates))
try:
canonical, = (
candidate for candidate in candidates
if candidate.startswith(f"python-{pep503_name} "))
except ValueError:
raise PackagingError(message)
else:
LOGGER.warning("%s Using canonical name: %s.",
message, canonical.split()[0])
candidates = [canonical]
if len(candidates) == 1:
pkgname, version = candidates[0].split()
arch_version = ArchVersion.parse(version)
return pkgname, arch_version
class NonPyPackageRef:
def __init__(self, pkgname):
self.pkgname = self.depname = pkgname
class PackageRef:
def __init__(self, name, *,
pre=False, guess_makedepends=(), subpkg_of=None):
# If `subpkg_of` is set, do not attempt to use the Arch Linux name,
# and name the package python--$pkgname to prevent collision.
self.orig_name = name # A name or an URL.
self.info = _get_info(
name, pre=pre, guess_makedepends=guess_makedepends)
self.pypi_name = self.info["info"]["name"]
# pacman -Slq | grep '^python-' | cut -d- -f 2- |
# grep -v '^\([[:alnum:]]\)*$' | grep '_'
# (or '\.', or '-') shows that PEP503 normalization is by far the most
# common, so we use it everywhere... except when downloading, which
# requires the actual PyPI-registered name.
self.pep503_name = pep503_normalize_name(self.pypi_name)
if subpkg_of:
pkgname = f"python--{self.pep503_name}"
depname = subpkg_of.pkgname
arch_version = None
else:
# For the name as package: First, check installed packages,
# which may have inherited non-standard names from the AUR (e.g.,
# `python-numpy-openblas`, `pipdeptree`). Specifically ignore
# vendored packages (`python--*`). Then, check official packages.
# Then, fallback on the default.
# For the name as dependency, try the official name first, so that
# one can replace the local package (which provides the official
# one anyways) by the official one if desired without breaking
# dependencies.
installed = _find_installed_name_version(
self.pep503_name, ignore_vendored=True)
arch = _find_arch_name_version(self.pep503_name)
default = f"python-{self.pep503_name}", None
pkgname, arch_version = installed or arch or default
depname, _ = arch or installed or default
arch_packaged = sorted({*_run_shell_stdout(
f"pkgfile -l {pkgname} 2>/dev/null | "
# Package name has no dash (per packaging standard) nor slashes
# (which can occur when a subpackage is vendored (depending on how
# it is done), e.g. `.../foo.egg-info` and `.../foo/bar.egg-info`
# both existing).
r"grep -Po '(?<=site-packages/)[^-/]*(?=.*\.egg-info/?$)'",
check=False).splitlines()})
# Final values.
vcs = _get_vcs(name)
self.pkgname = f"{pkgname}-{vcs}" if vcs else pkgname
# Packages that depend on a vendored package should list the
# metapackage (which may be otherwise unrelated) as a dependency, so
# that the metapackage can get updated into an official package without
# breaking dependencies.
# However, the owning metapackage should list their vendorees
# explicitly, so that they do not end up unrequired (other metapackages
# don't matter as they only depend on their own components).
# This logic is implemented in `DependsTuple.__fmt__`.
self.depname = depname
self.arch_version = arch_version
self.arch_packaged = arch_packaged
self.exists = arch_version is not None
class DependsTuple(tuple): # Keep it hashable.
@property
def pep503_names(self):
# Needs to be hashable.
return tuple(ref.pep503_name for ref in self
if isinstance(ref, PackageRef))
def __format__(self, fmt):
# See above re: dependency type.
def _unique(seq): return [*dict.fromkeys(seq)] # Unique, in order.
if fmt == "Package":
return " ".join(_unique(ref.depname for ref in self))
elif fmt == "MetaPackage":
return " ".join(_unique(ref.pkgname for ref in self))
else:
return super().__format__(fmt) # Raise TypeError.
BuildCacheEntry = namedtuple(
"BuildCacheEntry", "pkgname path is_dep namcap_report")
class _BasePackage(ABC):
build_cache = []
def __init__(self):
self._files = {}
# self._pkgbuild = ...
@abc.abstractmethod
def write_deps(self, options):
pass
def get_pkgbuild_extras(self, options):
if os.path.isdir(options.pkgbuild_extras):
extras_path = Path(options.pkgbuild_extras,
f"{self.pkgname}.PKGBUILD_EXTRAS")
if extras_path.exists():
LOGGER.info("Using %s.", extras_path)
return extras_path.read_text()
else:
return ""
else:
return options.pkgbuild_extras
def write(self, options):
cwd = options.base_path / self.pkgname
cwd.mkdir(parents=True, exist_ok=options.force)
(cwd / "PKGBUILD").write_text(self._pkgbuild)
(cwd / "PKGBUILD_EXTRAS").write_text(self.get_pkgbuild_extras(options))
for fname, content in self._files.items():
(cwd / fname).write_bytes(content)
if isinstance(self, Package):
srctree = _get_url_packed_path(self._get_pip_url())
dest = cwd / srctree.name
with suppress(FileNotFoundError):
if dest.is_dir():
shutil.rmtree(dest)
else:
dest.unlink()
shutil.move(srctree, dest)
cmd = ["makepkg",
*(["--force"] if options.force else []),
*shlex.split(options.makepkg)]
_run_shell(cmd, cwd=cwd)
def _get_fullpath():
# This may be absolute and not in cwd (if PKGDEST is set).
return Path(_run_shell_stdout("makepkg --packagelist", cwd=cwd))
fullpath = _get_fullpath()
# Update PKGBUILD.
needs_rebuild = False
# fullpath may not exist if --makepkg=--nobuild.
namcap = (_run_shell_stdout(["namcap", fullpath], cwd=cwd).splitlines()
if fullpath.exists() else [])
# `pkgver()` may update the PKGBUILD, so reread it.
pkgbuild_contents = (cwd / "PKGBUILD").read_text()
# Binary dependencies.
extra_deps_re = (f"(?<=^{self.pkgname} "
"E: Dependency ).*(?= detected and not included)")
extra_deps = [
match.group(0)
for match in map(re.compile(extra_deps_re).search, namcap)
if match]
pkgbuild_contents = pkgbuild_contents.replace(
"## EXTRA_DEPENDS ##",
"depends+=({})".format(" ".join(extra_deps)))
if extra_deps:
needs_rebuild = True
# Unexpected arch-dependent package (e.g. direct compilation of C
# source).
any_arch_re = (f"^{self.pkgname} "
"E: ELF file .* found in an 'any' package.")
if any(re.search(any_arch_re, line) for line in namcap):
pkgbuild_contents = re.sub(
"(?m)^arch=.*$", f"arch=({THIS_ARCH})", pkgbuild_contents, 1)
needs_rebuild = True
if needs_rebuild:
# Remove previous package, repackage, and get new name (arch may
# have changed).
fullpath.unlink()
(cwd / "PKGBUILD").write_text(pkgbuild_contents)
_run_shell("makepkg --force --repackage --nodeps", cwd=cwd)
fullpath = _get_fullpath()
namcap_pkgbuild_report = _run_shell_stdout(
"namcap PKGBUILD", cwd=cwd, check=False)
# Suppressed namcap warnings (may be better to do this via a namcap
# option?):
# - Python dependencies always get misanalyzed; filter them away.
# - Dependencies match install_requires + whatever namcap wants us to
# add, so suppress warning about redundant transitive dependencies.
# - Extension modules unconditionally link to `libpthread` (see
# output of `python-config --libs`); filter that away.
# - Extension modules appear to never be PIE?
namcap_package_report = (
_run_shell_stdout(
f"namcap {shlex.quote(str(fullpath))} | "
f"grep -v \"^{self.pkgname} W: "
r"\(Dependency included and not needed"
r"\|Dependency .* included but already satisfied$"
r"\|Unused shared library '/usr/lib/libpthread\.so\.0' by"
r"\|ELF file .* lacks PIE\.$\)"
"\"", cwd=cwd, check=False)
if fullpath.exists() else "")
namcap_report = [
line for report in [namcap_pkgbuild_report, namcap_package_report]
for line in report.split("\n") if line]
if re.search(f"^{self.pkgname} E: ", namcap_package_report):
raise PackagingError("namcap found a problem with the package.")
_run_shell("makepkg --printsrcinfo >.SRCINFO", cwd=cwd)
type(self).build_cache.append(BuildCacheEntry(
self.pkgname, fullpath, options.is_dep, namcap_report))
# FIXME Suppress message about redundancy of 'python' dependency.
class Package(_BasePackage):
def __init__(self, ref, options):
super().__init__()
self._ref = ref
self._pkgrel = options.pkgrel
stream = StringIO()
LOGGER.info("Packaging %s %s.",
self.pkgname, ref.info["info"]["version"])
self._urls = self._filter_and_sort_urls(
ref.info["urls"], options.pkgtypes)
if not self._urls:
raise PackagingError(
f"No URL available for package {self.pkgname}.")
self._find_makedepends(options)
for dep in self._makedepends:
if _run_shell(f"pacman -Q {dep.pkgname} >/dev/null 2>&1",
check=False).returncode:
# Only log this as needed, to not spam messages about pip.
_run_shell(f"sudo pacman -S --asdeps {dep.pkgname}",
verbose=True)
self._extract_setup_requires()