pipcl.py 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399
  1. '''
  2. Python packaging operations, including PEP-517 support, for use by a `setup.py`
  3. script.
  4. The intention is to take care of as many packaging details as possible so that
  5. setup.py contains only project-specific information, while also giving as much
  6. flexibility as possible.
  7. For example we provide a function `build_extension()` that can be used to build
  8. a SWIG extension, but we also give access to the located compiler/linker so
  9. that a `setup.py` script can take over the details itself.
  10. Run doctests with: `python -m doctest pipcl.py`
  11. '''
  12. import base64
  13. import glob
  14. import hashlib
  15. import inspect
  16. import io
  17. import os
  18. import platform
  19. import re
  20. import shutil
  21. import site
  22. import subprocess
  23. import sys
  24. import sysconfig
  25. import tarfile
  26. import textwrap
  27. import time
  28. import zipfile
  29. import wdev
  30. class Package:
  31. '''
  32. Our constructor takes a definition of a Python package similar to that
  33. passed to `distutils.core.setup()` or `setuptools.setup()` (name, version,
  34. summary etc) plus callbacks for building, getting a list of sdist
  35. filenames, and cleaning.
  36. We provide methods that can be used to implement a Python package's
  37. `setup.py` supporting PEP-517.
  38. We also support basic command line handling for use
  39. with a legacy (pre-PEP-517) pip, as implemented
  40. by legacy distutils/setuptools and described in:
  41. https://pip.pypa.io/en/stable/reference/build-system/setup-py/
  42. Here is a `doctest` example of using pipcl to create a SWIG extension
  43. module. Requires `swig`.
  44. Create an empty test directory:
  45. >>> import os
  46. >>> import shutil
  47. >>> shutil.rmtree('pipcl_test', ignore_errors=1)
  48. >>> os.mkdir('pipcl_test')
  49. Create a `setup.py` which uses `pipcl` to define an extension module.
  50. >>> import textwrap
  51. >>> with open('pipcl_test/setup.py', 'w') as f:
  52. ... _ = f.write(textwrap.dedent("""
  53. ... import sys
  54. ... import pipcl
  55. ...
  56. ... def build():
  57. ... so_leaf = pipcl.build_extension(
  58. ... name = 'foo',
  59. ... path_i = 'foo.i',
  60. ... outdir = 'build',
  61. ... )
  62. ... return [
  63. ... ('build/foo.py', 'foo/__init__.py'),
  64. ... ('cli.py', 'foo/__main__.py'),
  65. ... (f'build/{so_leaf}', f'foo/'),
  66. ... ('README', '$dist-info/'),
  67. ... (b'Hello world', 'foo/hw.txt'),
  68. ... ]
  69. ...
  70. ... def sdist():
  71. ... return [
  72. ... 'foo.i',
  73. ... 'bar.i',
  74. ... 'setup.py',
  75. ... 'pipcl.py',
  76. ... 'wdev.py',
  77. ... 'README',
  78. ... (b'Hello word2', 'hw2.txt'),
  79. ... ]
  80. ...
  81. ... p = pipcl.Package(
  82. ... name = 'foo',
  83. ... version = '1.2.3',
  84. ... fn_build = build,
  85. ... fn_sdist = sdist,
  86. ... entry_points = (
  87. ... { 'console_scripts': [
  88. ... 'foo_cli = foo.__main__:main',
  89. ... ],
  90. ... }),
  91. ... )
  92. ...
  93. ... build_wheel = p.build_wheel
  94. ... build_sdist = p.build_sdist
  95. ...
  96. ... # Handle old-style setup.py command-line usage:
  97. ... if __name__ == '__main__':
  98. ... p.handle_argv(sys.argv)
  99. ... """))
  100. Create the files required by the above `setup.py` - the SWIG `.i` input
  101. file, the README file, and copies of `pipcl.py` and `wdev.py`.
  102. >>> with open('pipcl_test/foo.i', 'w') as f:
  103. ... _ = f.write(textwrap.dedent("""
  104. ... %include bar.i
  105. ... %{
  106. ... #include <stdio.h>
  107. ... #include <string.h>
  108. ... int bar(const char* text)
  109. ... {
  110. ... printf("bar(): text: %s\\\\n", text);
  111. ... int len = (int) strlen(text);
  112. ... printf("bar(): len=%i\\\\n", len);
  113. ... fflush(stdout);
  114. ... return len;
  115. ... }
  116. ... %}
  117. ... int bar(const char* text);
  118. ... """))
  119. >>> with open('pipcl_test/bar.i', 'w') as f:
  120. ... _ = f.write( '\\n')
  121. >>> with open('pipcl_test/README', 'w') as f:
  122. ... _ = f.write(textwrap.dedent("""
  123. ... This is Foo.
  124. ... """))
  125. >>> with open('pipcl_test/cli.py', 'w') as f:
  126. ... _ = f.write(textwrap.dedent("""
  127. ... def main():
  128. ... print('pipcl_test:main().')
  129. ... if __name__ == '__main__':
  130. ... main()
  131. ... """))
  132. >>> root = os.path.dirname(__file__)
  133. >>> _ = shutil.copy2(f'{root}/pipcl.py', 'pipcl_test/pipcl.py')
  134. >>> _ = shutil.copy2(f'{root}/wdev.py', 'pipcl_test/wdev.py')
  135. Use `setup.py`'s command-line interface to build and install the extension
  136. module into root `pipcl_test/install`.
  137. >>> _ = subprocess.run(
  138. ... f'cd pipcl_test && {sys.executable} setup.py --root install install',
  139. ... shell=1, check=1)
  140. The actual install directory depends on `sysconfig.get_path('platlib')`:
  141. >>> if windows():
  142. ... install_dir = 'pipcl_test/install'
  143. ... else:
  144. ... install_dir = f'pipcl_test/install/{sysconfig.get_path("platlib").lstrip(os.sep)}'
  145. >>> assert os.path.isfile( f'{install_dir}/foo/__init__.py')
  146. Create a test script which asserts that Python function call `foo.bar(s)`
  147. returns the length of `s`, and run it with `PYTHONPATH` set to the install
  148. directory:
  149. >>> with open('pipcl_test/test.py', 'w') as f:
  150. ... _ = f.write(textwrap.dedent("""
  151. ... import sys
  152. ... import foo
  153. ... text = 'hello'
  154. ... print(f'test.py: calling foo.bar() with text={text!r}')
  155. ... sys.stdout.flush()
  156. ... l = foo.bar(text)
  157. ... print(f'test.py: foo.bar() returned: {l}')
  158. ... assert l == len(text)
  159. ... """))
  160. >>> r = subprocess.run(
  161. ... f'{sys.executable} pipcl_test/test.py',
  162. ... shell=1, check=1, text=1,
  163. ... stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
  164. ... env=os.environ | dict(PYTHONPATH=install_dir),
  165. ... )
  166. >>> print(r.stdout)
  167. test.py: calling foo.bar() with text='hello'
  168. bar(): text: hello
  169. bar(): len=5
  170. test.py: foo.bar() returned: 5
  171. <BLANKLINE>
  172. Check that building sdist and wheel succeeds. For now we don't attempt to
  173. check that the sdist and wheel actually work.
  174. >>> _ = subprocess.run(
  175. ... f'cd pipcl_test && {sys.executable} setup.py sdist',
  176. ... shell=1, check=1)
  177. >>> _ = subprocess.run(
  178. ... f'cd pipcl_test && {sys.executable} setup.py bdist_wheel',
  179. ... shell=1, check=1)
  180. Check that rebuild does nothing.
  181. >>> t0 = os.path.getmtime('pipcl_test/build/foo.py')
  182. >>> _ = subprocess.run(
  183. ... f'cd pipcl_test && {sys.executable} setup.py bdist_wheel',
  184. ... shell=1, check=1)
  185. >>> t = os.path.getmtime('pipcl_test/build/foo.py')
  186. >>> assert t == t0
  187. Check that touching bar.i forces rebuild.
  188. >>> os.utime('pipcl_test/bar.i')
  189. >>> _ = subprocess.run(
  190. ... f'cd pipcl_test && {sys.executable} setup.py bdist_wheel',
  191. ... shell=1, check=1)
  192. >>> t = os.path.getmtime('pipcl_test/build/foo.py')
  193. >>> assert t > t0
  194. Check that touching foo.i.cpp does not run swig, but does recompile/link.
  195. >>> t0 = time.time()
  196. >>> os.utime('pipcl_test/build/foo.i.cpp')
  197. >>> _ = subprocess.run(
  198. ... f'cd pipcl_test && {sys.executable} setup.py bdist_wheel',
  199. ... shell=1, check=1)
  200. >>> assert os.path.getmtime('pipcl_test/build/foo.py') <= t0
  201. >>> so = glob.glob('pipcl_test/build/*.so')
  202. >>> assert len(so) == 1
  203. >>> so = so[0]
  204. >>> assert os.path.getmtime(so) > t0
  205. Check `entry_points` causes creation of command `foo_cli` when we install
  206. from our wheel using pip. [As of 2024-02-24 using pipcl's CLI interface
  207. directly with `setup.py install` does not support entry points.]
  208. >>> print('Creating venv.', file=sys.stderr)
  209. >>> _ = subprocess.run(
  210. ... f'cd pipcl_test && {sys.executable} -m venv pylocal',
  211. ... shell=1, check=1)
  212. >>> print('Installing from wheel into venv using pip.', file=sys.stderr)
  213. >>> _ = subprocess.run(
  214. ... f'. pipcl_test/pylocal/bin/activate && pip install pipcl_test/dist/*.whl',
  215. ... shell=1, check=1)
  216. >>> print('Running foo_cli.', file=sys.stderr)
  217. >>> _ = subprocess.run(
  218. ... f'. pipcl_test/pylocal/bin/activate && foo_cli',
  219. ... shell=1, check=1)
  220. Wheels and sdists
  221. Wheels:
  222. We generate wheels according to:
  223. https://packaging.python.org/specifications/binary-distribution-format/
  224. * `{name}-{version}.dist-info/RECORD` uses sha256 hashes.
  225. * We do not generate other `RECORD*` files such as
  226. `RECORD.jws` or `RECORD.p7s`.
  227. * `{name}-{version}.dist-info/WHEEL` has:
  228. * `Wheel-Version: 1.0`
  229. * `Root-Is-Purelib: false`
  230. * No support for signed wheels.
  231. Sdists:
  232. We generate sdist's according to:
  233. https://packaging.python.org/specifications/source-distribution-format/
  234. '''
  235. def __init__(self,
  236. name,
  237. version,
  238. *,
  239. platform = None,
  240. supported_platform = None,
  241. summary = None,
  242. description = None,
  243. description_content_type = None,
  244. keywords = None,
  245. home_page = None,
  246. download_url = None,
  247. author = None,
  248. author_email = None,
  249. maintainer = None,
  250. maintainer_email = None,
  251. license = None,
  252. classifier = None,
  253. requires_dist = None,
  254. requires_python = None,
  255. requires_external = None,
  256. project_url = None,
  257. provides_extra = None,
  258. entry_points = None,
  259. root = None,
  260. fn_build = None,
  261. fn_clean = None,
  262. fn_sdist = None,
  263. tag_python = None,
  264. tag_abi = None,
  265. tag_platform = None,
  266. wheel_compression = zipfile.ZIP_DEFLATED,
  267. wheel_compresslevel = None,
  268. ):
  269. '''
  270. The initial args before `root` define the package
  271. metadata and closely follow the definitions in:
  272. https://packaging.python.org/specifications/core-metadata/
  273. Args:
  274. name:
  275. A string, the name of the Python package.
  276. version:
  277. A string, the version of the Python package. Also see PEP-440
  278. `Version Identification and Dependency Specification`.
  279. platform:
  280. A string or list of strings.
  281. supported_platform:
  282. A string or list of strings.
  283. summary:
  284. A string, short description of the package.
  285. description:
  286. A string, a detailed description of the package.
  287. description_content_type:
  288. A string describing markup of `description` arg. For example
  289. `text/markdown; variant=GFM`.
  290. keywords:
  291. A string containing comma-separated keywords.
  292. home_page:
  293. URL of home page.
  294. download_url:
  295. Where this version can be downloaded from.
  296. author:
  297. Author.
  298. author_email:
  299. Author email.
  300. maintainer:
  301. Maintainer.
  302. maintainer_email:
  303. Maintainer email.
  304. license:
  305. A string containing the license text. Written into metadata
  306. file `COPYING`. Is also written into metadata itself if not
  307. multi-line.
  308. classifier:
  309. A string or list of strings. Also see:
  310. * https://pypi.org/pypi?%3Aaction=list_classifiers
  311. * https://pypi.org/classifiers/
  312. requires_dist:
  313. A string or list of strings. Also see PEP-508.
  314. requires_python:
  315. A string or list of strings.
  316. requires_external:
  317. A string or list of strings.
  318. project_url:
  319. A string or list of strings, each of the form: `{name}, {url}`.
  320. provides_extra:
  321. A string or list of strings.
  322. entry_points:
  323. String or dict specifying *.dist-info/entry_points.txt, for
  324. example:
  325. ```
  326. [console_scripts]
  327. foo_cli = foo.__main__:main
  328. ```
  329. or:
  330. { 'console_scripts': [
  331. 'foo_cli = foo.__main__:main',
  332. ],
  333. }
  334. See: https://packaging.python.org/en/latest/specifications/entry-points/
  335. root:
  336. Root of package, defaults to current directory.
  337. fn_build:
  338. A function taking no args, or a single `config_settings` dict
  339. arg (as described in PEP-517), that builds the package.
  340. Should return a list of items; each item should be a tuple
  341. `(from_, to_)`, or a single string `path` which is treated as
  342. the tuple `(path, path)`.
  343. `from_` can be a string or a `bytes`. If a string it should
  344. be the path to a file; a relative path is treated as relative
  345. to `root`. If a `bytes` it is the contents of the file to be
  346. added.
  347. `to_` identifies what the file should be called within a wheel
  348. or when installing. If `to_` ends with `/`, the leaf of `from_`
  349. is appended to it (and `from_` must not be a `bytes`).
  350. Initial `$dist-info/` in `_to` is replaced by
  351. `{name}-{version}.dist-info/`; this is useful for license files
  352. etc.
  353. Initial `$data/` in `_to` is replaced by
  354. `{name}-{version}.data/`. We do not enforce particular
  355. subdirectories, instead it is up to `fn_build()` to specify
  356. specific subdirectories such as `purelib`, `headers`,
  357. `scripts`, `data` etc.
  358. If we are building a wheel (e.g. `python setup.py bdist_wheel`,
  359. or PEP-517 pip calls `self.build_wheel()`), we add file `from_`
  360. to the wheel archive with name `to_`.
  361. If we are installing (e.g. `install` command in
  362. the argv passed to `self.handle_argv()`), then
  363. we copy `from_` to `{sitepackages}/{to_}`, where
  364. `sitepackages` is the installation directory, the
  365. default being `sysconfig.get_path('platlib')` e.g.
  366. `myvenv/lib/python3.9/site-packages/`.
  367. fn_clean:
  368. A function taking a single arg `all_` that cleans generated
  369. files. `all_` is true iff `--all` is in argv.
  370. For safety and convenience, can also returns a list of
  371. files/directory paths to be deleted. Relative paths are
  372. interpreted as relative to `root`. All paths are asserted to be
  373. within `root`.
  374. fn_sdist:
  375. A function taking no args, or a single `config_settings` dict
  376. arg (as described in PEP517), that returns a list of items to
  377. be copied into the sdist. The list should be in the same format
  378. as returned by `fn_build`.
  379. It can be convenient to use `pipcl.git_items()`.
  380. The specification for sdists requires that the list contains
  381. `pyproject.toml`; we enforce this with a diagnostic rather than
  382. raising an exception, to allow legacy command-line usage.
  383. tag_python:
  384. First element of wheel tag defined in PEP-425. If None we use
  385. `cp{version}`.
  386. For example if code works with any Python version, one can use
  387. 'py3'.
  388. tag_abi:
  389. Second element of wheel tag defined in PEP-425. If None we use
  390. `none`.
  391. tag_platform:
  392. Third element of wheel tag defined in PEP-425. Default is
  393. `os.environ('AUDITWHEEL_PLAT')` if set, otherwise derived
  394. from `setuptools.distutils.util.get_platform()` (was
  395. `distutils.util.get_platform()` as specified in the PEP), e.g.
  396. `openbsd_7_0_amd64`.
  397. For pure python packages use: `tag_platform=any`
  398. wheel_compression:
  399. Used as `zipfile.ZipFile()`'s `compression` parameter when
  400. creating wheels.
  401. wheel_compresslevel:
  402. Used as `zipfile.ZipFile()`'s `compresslevel` parameter when
  403. creating wheels.
  404. '''
  405. assert name
  406. assert version
  407. def assert_str( v):
  408. if v is not None:
  409. assert isinstance( v, str), f'Not a string: {v!r}'
  410. def assert_str_or_multi( v):
  411. if v is not None:
  412. assert isinstance( v, (str, tuple, list)), f'Not a string, tuple or list: {v!r}'
  413. assert_str( name)
  414. assert_str( version)
  415. assert_str_or_multi( platform)
  416. assert_str_or_multi( supported_platform)
  417. assert_str( summary)
  418. assert_str( description)
  419. assert_str( description_content_type)
  420. assert_str( keywords)
  421. assert_str( home_page)
  422. assert_str( download_url)
  423. assert_str( author)
  424. assert_str( author_email)
  425. assert_str( maintainer)
  426. assert_str( maintainer_email)
  427. assert_str( license)
  428. assert_str_or_multi( classifier)
  429. assert_str_or_multi( requires_dist)
  430. assert_str( requires_python)
  431. assert_str_or_multi( requires_external)
  432. assert_str_or_multi( project_url)
  433. assert_str_or_multi( provides_extra)
  434. # https://packaging.python.org/en/latest/specifications/core-metadata/.
  435. assert re.match('([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$', name, re.IGNORECASE), \
  436. f'Bad name: {name!r}'
  437. _assert_version_pep_440(version)
  438. # https://packaging.python.org/en/latest/specifications/binary-distribution-format/
  439. if tag_python:
  440. assert '-' not in tag_python
  441. if tag_abi:
  442. assert '-' not in tag_abi
  443. if tag_platform:
  444. assert '-' not in tag_platform
  445. self.name = name
  446. self.version = version
  447. self.platform = platform
  448. self.supported_platform = supported_platform
  449. self.summary = summary
  450. self.description = description
  451. self.description_content_type = description_content_type
  452. self.keywords = keywords
  453. self.home_page = home_page
  454. self.download_url = download_url
  455. self.author = author
  456. self.author_email = author_email
  457. self.maintainer = maintainer
  458. self.maintainer_email = maintainer_email
  459. self.license = license
  460. self.classifier = classifier
  461. self.requires_dist = requires_dist
  462. self.requires_python = requires_python
  463. self.requires_external = requires_external
  464. self.project_url = project_url
  465. self.provides_extra = provides_extra
  466. self.entry_points = entry_points
  467. self.root = os.path.abspath(root if root else os.getcwd())
  468. self.fn_build = fn_build
  469. self.fn_clean = fn_clean
  470. self.fn_sdist = fn_sdist
  471. self.tag_python = tag_python
  472. self.tag_abi = tag_abi
  473. self.tag_platform = tag_platform
  474. self.wheel_compression = wheel_compression
  475. self.wheel_compresslevel = wheel_compresslevel
  476. def build_wheel(self,
  477. wheel_directory,
  478. config_settings=None,
  479. metadata_directory=None,
  480. ):
  481. '''
  482. A PEP-517 `build_wheel()` function.
  483. Also called by `handle_argv()` to handle the `bdist_wheel` command.
  484. Returns leafname of generated wheel within `wheel_directory`.
  485. '''
  486. log2(
  487. f' wheel_directory={wheel_directory!r}'
  488. f' config_settings={config_settings!r}'
  489. f' metadata_directory={metadata_directory!r}'
  490. )
  491. # Get two-digit python version, e.g. 'cp3.8' for python-3.8.6.
  492. #
  493. if self.tag_python:
  494. tag_python = self.tag_python
  495. else:
  496. tag_python = 'cp' + ''.join(platform.python_version().split('.')[:2])
  497. # ABI tag.
  498. if self.tag_abi:
  499. tag_abi = self.tag_abi
  500. else:
  501. tag_abi = 'none'
  502. # Find platform tag used in wheel filename.
  503. #
  504. tag_platform = None
  505. if not tag_platform:
  506. tag_platform = self.tag_platform
  507. if not tag_platform:
  508. # Prefer this to PEP-425. Appears to be undocumented,
  509. # but set in manylinux docker images and appears
  510. # to be used by cibuildwheel and auditwheel, e.g.
  511. # https://github.com/rapidsai/shared-action-workflows/issues/80
  512. tag_platform = os.environ.get( 'AUDITWHEEL_PLAT')
  513. if not tag_platform:
  514. # PEP-425. On Linux gives `linux_x86_64` which is rejected by
  515. # pypi.org.
  516. #
  517. import setuptools
  518. tag_platform = setuptools.distutils.util.get_platform().replace('-', '_').replace('.', '_')
  519. # We need to patch things on MacOS.
  520. #
  521. # E.g. `foo-1.2.3-cp311-none-macosx_13_x86_64.whl`
  522. # causes `pip` to fail with: `not a supported wheel on this
  523. # platform`. We seem to need to add `_0` to the OS version.
  524. #
  525. m = re.match( '^(macosx_[0-9]+)(_[^0-9].+)$', tag_platform)
  526. if m:
  527. tag_platform2 = f'{m.group(1)}_0{m.group(2)}'
  528. log2( f'Changing from {tag_platform!r} to {tag_platform2!r}')
  529. tag_platform = tag_platform2
  530. # Final tag is, for example, 'cp39-none-win32', 'cp39-none-win_amd64'
  531. # or 'cp38-none-openbsd_6_8_amd64'.
  532. #
  533. tag = f'{tag_python}-{tag_abi}-{tag_platform}'
  534. path = f'{wheel_directory}/{self.name}-{self.version}-{tag}.whl'
  535. # Do a build and get list of files to copy into the wheel.
  536. #
  537. items = list()
  538. if self.fn_build:
  539. items = self._call_fn_build(config_settings)
  540. log2(f'Creating wheel: {path}')
  541. os.makedirs(wheel_directory, exist_ok=True)
  542. record = _Record()
  543. with zipfile.ZipFile(path, 'w', self.wheel_compression, self.wheel_compresslevel) as z:
  544. def add(from_, to_):
  545. if isinstance(from_, str):
  546. z.write(from_, to_)
  547. record.add_file(from_, to_)
  548. elif isinstance(from_, bytes):
  549. z.writestr(to_, from_)
  550. record.add_content(from_, to_)
  551. else:
  552. assert 0
  553. def add_str(content, to_):
  554. add(content.encode('utf8'), to_)
  555. dist_info_dir = self._dist_info_dir()
  556. # Add the files returned by fn_build().
  557. #
  558. for item in items:
  559. from_, (to_abs, to_rel) = self._fromto(item)
  560. add(from_, to_rel)
  561. # Add <name>-<version>.dist-info/WHEEL.
  562. #
  563. add_str(
  564. f'Wheel-Version: 1.0\n'
  565. f'Generator: pipcl\n'
  566. f'Root-Is-Purelib: false\n'
  567. f'Tag: {tag}\n'
  568. ,
  569. f'{dist_info_dir}/WHEEL',
  570. )
  571. # Add <name>-<version>.dist-info/METADATA.
  572. #
  573. add_str(self._metainfo(), f'{dist_info_dir}/METADATA')
  574. # Add <name>-<version>.dist-info/COPYING.
  575. if self.license:
  576. add_str(self.license, f'{dist_info_dir}/COPYING')
  577. # Add <name>-<version>.dist-info/entry_points.txt.
  578. entry_points_text = self._entry_points_text()
  579. if entry_points_text:
  580. add_str(entry_points_text, f'{dist_info_dir}/entry_points.txt')
  581. # Update <name>-<version>.dist-info/RECORD. This must be last.
  582. #
  583. z.writestr(f'{dist_info_dir}/RECORD', record.get(f'{dist_info_dir}/RECORD'))
  584. st = os.stat(path)
  585. log1( f'Have created wheel size={st.st_size}: {path}')
  586. if g_verbose >= 2:
  587. with zipfile.ZipFile(path, compression=self.wheel_compression) as z:
  588. log2(f'Contents are:')
  589. for zi in sorted(z.infolist(), key=lambda z: z.filename):
  590. log2(f' {zi.file_size: 10d} {zi.filename}')
  591. return os.path.basename(path)
  592. def build_sdist(self,
  593. sdist_directory,
  594. formats,
  595. config_settings=None,
  596. ):
  597. '''
  598. A PEP-517 `build_sdist()` function.
  599. Also called by `handle_argv()` to handle the `sdist` command.
  600. Returns leafname of generated archive within `sdist_directory`.
  601. '''
  602. log2(
  603. f' sdist_directory={sdist_directory!r}'
  604. f' formats={formats!r}'
  605. f' config_settings={config_settings!r}'
  606. )
  607. if formats and formats != 'gztar':
  608. raise Exception( f'Unsupported: formats={formats}')
  609. items = list()
  610. if self.fn_sdist:
  611. if inspect.signature(self.fn_sdist).parameters:
  612. items = self.fn_sdist(config_settings)
  613. else:
  614. items = self.fn_sdist()
  615. prefix = f'{self.name}-{self.version}'
  616. os.makedirs(sdist_directory, exist_ok=True)
  617. tarpath = f'{sdist_directory}/{prefix}.tar.gz'
  618. log2(f'Creating sdist: {tarpath}')
  619. with tarfile.open(tarpath, 'w:gz') as tar:
  620. names_in_tar = list()
  621. def check_name(name):
  622. if name in names_in_tar:
  623. raise Exception(f'Name specified twice: {name}')
  624. names_in_tar.append(name)
  625. def add(from_, name):
  626. check_name(name)
  627. if isinstance(from_, str):
  628. log2( f'Adding file: {os.path.relpath(from_)} => {name}')
  629. tar.add( from_, f'{prefix}/{name}', recursive=False)
  630. elif isinstance(from_, bytes):
  631. log2( f'Adding: {name}')
  632. ti = tarfile.TarInfo(f'{prefix}/{name}')
  633. ti.size = len(from_)
  634. ti.mtime = time.time()
  635. tar.addfile(ti, io.BytesIO(from_))
  636. else:
  637. assert 0
  638. def add_string(text, name):
  639. textb = text.encode('utf8')
  640. return add(textb, name)
  641. found_pyproject_toml = False
  642. for item in items:
  643. from_, (to_abs, to_rel) = self._fromto(item)
  644. if isinstance(from_, bytes):
  645. add(from_, to_rel)
  646. else:
  647. if from_.startswith(f'{os.path.abspath(sdist_directory)}/'):
  648. # Source files should not be inside <sdist_directory>.
  649. assert 0, f'Path is inside sdist_directory={sdist_directory}: {from_!r}'
  650. assert os.path.exists(from_), f'Path does not exist: {from_!r}'
  651. assert os.path.isfile(from_), f'Path is not a file: {from_!r}'
  652. if to_rel == 'pyproject.toml':
  653. found_pyproject_toml = True
  654. add(from_, to_rel)
  655. if not found_pyproject_toml:
  656. log0(f'Warning: no pyproject.toml specified.')
  657. # Always add a PKG-INFO file.
  658. add_string(self._metainfo(), 'PKG-INFO')
  659. if self.license:
  660. if 'COPYING' in names_in_tar:
  661. log2(f'Not writing .license because file already in sdist: COPYING')
  662. else:
  663. add_string(self.license, 'COPYING')
  664. log1( f'Have created sdist: {tarpath}')
  665. return os.path.basename(tarpath)
  666. def _entry_points_text(self):
  667. if self.entry_points:
  668. if isinstance(self.entry_points, str):
  669. return self.entry_points
  670. ret = ''
  671. for key, values in self.entry_points.items():
  672. ret += f'[{key}]\n'
  673. for value in values:
  674. ret += f'{value}\n'
  675. return ret
  676. def _call_fn_build( self, config_settings=None):
  677. assert self.fn_build
  678. log2(f'calling self.fn_build={self.fn_build}')
  679. if inspect.signature(self.fn_build).parameters:
  680. ret = self.fn_build(config_settings)
  681. else:
  682. ret = self.fn_build()
  683. assert isinstance( ret, (list, tuple)), \
  684. f'Expected list/tuple from {self.fn_build} but got: {ret!r}'
  685. return ret
  686. def _argv_clean(self, all_):
  687. '''
  688. Called by `handle_argv()`.
  689. '''
  690. if not self.fn_clean:
  691. return
  692. paths = self.fn_clean(all_)
  693. if paths:
  694. if isinstance(paths, str):
  695. paths = paths,
  696. for path in paths:
  697. if not os.path.isabs(path):
  698. path = ps.path.join(self.root, path)
  699. path = os.path.abspath(path)
  700. assert path.startswith(self.root+os.sep), \
  701. f'path={path!r} does not start with root={self.root+os.sep!r}'
  702. log2(f'Removing: {path}')
  703. shutil.rmtree(path, ignore_errors=True)
  704. def install(self, record_path=None, root=None):
  705. '''
  706. Called by `handle_argv()` to handle `install` command..
  707. '''
  708. log2( f'{record_path=} {root=}')
  709. # Do a build and get list of files to install.
  710. #
  711. items = list()
  712. if self.fn_build:
  713. items = self._call_fn_build( dict())
  714. root2 = install_dir(root)
  715. log2( f'{root2=}')
  716. log1( f'Installing into: {root2!r}')
  717. dist_info_dir = self._dist_info_dir()
  718. if not record_path:
  719. record_path = f'{root2}/{dist_info_dir}/RECORD'
  720. record = _Record()
  721. def add_file(from_, to_abs, to_rel):
  722. os.makedirs( os.path.dirname( to_abs), exist_ok=True)
  723. if isinstance(from_, bytes):
  724. log2(f'Copying content into {to_abs}.')
  725. with open(to_abs, 'wb') as f:
  726. f.write(from_)
  727. record.add_content(from_, to_rel)
  728. else:
  729. log0(f'{from_=}')
  730. log2(f'Copying from {os.path.relpath(from_, self.root)} to {to_abs}')
  731. shutil.copy2( from_, to_abs)
  732. record.add_file(from_, to_rel)
  733. def add_str(content, to_abs, to_rel):
  734. log2( f'Writing to: {to_abs}')
  735. os.makedirs( os.path.dirname( to_abs), exist_ok=True)
  736. with open( to_abs, 'w') as f:
  737. f.write( content)
  738. record.add_content(content, to_rel)
  739. for item in items:
  740. from_, (to_abs, to_rel) = self._fromto(item)
  741. log0(f'{from_=} {to_abs=} {to_rel=}')
  742. to_abs2 = f'{root2}/{to_rel}'
  743. add_file( from_, to_abs2, to_rel)
  744. add_str( self._metainfo(), f'{root2}/{dist_info_dir}/METADATA', f'{dist_info_dir}/METADATA')
  745. if self.license:
  746. add_str( self.license, f'{root2}/{dist_info_dir}/COPYING', f'{dist_info_dir}/COPYING')
  747. entry_points_text = self._entry_points_text()
  748. if entry_points_text:
  749. add_str(
  750. entry_points_text,
  751. f'{root2}/{dist_info_dir}/entry_points.txt',
  752. f'{dist_info_dir}/entry_points.txt',
  753. )
  754. log2( f'Writing to: {record_path}')
  755. with open(record_path, 'w') as f:
  756. f.write(record.get())
  757. log2(f'Finished.')
  758. def _argv_dist_info(self, root):
  759. '''
  760. Called by `handle_argv()`. There doesn't seem to be any documentation
  761. for `setup.py dist_info`, but it appears to be like `egg_info` except
  762. it writes to a slightly different directory.
  763. '''
  764. if root is None:
  765. root = f'{self.name}-{self.version}.dist-info'
  766. self._write_info(f'{root}/METADATA')
  767. if self.license:
  768. with open( f'{root}/COPYING', 'w') as f:
  769. f.write( self.license)
  770. def _argv_egg_info(self, egg_base):
  771. '''
  772. Called by `handle_argv()`.
  773. '''
  774. if egg_base is None:
  775. egg_base = '.'
  776. self._write_info(f'{egg_base}/.egg-info')
  777. def _write_info(self, dirpath=None):
  778. '''
  779. Writes egg/dist info to files in directory `dirpath` or `self.root` if
  780. `None`.
  781. '''
  782. if dirpath is None:
  783. dirpath = self.root
  784. log2(f'Creating files in directory {dirpath}')
  785. os.makedirs(dirpath, exist_ok=True)
  786. with open(os.path.join(dirpath, 'PKG-INFO'), 'w') as f:
  787. f.write(self._metainfo())
  788. # These don't seem to be required?
  789. #
  790. #with open(os.path.join(dirpath, 'SOURCES.txt', 'w') as f:
  791. # pass
  792. #with open(os.path.join(dirpath, 'dependency_links.txt', 'w') as f:
  793. # pass
  794. #with open(os.path.join(dirpath, 'top_level.txt', 'w') as f:
  795. # f.write(f'{self.name}\n')
  796. #with open(os.path.join(dirpath, 'METADATA', 'w') as f:
  797. # f.write(self._metainfo())
  798. def handle_argv(self, argv):
  799. '''
  800. Attempt to handles old-style (pre PEP-517) command line passed by
  801. old releases of pip to a `setup.py` script, and manual running of
  802. `setup.py`.
  803. This is partial support at best.
  804. '''
  805. global g_verbose
  806. #log2(f'argv: {argv}')
  807. class ArgsRaise:
  808. pass
  809. class Args:
  810. '''
  811. Iterates over argv items.
  812. '''
  813. def __init__( self, argv):
  814. self.items = iter( argv)
  815. def next( self, eof=ArgsRaise):
  816. '''
  817. Returns next arg. If no more args, we return <eof> or raise an
  818. exception if <eof> is ArgsRaise.
  819. '''
  820. try:
  821. return next( self.items)
  822. except StopIteration:
  823. if eof is ArgsRaise:
  824. raise Exception('Not enough args')
  825. return eof
  826. command = None
  827. opt_all = None
  828. opt_dist_dir = 'dist'
  829. opt_egg_base = None
  830. opt_formats = None
  831. opt_install_headers = None
  832. opt_record = None
  833. opt_root = None
  834. args = Args(argv[1:])
  835. while 1:
  836. arg = args.next(None)
  837. if arg is None:
  838. break
  839. elif arg in ('-h', '--help', '--help-commands'):
  840. log0(textwrap.dedent('''
  841. Usage:
  842. [<options>...] <command> [<options>...]
  843. Commands:
  844. bdist_wheel
  845. Creates a wheel called
  846. <dist-dir>/<name>-<version>-<details>.whl, where
  847. <dist-dir> is "dist" or as specified by --dist-dir,
  848. and <details> encodes ABI and platform etc.
  849. clean
  850. Cleans build files.
  851. dist_info
  852. Creates files in <name>-<version>.dist-info/ or
  853. directory specified by --egg-base.
  854. egg_info
  855. Creates files in .egg-info/ or directory
  856. directory specified by --egg-base.
  857. install
  858. Builds and installs. Writes installation
  859. information to <record> if --record was
  860. specified.
  861. sdist
  862. Make a source distribution:
  863. <dist-dir>/<name>-<version>.tar.gz
  864. Options:
  865. --all
  866. Used by "clean".
  867. --compile
  868. Ignored.
  869. --dist-dir | -d <dist-dir>
  870. Default is "dist".
  871. --egg-base <egg-base>
  872. Used by "egg_info".
  873. --formats <formats>
  874. Used by "sdist".
  875. --install-headers <directory>
  876. Ignored.
  877. --python-tag <python-tag>
  878. Ignored.
  879. --record <record>
  880. Used by "install".
  881. --root <path>
  882. Used by "install".
  883. --single-version-externally-managed
  884. Ignored.
  885. --verbose -v
  886. Extra diagnostics.
  887. Other:
  888. windows-vs [-y <year>] [-v <version>] [-g <grade] [--verbose]
  889. Windows only; looks for matching Visual Studio.
  890. windows-python [-v <version>] [--verbose]
  891. Windows only; looks for matching Python.
  892. '''))
  893. return
  894. elif arg in ('bdist_wheel', 'clean', 'dist_info', 'egg_info', 'install', 'sdist'):
  895. assert command is None, 'Two commands specified: {command} and {arg}.'
  896. command = arg
  897. elif arg == '--all': opt_all = True
  898. elif arg == '--compile': pass
  899. elif arg == '--dist-dir' or arg == '-d': opt_dist_dir = args.next()
  900. elif arg == '--egg-base': opt_egg_base = args.next()
  901. elif arg == '--formats': opt_formats = args.next()
  902. elif arg == '--install-headers': opt_install_headers = args.next()
  903. elif arg == '--python-tag': pass
  904. elif arg == '--record': opt_record = args.next()
  905. elif arg == '--root': opt_root = args.next()
  906. elif arg == '--single-version-externally-managed': pass
  907. elif arg == '--verbose' or arg == '-v': g_verbose += 1
  908. elif arg == 'windows-vs':
  909. command = arg
  910. break
  911. elif arg == 'windows-python':
  912. command = arg
  913. break
  914. else:
  915. raise Exception(f'Unrecognised arg: {arg}')
  916. assert command, 'No command specified'
  917. log1(f'Handling command={command}')
  918. if 0: pass
  919. elif command == 'bdist_wheel': self.build_wheel(opt_dist_dir)
  920. elif command == 'clean': self._argv_clean(opt_all)
  921. elif command == 'dist_info': self._argv_dist_info(opt_egg_base)
  922. elif command == 'egg_info': self._argv_egg_info(opt_egg_base)
  923. elif command == 'install': self.install(opt_record, opt_root)
  924. elif command == 'sdist': self.build_sdist(opt_dist_dir, opt_formats)
  925. elif command == 'windows-python':
  926. version = None
  927. while 1:
  928. arg = args.next(None)
  929. if arg is None:
  930. break
  931. elif arg == '-v':
  932. version = args.next()
  933. elif arg == '--verbose':
  934. g_verbose += 1
  935. else:
  936. assert 0, f'Unrecognised {arg=}'
  937. python = wdev.WindowsPython(version=version)
  938. print(f'Python is:\n{python.description_ml(" ")}')
  939. elif command == 'windows-vs':
  940. grade = None
  941. version = None
  942. year = None
  943. while 1:
  944. arg = args.next(None)
  945. if arg is None:
  946. break
  947. elif arg == '-g':
  948. grade = args.next()
  949. elif arg == '-v':
  950. version = args.next()
  951. elif arg == '-y':
  952. year = args.next()
  953. elif arg == '--verbose':
  954. g_verbose += 1
  955. else:
  956. assert 0, f'Unrecognised {arg=}'
  957. vs = wdev.WindowsVS(year=year, grade=grade, version=version)
  958. print(f'Visual Studio is:\n{vs.description_ml(" ")}')
  959. else:
  960. assert 0, f'Unrecognised command: {command}'
  961. log2(f'Finished handling command: {command}')
  962. def __str__(self):
  963. return ('{'
  964. f'name={self.name!r}'
  965. f' version={self.version!r}'
  966. f' platform={self.platform!r}'
  967. f' supported_platform={self.supported_platform!r}'
  968. f' summary={self.summary!r}'
  969. f' description={self.description!r}'
  970. f' description_content_type={self.description_content_type!r}'
  971. f' keywords={self.keywords!r}'
  972. f' home_page={self.home_page!r}'
  973. f' download_url={self.download_url!r}'
  974. f' author={self.author!r}'
  975. f' author_email={self.author_email!r}'
  976. f' maintainer={self.maintainer!r}'
  977. f' maintainer_email={self.maintainer_email!r}'
  978. f' license={self.license!r}'
  979. f' classifier={self.classifier!r}'
  980. f' requires_dist={self.requires_dist!r}'
  981. f' requires_python={self.requires_python!r}'
  982. f' requires_external={self.requires_external!r}'
  983. f' project_url={self.project_url!r}'
  984. f' provides_extra={self.provides_extra!r}'
  985. f' root={self.root!r}'
  986. f' fn_build={self.fn_build!r}'
  987. f' fn_sdist={self.fn_sdist!r}'
  988. f' fn_clean={self.fn_clean!r}'
  989. f' tag_python={self.tag_python!r}'
  990. f' tag_abi={self.tag_abi!r}'
  991. f' tag_platform={self.tag_platform!r}'
  992. '}'
  993. )
  994. def _dist_info_dir( self):
  995. return f'{self.name}-{self.version}.dist-info'
  996. def _metainfo(self):
  997. '''
  998. Returns text for `.egg-info/PKG-INFO` file, or `PKG-INFO` in an sdist
  999. `.tar.gz` file, or `...dist-info/METADATA` in a wheel.
  1000. '''
  1001. # 2021-04-30: Have been unable to get multiline content working on
  1002. # test.pypi.org so we currently put the description as the body after
  1003. # all the other headers.
  1004. #
  1005. ret = ['']
  1006. def add(key, value):
  1007. if value is None:
  1008. return
  1009. if isinstance( value, (tuple, list)):
  1010. for v in value:
  1011. add( key, v)
  1012. return
  1013. if key == 'License' and '\n' in value:
  1014. # This is ok because we write `self.license` into
  1015. # *.dist-info/COPYING.
  1016. #
  1017. log1( f'Omitting license because contains newline(s).')
  1018. return
  1019. assert '\n' not in value, f'key={key} value contains newline: {value!r}'
  1020. if key == 'Project-URL':
  1021. assert value.count(',') == 1, f'For {key=}, should have one comma in {value!r}.'
  1022. ret[0] += f'{key}: {value}\n'
  1023. #add('Description', self.description)
  1024. add('Metadata-Version', '2.1')
  1025. # These names are from:
  1026. # https://packaging.python.org/specifications/core-metadata/
  1027. #
  1028. for name in (
  1029. 'Name',
  1030. 'Version',
  1031. 'Platform',
  1032. 'Supported-Platform',
  1033. 'Summary',
  1034. 'Description-Content-Type',
  1035. 'Keywords',
  1036. 'Home-page',
  1037. 'Download-URL',
  1038. 'Author',
  1039. 'Author-email',
  1040. 'Maintainer',
  1041. 'Maintainer-email',
  1042. 'License',
  1043. 'Classifier',
  1044. 'Requires-Dist',
  1045. 'Requires-Python',
  1046. 'Requires-External',
  1047. 'Project-URL',
  1048. 'Provides-Extra',
  1049. ):
  1050. identifier = name.lower().replace( '-', '_')
  1051. add( name, getattr( self, identifier))
  1052. ret = ret[0]
  1053. # Append description as the body
  1054. if self.description:
  1055. ret += '\n' # Empty line separates headers from body.
  1056. ret += self.description.strip()
  1057. ret += '\n'
  1058. return ret
  1059. def _path_relative_to_root(self, path, assert_within_root=True):
  1060. '''
  1061. Returns `(path_abs, path_rel)`, where `path_abs` is absolute path and
  1062. `path_rel` is relative to `self.root`.
  1063. Interprets `path` as relative to `self.root` if not absolute.
  1064. We use `os.path.realpath()` to resolve any links.
  1065. if `assert_within_root` is true, assert-fails if `path` is not within
  1066. `self.root`.
  1067. '''
  1068. if os.path.isabs(path):
  1069. p = path
  1070. else:
  1071. p = os.path.join(self.root, path)
  1072. p = os.path.realpath(os.path.abspath(p))
  1073. if assert_within_root:
  1074. assert p.startswith(self.root+os.sep) or p == self.root, \
  1075. f'Path not within root={self.root+os.sep!r}: {path=} {p=}'
  1076. p_rel = os.path.relpath(p, self.root)
  1077. return p, p_rel
  1078. def _fromto(self, p):
  1079. '''
  1080. Returns `(from_, (to_abs, to_rel))`.
  1081. If `p` is a string we convert to `(p, p)`. Otherwise we assert that
  1082. `p` is a tuple `(from_, to_)` where `from_` is str/bytes and `to_` is
  1083. str. If `from_` is a bytes it is contents of file to add, otherwise the
  1084. path of an existing file; non-absolute paths are assumed to be relative
  1085. to `self.root`. If `to_` is empty or ends with `/`, we append the leaf
  1086. of `from_` (which must be a str).
  1087. If `to_` starts with `$dist-info/`, we replace this with
  1088. `self._dist_info_dir()`.
  1089. If `to_` starts with `$data/`, we replace this with
  1090. `{self.name}-{self.version}.data/`.
  1091. We assert that `to_abs` is `within self.root`.
  1092. `to_rel` is derived from the `to_abs` and is relative to self.root`.
  1093. '''
  1094. ret = None
  1095. if isinstance(p, str):
  1096. p = p, p
  1097. assert isinstance(p, tuple) and len(p) == 2
  1098. from_, to_ = p
  1099. assert isinstance(from_, (str, bytes))
  1100. assert isinstance(to_, str)
  1101. if to_.endswith('/') or to_=='':
  1102. to_ += os.path.basename(from_)
  1103. prefix = '$dist-info/'
  1104. if to_.startswith( prefix):
  1105. to_ = f'{self._dist_info_dir()}/{to_[ len(prefix):]}'
  1106. prefix = '$data/'
  1107. if to_.startswith( prefix):
  1108. to_ = f'{self.name}-{self.version}.data/{to_[ len(prefix):]}'
  1109. if isinstance(from_, str):
  1110. from_, _ = self._path_relative_to_root( from_, assert_within_root=False)
  1111. to_ = self._path_relative_to_root(to_)
  1112. assert isinstance(from_, (str, bytes))
  1113. log2(f'returning {from_=} {to_=}')
  1114. return from_, to_
  1115. def build_extension(
  1116. name,
  1117. path_i,
  1118. outdir,
  1119. builddir=None,
  1120. includes=None,
  1121. defines=None,
  1122. libpaths=None,
  1123. libs=None,
  1124. optimise=True,
  1125. debug=False,
  1126. compiler_extra='',
  1127. linker_extra='',
  1128. swig='swig',
  1129. cpp=True,
  1130. prerequisites_swig=None,
  1131. prerequisites_compile=None,
  1132. prerequisites_link=None,
  1133. infer_swig_includes=True,
  1134. ):
  1135. '''
  1136. Builds a Python extension module using SWIG. Works on Windows, Linux, MacOS
  1137. and OpenBSD.
  1138. On Unix, sets rpath when linking shared libraries.
  1139. Args:
  1140. name:
  1141. Name of generated extension module.
  1142. path_i:
  1143. Path of input SWIG `.i` file. Internally we use swig to generate a
  1144. corresponding `.c` or `.cpp` file.
  1145. outdir:
  1146. Output directory for generated files:
  1147. * `{outdir}/{name}.py`
  1148. * `{outdir}/_{name}.so` # Unix
  1149. * `{outdir}/_{name}.*.pyd` # Windows
  1150. We return the leafname of the `.so` or `.pyd` file.
  1151. builddir:
  1152. Where to put intermediate files, for example the .cpp file
  1153. generated by swig and `.d` dependency files. Default is `outdir`.
  1154. includes:
  1155. A string, or a sequence of extra include directories to be prefixed
  1156. with `-I`.
  1157. defines:
  1158. A string, or a sequence of extra preprocessor defines to be
  1159. prefixed with `-D`.
  1160. libpaths
  1161. A string, or a sequence of library paths to be prefixed with
  1162. `/LIBPATH:` on Windows or `-L` on Unix.
  1163. libs
  1164. A string, or a sequence of library names to be prefixed with `-l`.
  1165. optimise:
  1166. Whether to use compiler optimisations.
  1167. debug:
  1168. Whether to build with debug symbols.
  1169. compiler_extra:
  1170. Extra compiler flags.
  1171. linker_extra:
  1172. Extra linker flags.
  1173. swig:
  1174. Base swig command.
  1175. cpp:
  1176. If true we tell SWIG to generate C++ code instead of C.
  1177. prerequisites_swig:
  1178. prerequisites_compile:
  1179. prerequisites_link:
  1180. [These are mainly for use on Windows. On other systems we
  1181. automatically generate dynamic dependencies using swig/compile/link
  1182. commands' `-MD` and `-MF` args.]
  1183. Sequences of extra input files/directories that should force
  1184. running of swig, compile or link commands if they are newer than
  1185. any existing generated SWIG `.i` file, compiled object file or
  1186. shared library file.
  1187. If present, the first occurrence of `True` or `False` forces re-run
  1188. or no re-run. Any occurrence of None is ignored. If an item is a
  1189. directory path we look for newest file within the directory tree.
  1190. If not a sequence, we convert into a single-item list.
  1191. prerequisites_swig
  1192. We use swig's -MD and -MF args to generate dynamic dependencies
  1193. automatically, so this is not usually required.
  1194. prerequisites_compile
  1195. prerequisites_link
  1196. On non-Windows we use cc's -MF and -MF args to generate dynamic
  1197. dependencies so this is not usually required.
  1198. infer_swig_includes:
  1199. If true, we extract `-I<path>` and `-I <path>` args from
  1200. `compile_extra` (also `/I` on windows) and use them with swig so
  1201. that it can see the same header files as C/C++. This is useful
  1202. when using enviromment variables such as `CC` and `CXX` to set
  1203. `compile_extra.
  1204. Returns the leafname of the generated library file within `outdir`, e.g.
  1205. `_{name}.so` on Unix or `_{name}.cp311-win_amd64.pyd` on Windows.
  1206. '''
  1207. if builddir is None:
  1208. builddir = outdir
  1209. includes_text = _flags( includes, '-I')
  1210. defines_text = _flags( defines, '-D')
  1211. libpaths_text = _flags( libpaths, '/LIBPATH:', '"') if windows() else _flags( libpaths, '-L')
  1212. libs_text = _flags( libs, '-l')
  1213. path_cpp = f'{builddir}/{os.path.basename(path_i)}'
  1214. path_cpp += '.cpp' if cpp else '.c'
  1215. os.makedirs( outdir, exist_ok=True)
  1216. # Run SWIG.
  1217. if infer_swig_includes:
  1218. # Extract include flags from `compiler_extra`.
  1219. swig_includes_extra = ''
  1220. compiler_extra_items = compiler_extra.split()
  1221. i = 0
  1222. while i < len(compiler_extra_items):
  1223. item = compiler_extra_items[i]
  1224. # Swig doesn't seem to like a space after `I`.
  1225. if item == '-I' or (windows() and item == '/I'):
  1226. swig_includes_extra += f' -I{compiler_extra_items[i+1]}'
  1227. i += 1
  1228. elif item.startswith('-I') or (windows() and item.startswith('/I')):
  1229. swig_includes_extra += f' -I{compiler_extra_items[i][2:]}'
  1230. i += 1
  1231. swig_includes_extra = swig_includes_extra.strip()
  1232. deps_path = f'{path_cpp}.d'
  1233. prerequisites_swig2 = _get_prerequisites( deps_path)
  1234. run_if(
  1235. f'''
  1236. {swig}
  1237. -Wall
  1238. {"-c++" if cpp else ""}
  1239. -python
  1240. -module {name}
  1241. -outdir {outdir}
  1242. -o {path_cpp}
  1243. -MD -MF {deps_path}
  1244. {includes_text}
  1245. {swig_includes_extra}
  1246. {path_i}
  1247. '''
  1248. ,
  1249. path_cpp,
  1250. path_i,
  1251. prerequisites_swig,
  1252. prerequisites_swig2,
  1253. )
  1254. path_so_leaf = f'_{name}{_so_suffix()}'
  1255. path_so = f'{outdir}/{path_so_leaf}'
  1256. if windows():
  1257. path_obj = f'{path_so}.obj'
  1258. permissive = '/permissive-'
  1259. EHsc = '/EHsc'
  1260. T = '/Tp' if cpp else '/Tc'
  1261. optimise2 = '/DNDEBUG /O2' if optimise else '/D_DEBUG'
  1262. debug2 = ''
  1263. if debug:
  1264. debug2 = '/Zi' # Generate .pdb.
  1265. # debug2 = '/Z7' # Embed debug info in .obj files.
  1266. # As of 2023-08-23, it looks like VS tools create slightly
  1267. # .dll's each time, even with identical inputs.
  1268. #
  1269. # Some info about this is at:
  1270. # https://nikhilism.com/post/2020/windows-deterministic-builds/.
  1271. # E.g. an undocumented linker flag `/Brepro`.
  1272. #
  1273. command, pythonflags = base_compiler(cpp=cpp)
  1274. command = f'''
  1275. {command}
  1276. # General:
  1277. /c # Compiles without linking.
  1278. {EHsc} # Enable "Standard C++ exception handling".
  1279. #/MD # Creates a multithreaded DLL using MSVCRT.lib.
  1280. {'/MDd' if debug else '/MD'}
  1281. # Input/output files:
  1282. {T}{path_cpp} # /Tp specifies C++ source file.
  1283. /Fo{path_obj} # Output file. codespell:ignore
  1284. # Include paths:
  1285. {includes_text}
  1286. {pythonflags.includes} # Include path for Python headers.
  1287. # Code generation:
  1288. {optimise2}
  1289. {debug2}
  1290. {permissive} # Set standard-conformance mode.
  1291. # Diagnostics:
  1292. #/FC # Display full path of source code files passed to cl.exe in diagnostic text.
  1293. /W3 # Sets which warning level to output. /W3 is IDE default.
  1294. /diagnostics:caret # Controls the format of diagnostic messages.
  1295. /nologo #
  1296. {defines_text}
  1297. {compiler_extra}
  1298. '''
  1299. run_if( command, path_obj, path_cpp, prerequisites_compile)
  1300. command, pythonflags = base_linker(cpp=cpp)
  1301. debug2 = '/DEBUG' if debug else ''
  1302. base, _ = os.path.splitext(path_so_leaf)
  1303. command = f'''
  1304. {command}
  1305. /DLL # Builds a DLL.
  1306. /EXPORT:PyInit__{name} # Exports a function.
  1307. /IMPLIB:{base}.lib # Overrides the default import library name.
  1308. {libpaths_text}
  1309. {pythonflags.ldflags}
  1310. /OUT:{path_so} # Specifies the output file name.
  1311. {debug2}
  1312. /nologo
  1313. {libs_text}
  1314. {path_obj}
  1315. {linker_extra}
  1316. '''
  1317. run_if( command, path_so, path_obj, prerequisites_link)
  1318. else:
  1319. # Not Windows.
  1320. #
  1321. command, pythonflags = base_compiler(cpp=cpp)
  1322. # setuptools on Linux seems to use slightly different compile flags:
  1323. #
  1324. # -fwrapv -O3 -Wall -O2 -g0 -DPY_CALL_TRAMPOLINE
  1325. #
  1326. general_flags = ''
  1327. if debug:
  1328. general_flags += ' -g'
  1329. if optimise:
  1330. general_flags += ' -O2 -DNDEBUG'
  1331. if darwin():
  1332. # MacOS's linker does not like `-z origin`.
  1333. rpath_flag = "-Wl,-rpath,@loader_path/"
  1334. # Avoid `Undefined symbols for ... "_PyArg_UnpackTuple" ...'.
  1335. general_flags += ' -undefined dynamic_lookup'
  1336. elif pyodide():
  1337. # Setting `-Wl,-rpath,'$ORIGIN',-z,origin` gives:
  1338. # emcc: warning: ignoring unsupported linker flag: `-rpath` [-Wlinkflags]
  1339. # wasm-ld: error: unknown -z value: origin
  1340. #
  1341. log0(f'pyodide: PEP-3149 suffix untested, so omitting. {_so_suffix()=}.')
  1342. path_so_leaf = f'_{name}.so'
  1343. path_so = f'{outdir}/{path_so_leaf}'
  1344. rpath_flag = ''
  1345. else:
  1346. rpath_flag = "-Wl,-rpath,'$ORIGIN',-z,origin"
  1347. path_so = f'{outdir}/{path_so_leaf}'
  1348. # Fun fact - on Linux, if the -L and -l options are before '{path_cpp}'
  1349. # they seem to be ignored...
  1350. #
  1351. prerequisites = list()
  1352. if pyodide():
  1353. # Looks like pyodide's `cc` can't compile and link in one invocation.
  1354. prerequisites_compile_path = f'{path_cpp}.o.d'
  1355. prerequisites += _get_prerequisites( prerequisites_compile_path)
  1356. command = f'''
  1357. {command}
  1358. -fPIC
  1359. {general_flags.strip()}
  1360. {pythonflags.includes}
  1361. {includes_text}
  1362. {defines_text}
  1363. -MD -MF {prerequisites_compile_path}
  1364. -c {path_cpp}
  1365. -o {path_cpp}.o
  1366. {compiler_extra}
  1367. '''
  1368. prerequisites_link_path = f'{path_cpp}.o.d'
  1369. prerequisites += _get_prerequisites( prerequisites_link_path)
  1370. ld, _ = base_linker(cpp=cpp)
  1371. command += f'''
  1372. && {ld}
  1373. {path_cpp}.o
  1374. -o {path_so}
  1375. -MD -MF {prerequisites_link_path}
  1376. {rpath_flag}
  1377. {libpaths_text}
  1378. {libs_text}
  1379. {linker_extra}
  1380. {pythonflags.ldflags}
  1381. '''
  1382. else:
  1383. # We use compiler to compile and link in one command.
  1384. prerequisites_path = f'{path_so}.d'
  1385. prerequisites = _get_prerequisites(prerequisites_path)
  1386. command = f'''
  1387. {command}
  1388. -fPIC
  1389. -shared
  1390. {general_flags.strip()}
  1391. {pythonflags.includes}
  1392. {includes_text}
  1393. {defines_text}
  1394. {path_cpp}
  1395. -MD -MF {prerequisites_path}
  1396. -o {path_so}
  1397. {compiler_extra}
  1398. {libpaths_text}
  1399. {linker_extra}
  1400. {pythonflags.ldflags}
  1401. {libs_text}
  1402. {rpath_flag}
  1403. '''
  1404. command_was_run = run_if(
  1405. command,
  1406. path_so,
  1407. path_cpp,
  1408. prerequisites_compile,
  1409. prerequisites_link,
  1410. prerequisites,
  1411. )
  1412. if command_was_run and darwin():
  1413. # We need to patch up references to shared libraries in `libs`.
  1414. sublibraries = list()
  1415. for lib in () if libs is None else libs:
  1416. for libpath in libpaths:
  1417. found = list()
  1418. for suffix in '.so', '.dylib':
  1419. path = f'{libpath}/lib{os.path.basename(lib)}{suffix}'
  1420. if os.path.exists( path):
  1421. found.append( path)
  1422. if found:
  1423. assert len(found) == 1, f'More than one file matches lib={lib!r}: {found}'
  1424. sublibraries.append( found[0])
  1425. break
  1426. else:
  1427. log2(f'Warning: can not find path of lib={lib!r} in libpaths={libpaths}')
  1428. macos_patch( path_so, *sublibraries)
  1429. #run(f'ls -l {path_so}', check=0)
  1430. #run(f'file {path_so}', check=0)
  1431. return path_so_leaf
  1432. # Functions that might be useful.
  1433. #
  1434. def base_compiler(vs=None, pythonflags=None, cpp=False, use_env=True):
  1435. '''
  1436. Returns basic compiler command and PythonFlags.
  1437. Args:
  1438. vs:
  1439. Windows only. A `wdev.WindowsVS` instance or None to use default
  1440. `wdev.WindowsVS` instance.
  1441. pythonflags:
  1442. A `pipcl.PythonFlags` instance or None to use default
  1443. `pipcl.PythonFlags` instance.
  1444. cpp:
  1445. If true we return C++ compiler command instead of C. On Windows
  1446. this has no effect - we always return `cl.exe`.
  1447. use_env:
  1448. If true we return '$CC' or '$CXX' if the corresponding
  1449. environmental variable is set (without evaluating with `getenv()`
  1450. or `os.environ`).
  1451. Returns `(cc, pythonflags)`:
  1452. cc:
  1453. C or C++ command. On Windows this is of the form
  1454. `{vs.vcvars}&&{vs.cl}`; otherwise it is typically `cc` or `c++`.
  1455. pythonflags:
  1456. The `pythonflags` arg or a new `pipcl.PythonFlags` instance.
  1457. '''
  1458. if not pythonflags:
  1459. pythonflags = PythonFlags()
  1460. cc = None
  1461. if use_env:
  1462. if cpp:
  1463. if os.environ.get( 'CXX'):
  1464. cc = '$CXX'
  1465. else:
  1466. if os.environ.get( 'CC'):
  1467. cc = '$CC'
  1468. if cc:
  1469. pass
  1470. elif windows():
  1471. if not vs:
  1472. vs = wdev.WindowsVS()
  1473. cc = f'"{vs.vcvars}"&&"{vs.cl}"'
  1474. elif wasm():
  1475. cc = 'em++' if cpp else 'emcc'
  1476. else:
  1477. cc = 'c++' if cpp else 'cc'
  1478. cc = macos_add_cross_flags( cc)
  1479. return cc, pythonflags
  1480. def base_linker(vs=None, pythonflags=None, cpp=False, use_env=True):
  1481. '''
  1482. Returns basic linker command.
  1483. Args:
  1484. vs:
  1485. Windows only. A `wdev.WindowsVS` instance or None to use default
  1486. `wdev.WindowsVS` instance.
  1487. pythonflags:
  1488. A `pipcl.PythonFlags` instance or None to use default
  1489. `pipcl.PythonFlags` instance.
  1490. cpp:
  1491. If true we return C++ linker command instead of C. On Windows this
  1492. has no effect - we always return `link.exe`.
  1493. use_env:
  1494. If true we use `os.environ['LD']` if set.
  1495. Returns `(linker, pythonflags)`:
  1496. linker:
  1497. Linker command. On Windows this is of the form
  1498. `{vs.vcvars}&&{vs.link}`; otherwise it is typically `cc` or `c++`.
  1499. pythonflags:
  1500. The `pythonflags` arg or a new `pipcl.PythonFlags` instance.
  1501. '''
  1502. if not pythonflags:
  1503. pythonflags = PythonFlags()
  1504. linker = None
  1505. if use_env:
  1506. if os.environ.get( 'LD'):
  1507. linker = '$LD'
  1508. if linker:
  1509. pass
  1510. elif windows():
  1511. if not vs:
  1512. vs = wdev.WindowsVS()
  1513. linker = f'"{vs.vcvars}"&&"{vs.link}"'
  1514. elif wasm():
  1515. linker = 'em++' if cpp else 'emcc'
  1516. else:
  1517. linker = 'c++' if cpp else 'cc'
  1518. linker = macos_add_cross_flags( linker)
  1519. return linker, pythonflags
  1520. def git_items( directory, submodules=False):
  1521. '''
  1522. Returns list of paths for all files known to git within a `directory`.
  1523. Args:
  1524. directory:
  1525. Must be somewhere within a git checkout.
  1526. submodules:
  1527. If true we also include git submodules.
  1528. Returns:
  1529. A list of paths for all files known to git within `directory`. Each
  1530. path is relative to `directory`. `directory` must be somewhere within a
  1531. git checkout.
  1532. We run a `git ls-files` command internally.
  1533. This function can be useful for the `fn_sdist()` callback.
  1534. '''
  1535. command = 'cd ' + directory + ' && git ls-files'
  1536. if submodules:
  1537. command += ' --recurse-submodules'
  1538. log1(f'Running {command=}')
  1539. text = subprocess.check_output( command, shell=True)
  1540. ret = []
  1541. for path in text.decode('utf8').strip().split( '\n'):
  1542. path2 = os.path.join(directory, path)
  1543. # Sometimes git ls-files seems to list empty/non-existent directories
  1544. # within submodules.
  1545. #
  1546. if not os.path.exists(path2):
  1547. log2(f'Ignoring git ls-files item that does not exist: {path2}')
  1548. elif os.path.isdir(path2):
  1549. log2(f'Ignoring git ls-files item that is actually a directory: {path2}')
  1550. else:
  1551. ret.append(path)
  1552. return ret
  1553. def run( command, capture=False, check=1, verbose=1):
  1554. '''
  1555. Runs a command using `subprocess.run()`.
  1556. Args:
  1557. command:
  1558. A string, the command to run.
  1559. Multiple lines in `command` are are treated as a single command.
  1560. * If a line starts with `#` it is discarded.
  1561. * If a line contains ` #`, the trailing text is discarded.
  1562. When running the command, on Windows newlines are replaced by
  1563. spaces; otherwise each line is terminated by a backslash character.
  1564. capture:
  1565. If true, we include the command's output in our return value.
  1566. check:
  1567. If true we raise an exception on error; otherwise we include the
  1568. command's returncode in our return value.
  1569. verbose:
  1570. If true we show the command.
  1571. Returns:
  1572. check capture Return
  1573. --------------------------
  1574. false false returncode
  1575. false true (returncode, output)
  1576. true false None or raise exception
  1577. true true output or raise exception
  1578. '''
  1579. lines = _command_lines( command)
  1580. nl = '\n'
  1581. if verbose:
  1582. log1( f'Running: {nl.join(lines)}')
  1583. sep = ' ' if windows() else ' \\\n'
  1584. command2 = sep.join( lines)
  1585. cp = subprocess.run(
  1586. command2,
  1587. shell=True,
  1588. stdout=subprocess.PIPE if capture else None,
  1589. stderr=subprocess.STDOUT if capture else None,
  1590. check=check,
  1591. encoding='utf8',
  1592. )
  1593. if check:
  1594. return cp.stdout if capture else None
  1595. else:
  1596. return (cp.returncode, cp.stdout) if capture else cp.returncode
  1597. def darwin():
  1598. return sys.platform.startswith( 'darwin')
  1599. def windows():
  1600. return platform.system() == 'Windows'
  1601. def wasm():
  1602. return os.environ.get( 'OS') in ('wasm', 'wasm-mt')
  1603. def pyodide():
  1604. return os.environ.get( 'PYODIDE') == '1'
  1605. def linux():
  1606. return platform.system() == 'Linux'
  1607. def openbsd():
  1608. return platform.system() == 'OpenBSD'
  1609. class PythonFlags:
  1610. '''
  1611. Compile/link flags for the current python, for example the include path
  1612. needed to get `Python.h`.
  1613. The 'PIPCL_PYTHON_CONFIG' environment variable allows to override
  1614. the location of the python-config executable.
  1615. Members:
  1616. .includes:
  1617. String containing compiler flags for include paths.
  1618. .ldflags:
  1619. String containing linker flags for library paths.
  1620. '''
  1621. def __init__(self):
  1622. if windows():
  1623. wp = wdev.WindowsPython()
  1624. self.includes = f'/I"{wp.include}"'
  1625. self.ldflags = f'/LIBPATH:"{wp.libs}"'
  1626. elif pyodide():
  1627. _include_dir = os.environ[ 'PYO3_CROSS_INCLUDE_DIR']
  1628. _lib_dir = os.environ[ 'PYO3_CROSS_LIB_DIR']
  1629. self.includes = f'-I {_include_dir}'
  1630. self.ldflags = f'-L {_lib_dir}'
  1631. else:
  1632. python_config = os.environ.get("PIPCL_PYTHON_CONFIG")
  1633. if not python_config:
  1634. # We use python-config which appears to work better than pkg-config
  1635. # because it copes with multiple installed python's, e.g.
  1636. # manylinux_2014's /opt/python/cp*-cp*/bin/python*.
  1637. #
  1638. # But... on non-macos it seems that we should not attempt to specify
  1639. # libpython on the link command. The manylinux docker containers
  1640. # don't actually contain libpython.so, and it seems that this
  1641. # deliberate. And the link command runs ok.
  1642. #
  1643. python_exe = os.path.realpath( sys.executable)
  1644. if darwin():
  1645. # Basic install of dev tools with `xcode-select --install` doesn't
  1646. # seem to provide a `python3-config` or similar, but there is a
  1647. # `python-config.py` accessible via sysconfig.
  1648. #
  1649. # We try different possibilities and use the last one that
  1650. # works.
  1651. #
  1652. python_config = None
  1653. for pc in (
  1654. f'python3-config',
  1655. f'{sys.executable} {sysconfig.get_config_var("srcdir")}/python-config.py',
  1656. f'{python_exe}-config',
  1657. ):
  1658. e = subprocess.run(
  1659. f'{pc} --includes',
  1660. shell=1,
  1661. stdout=subprocess.DEVNULL,
  1662. stderr=subprocess.DEVNULL,
  1663. check=0,
  1664. ).returncode
  1665. log2(f'{e=} from {pc!r}.')
  1666. if e == 0:
  1667. python_config = pc
  1668. assert python_config, f'Cannot find python-config'
  1669. else:
  1670. python_config = f'{python_exe}-config'
  1671. log2(f'Using {python_config=}.')
  1672. try:
  1673. self.includes = run( f'{python_config} --includes', capture=1, verbose=0).strip()
  1674. except Exception as e:
  1675. raise Exception('We require python development tools to be installed.') from e
  1676. self.ldflags = run( f'{python_config} --ldflags', capture=1, verbose=0).strip()
  1677. if linux():
  1678. # It seems that with python-3.10 on Linux, we can get an
  1679. # incorrect -lcrypt flag that on some systems (e.g. WSL)
  1680. # causes:
  1681. #
  1682. # ImportError: libcrypt.so.2: cannot open shared object file: No such file or directory
  1683. #
  1684. ldflags2 = self.ldflags.replace(' -lcrypt ', ' ')
  1685. if ldflags2 != self.ldflags:
  1686. log2(f'### Have removed `-lcrypt` from ldflags: {self.ldflags!r} -> {ldflags2!r}')
  1687. self.ldflags = ldflags2
  1688. log2(f'{self.includes=}')
  1689. log2(f'{self.ldflags=}')
  1690. def macos_add_cross_flags(command):
  1691. '''
  1692. If running on MacOS and environment variables ARCHFLAGS is set
  1693. (indicating we are cross-building, e.g. for arm64), returns
  1694. `command` with extra flags appended. Otherwise returns unchanged
  1695. `command`.
  1696. '''
  1697. if darwin():
  1698. archflags = os.environ.get( 'ARCHFLAGS')
  1699. if archflags:
  1700. command = f'{command} {archflags}'
  1701. log2(f'Appending ARCHFLAGS to command: {command}')
  1702. return command
  1703. return command
  1704. def macos_patch( library, *sublibraries):
  1705. '''
  1706. If running on MacOS, patches `library` so that all references to items in
  1707. `sublibraries` are changed to `@rpath/{leafname}`. Does nothing on other
  1708. platforms.
  1709. library:
  1710. Path of shared library.
  1711. sublibraries:
  1712. List of paths of shared libraries; these have typically been
  1713. specified with `-l` when `library` was created.
  1714. '''
  1715. log2( f'macos_patch(): library={library} sublibraries={sublibraries}')
  1716. if not darwin():
  1717. return
  1718. if not sublibraries:
  1719. return
  1720. subprocess.run( f'otool -L {library}', shell=1, check=1)
  1721. command = 'install_name_tool'
  1722. names = []
  1723. for sublibrary in sublibraries:
  1724. name = subprocess.run(
  1725. f'otool -D {sublibrary}',
  1726. shell=1,
  1727. check=1,
  1728. capture_output=1,
  1729. encoding='utf8',
  1730. ).stdout.strip()
  1731. name = name.split('\n')
  1732. assert len(name) == 2 and name[0] == f'{sublibrary}:', f'{name=}'
  1733. name = name[1]
  1734. # strip trailing so_name.
  1735. leaf = os.path.basename(name)
  1736. m = re.match('^(.+[.]((so)|(dylib)))[0-9.]*$', leaf)
  1737. assert m
  1738. log2(f'Changing {leaf=} to {m.group(1)}')
  1739. leaf = m.group(1)
  1740. command += f' -change {name} @rpath/{leaf}'
  1741. command += f' {library}'
  1742. log2( f'Running: {command}')
  1743. subprocess.run( command, shell=1, check=1)
  1744. subprocess.run( f'otool -L {library}', shell=1, check=1)
  1745. # Internal helpers.
  1746. #
  1747. def _command_lines( command):
  1748. '''
  1749. Process multiline command by running through `textwrap.dedent()`, removes
  1750. comments (lines starting with `#` or ` #` until end of line), removes
  1751. entirely blank lines.
  1752. Returns list of lines.
  1753. '''
  1754. command = textwrap.dedent( command)
  1755. lines = []
  1756. for line in command.split( '\n'):
  1757. if line.startswith( '#'):
  1758. h = 0
  1759. else:
  1760. h = line.find( ' #')
  1761. if h >= 0:
  1762. line = line[:h]
  1763. if line.strip():
  1764. lines.append(line.rstrip())
  1765. return lines
  1766. def _cpu_name():
  1767. '''
  1768. Returns `x32` or `x64` depending on Python build.
  1769. '''
  1770. #log(f'sys.maxsize={hex(sys.maxsize)}')
  1771. return f'x{32 if sys.maxsize == 2**31 - 1 else 64}'
  1772. def run_if( command, out, *prerequisites):
  1773. '''
  1774. Runs a command only if the output file is not up to date.
  1775. Args:
  1776. command:
  1777. The command to run. We write this into a file <out>.cmd so that we
  1778. know to run a command if the command itself has changed.
  1779. out:
  1780. Path of the output file.
  1781. prerequisites:
  1782. List of prerequisite paths or true/false/None items. If an item
  1783. is None it is ignored, otherwise if an item is not a string we
  1784. immediately return it cast to a bool.
  1785. Returns:
  1786. True if we ran the command, otherwise None.
  1787. If the output file does not exist, the command is run:
  1788. >>> verbose(1)
  1789. 1
  1790. >>> out = 'run_if_test_out'
  1791. >>> if os.path.exists( out):
  1792. ... os.remove( out)
  1793. >>> if os.path.exists( f'{out}.cmd'):
  1794. ... os.remove( f'{out}.cmd')
  1795. >>> run_if( f'touch {out}', out)
  1796. pipcl.py: run_if(): Running command because: File does not exist: 'run_if_test_out'
  1797. pipcl.py: run(): Running: touch run_if_test_out
  1798. True
  1799. If we repeat, the output file will be up to date so the command is not run:
  1800. >>> run_if( f'touch {out}', out)
  1801. pipcl.py: run_if(): Not running command because up to date: 'run_if_test_out'
  1802. If we change the command, the command is run:
  1803. >>> run_if( f'touch {out}', out)
  1804. pipcl.py: run_if(): Running command because: Command has changed
  1805. pipcl.py: run(): Running: touch run_if_test_out
  1806. True
  1807. If we add a prerequisite that is newer than the output, the command is run:
  1808. >>> time.sleep(1)
  1809. >>> prerequisite = 'run_if_test_prerequisite'
  1810. >>> run( f'touch {prerequisite}')
  1811. pipcl.py: run(): Running: touch run_if_test_prerequisite
  1812. >>> run_if( f'touch {out}', out, prerequisite)
  1813. pipcl.py: run_if(): Running command because: Prerequisite is new: 'run_if_test_prerequisite'
  1814. pipcl.py: run(): Running: touch run_if_test_out
  1815. True
  1816. If we repeat, the output will be newer than the prerequisite, so the
  1817. command is not run:
  1818. >>> run_if( f'touch {out}', out, prerequisite)
  1819. pipcl.py: run_if(): Not running command because up to date: 'run_if_test_out'
  1820. '''
  1821. doit = False
  1822. cmd_path = f'{out}.cmd'
  1823. if not doit:
  1824. out_mtime = _fs_mtime( out)
  1825. if out_mtime == 0:
  1826. doit = f'File does not exist: {out!r}'
  1827. if not doit:
  1828. if os.path.isfile( cmd_path):
  1829. with open( cmd_path) as f:
  1830. cmd = f.read()
  1831. else:
  1832. cmd = None
  1833. if command != cmd:
  1834. if cmd is None:
  1835. doit = 'No previous command stored'
  1836. else:
  1837. doit = f'Command has changed'
  1838. if 0:
  1839. doit += f': {cmd!r} => {command!r}'
  1840. if not doit:
  1841. # See whether any prerequisites are newer than target.
  1842. def _make_prerequisites(p):
  1843. if isinstance( p, (list, tuple)):
  1844. return list(p)
  1845. else:
  1846. return [p]
  1847. prerequisites_all = list()
  1848. for p in prerequisites:
  1849. prerequisites_all += _make_prerequisites( p)
  1850. if 0:
  1851. log2( 'prerequisites_all:')
  1852. for i in prerequisites_all:
  1853. log2( f' {i!r}')
  1854. pre_mtime = 0
  1855. pre_path = None
  1856. for prerequisite in prerequisites_all:
  1857. if isinstance( prerequisite, str):
  1858. mtime = _fs_mtime_newest( prerequisite)
  1859. if mtime >= pre_mtime:
  1860. pre_mtime = mtime
  1861. pre_path = prerequisite
  1862. elif prerequisite is None:
  1863. pass
  1864. elif prerequisite:
  1865. doit = str(prerequisite)
  1866. break
  1867. if not doit:
  1868. if pre_mtime > out_mtime:
  1869. doit = f'Prerequisite is new: {pre_path!r}'
  1870. if doit:
  1871. # Remove `cmd_path` before we run the command, so any failure
  1872. # will force rerun next time.
  1873. #
  1874. try:
  1875. os.remove( cmd_path)
  1876. except Exception:
  1877. pass
  1878. log1( f'Running command because: {doit}')
  1879. run( command)
  1880. # Write the command we ran, into `cmd_path`.
  1881. with open( cmd_path, 'w') as f:
  1882. f.write( command)
  1883. return True
  1884. else:
  1885. log1( f'Not running command because up to date: {out!r}')
  1886. if 0:
  1887. log2( f'out_mtime={time.ctime(out_mtime)} pre_mtime={time.ctime(pre_mtime)}.'
  1888. f' pre_path={pre_path!r}: returning {ret!r}.'
  1889. )
  1890. def _get_prerequisites(path):
  1891. '''
  1892. Returns list of prerequisites from Makefile-style dependency file, e.g.
  1893. created by `cc -MD -MF <path>`.
  1894. '''
  1895. ret = list()
  1896. if os.path.isfile(path):
  1897. with open(path) as f:
  1898. for line in f:
  1899. for item in line.split():
  1900. if item.endswith( (':', '\\')):
  1901. continue
  1902. ret.append( item)
  1903. return ret
  1904. def _fs_mtime_newest( path):
  1905. '''
  1906. path:
  1907. If a file, returns mtime of the file. If a directory, returns mtime of
  1908. newest file anywhere within directory tree. Otherwise returns 0.
  1909. '''
  1910. ret = 0
  1911. if os.path.isdir( path):
  1912. for dirpath, dirnames, filenames in os.walk( path):
  1913. for filename in filenames:
  1914. path = os.path.join( dirpath, filename)
  1915. ret = max( ret, _fs_mtime( path))
  1916. else:
  1917. ret = _fs_mtime( path)
  1918. return ret
  1919. def _flags( items, prefix='', quote=''):
  1920. '''
  1921. Turns sequence into string, prefixing/quoting each item.
  1922. '''
  1923. if not items:
  1924. return ''
  1925. if isinstance( items, str):
  1926. return items
  1927. ret = ''
  1928. for item in items:
  1929. if ret:
  1930. ret += ' '
  1931. ret += f'{prefix}{quote}{item}{quote}'
  1932. return ret.strip()
  1933. def _fs_mtime( filename, default=0):
  1934. '''
  1935. Returns mtime of file, or `default` if error - e.g. doesn't exist.
  1936. '''
  1937. try:
  1938. return os.path.getmtime( filename)
  1939. except OSError:
  1940. return default
  1941. def _assert_version_pep_440(version):
  1942. assert re.match(
  1943. 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]*))?$',
  1944. version,
  1945. ), \
  1946. f'Bad version: {version!r}.'
  1947. g_verbose = int(os.environ.get('PIPCL_VERBOSE', '1'))
  1948. def verbose(level=None):
  1949. '''
  1950. Sets verbose level if `level` is not None.
  1951. Returns verbose level.
  1952. '''
  1953. global g_verbose
  1954. if level is not None:
  1955. g_verbose = level
  1956. return g_verbose
  1957. def log0(text=''):
  1958. _log(text, 0)
  1959. def log1(text=''):
  1960. _log(text, 1)
  1961. def log2(text=''):
  1962. _log(text, 2)
  1963. def _log(text, level):
  1964. '''
  1965. Logs lines with prefix.
  1966. '''
  1967. if g_verbose >= level:
  1968. caller = inspect.stack()[2].function
  1969. for line in text.split('\n'):
  1970. print(f'pipcl.py: {caller}(): {line}')
  1971. sys.stdout.flush()
  1972. def _so_suffix():
  1973. '''
  1974. Filename suffix for shared libraries is defined in pep-3149. The
  1975. pep claims to only address posix systems, but the recommended
  1976. sysconfig.get_config_var('EXT_SUFFIX') also seems to give the
  1977. right string on Windows.
  1978. '''
  1979. # Example values:
  1980. # linux: .cpython-311-x86_64-linux-gnu.so
  1981. # macos: .cpython-311-darwin.so
  1982. # openbsd: .cpython-310.so
  1983. # windows .cp311-win_amd64.pyd
  1984. #
  1985. # Only Linux and Windows seem to identify the cpu. For example shared
  1986. # libraries in numpy-1.25.2-cp311-cp311-macosx_11_0_arm64.whl are called
  1987. # things like `numpy/core/_simd.cpython-311-darwin.so`.
  1988. #
  1989. return sysconfig.get_config_var('EXT_SUFFIX')
  1990. def get_soname(path):
  1991. '''
  1992. If we are on Linux and `path` is softlink and points to a shared library
  1993. for which `objdump -p` contains 'SONAME', return the pointee. Otherwise
  1994. return `path`. Useful if Linux shared libraries have been created with
  1995. `-Wl,-soname,...`, where we need to embed the versioned library.
  1996. '''
  1997. if linux() and os.path.islink(path):
  1998. path2 = os.path.realpath(path)
  1999. if subprocess.run(f'objdump -p {path2}|grep SONAME', shell=1, check=0).returncode == 0:
  2000. return path2
  2001. elif openbsd():
  2002. # Return newest .so with version suffix.
  2003. sos = glob.glob(f'{path}.*')
  2004. log1(f'{sos=}')
  2005. sos2 = list()
  2006. for so in sos:
  2007. suffix = so[len(path):]
  2008. if not suffix or re.match('^[.][0-9.]*[0-9]$', suffix):
  2009. sos2.append(so)
  2010. sos2.sort(key=lambda p: os.path.getmtime(p))
  2011. log1(f'{sos2=}')
  2012. return sos2[-1]
  2013. return path
  2014. def install_dir(root=None):
  2015. '''
  2016. Returns install directory used by `install()`.
  2017. This will be `sysconfig.get_path('platlib')`, modified by `root` if not
  2018. None.
  2019. '''
  2020. # todo: for pure-python we should use sysconfig.get_path('purelib') ?
  2021. root2 = sysconfig.get_path('platlib')
  2022. if root:
  2023. if windows():
  2024. # If we are in a venv, `sysconfig.get_path('platlib')`
  2025. # can be absolute, e.g.
  2026. # `C:\\...\\venv-pypackage-3.11.1-64\\Lib\\site-packages`, so it's
  2027. # not clear how to append it to `root`. So we just use `root`.
  2028. return root
  2029. else:
  2030. # E.g. if `root` is `install' and `sysconfig.get_path('platlib')`
  2031. # is `/usr/local/lib/python3.9/site-packages`, we set `root2` to
  2032. # `install/usr/local/lib/python3.9/site-packages`.
  2033. #
  2034. return os.path.join( root, root2.lstrip( os.sep))
  2035. else:
  2036. return root2
  2037. class _Record:
  2038. '''
  2039. Internal - builds up text suitable for writing to a RECORD item, e.g.
  2040. within a wheel.
  2041. '''
  2042. def __init__(self):
  2043. self.text = ''
  2044. def add_content(self, content, to_, verbose=True):
  2045. if isinstance(content, str):
  2046. content = content.encode('utf8')
  2047. # Specification for the line we write is supposed to be in
  2048. # https://packaging.python.org/en/latest/specifications/binary-distribution-format
  2049. # but it's not very clear.
  2050. #
  2051. h = hashlib.sha256(content)
  2052. digest = h.digest()
  2053. digest = base64.urlsafe_b64encode(digest)
  2054. digest = digest.rstrip(b'=')
  2055. digest = digest.decode('utf8')
  2056. self.text += f'{to_},sha256={digest},{len(content)}\n'
  2057. if verbose:
  2058. log2(f'Adding {to_}')
  2059. def add_file(self, from_, to_):
  2060. log1(f'Adding file: {os.path.relpath(from_)} => {to_}')
  2061. with open(from_, 'rb') as f:
  2062. content = f.read()
  2063. self.add_content(content, to_, verbose=False)
  2064. def get(self, record_path=None):
  2065. '''
  2066. Returns contents of the RECORD file. If `record_path` is
  2067. specified we append a final line `<record_path>,,`; this can be
  2068. used to include the RECORD file itself in the contents, with
  2069. empty hash and size fields.
  2070. '''
  2071. ret = self.text
  2072. if record_path:
  2073. ret += f'{record_path},,\n'
  2074. return ret