makewheel.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. """
  2. Generates a wheel (.whl) file from the output of makepanda.
  3. """
  4. from __future__ import print_function, unicode_literals
  5. import json
  6. import sys
  7. import os
  8. from os.path import join
  9. import shutil
  10. import zipfile
  11. import hashlib
  12. import tempfile
  13. import subprocess
  14. from optparse import OptionParser
  15. from makepandacore import ColorText, LocateBinary, GetExtensionSuffix, SetVerbose, GetVerbose, GetMetadataValue
  16. from base64 import urlsafe_b64encode
  17. from locations import get_config_var
  18. from sysconfig import get_platform
  19. def get_abi_tag():
  20. if sys.version_info >= (3, 13):
  21. ver = 'cp%d%d' % sys.version_info[:2]
  22. if hasattr(sys, 'abiflags'):
  23. return ver + sys.abiflags
  24. gil_disabled = get_config_var("Py_GIL_DISABLED")
  25. if gil_disabled and int(gil_disabled):
  26. return ver + 't'
  27. return ver
  28. if sys.version_info >= (3, 0):
  29. soabi = get_config_var('SOABI')
  30. if soabi and soabi.startswith('cpython-'):
  31. return 'cp' + soabi.split('-')[1]
  32. elif soabi:
  33. return soabi.replace('.', '_').replace('-', '_')
  34. soabi = 'cp%d%d' % (sys.version_info[:2])
  35. if sys.version_info >= (3, 8):
  36. return soabi
  37. debug_flag = get_config_var('Py_DEBUG')
  38. if (debug_flag is None and hasattr(sys, 'gettotalrefcount')) or debug_flag:
  39. soabi += 'd'
  40. malloc_flag = get_config_var('WITH_PYMALLOC')
  41. if malloc_flag is None or malloc_flag:
  42. soabi += 'm'
  43. if sys.version_info < (3, 3):
  44. usize = get_config_var('Py_UNICODE_SIZE')
  45. if (usize is None and sys.maxunicode == 0x10ffff) or usize == 4:
  46. soabi += 'u'
  47. return soabi
  48. def is_exe_file(path):
  49. return os.path.isfile(path) and path.lower().endswith('.exe')
  50. def is_elf_file(path):
  51. base = os.path.basename(path)
  52. return os.path.isfile(path) and '.' not in base and \
  53. open(path, 'rb').read(4) == b'\x7FELF'
  54. def is_macho_or_fat_file(path):
  55. base = os.path.basename(path)
  56. return os.path.isfile(path) and '.' not in base and \
  57. open(path, 'rb').read(4) in (b'\xFE\xED\xFA\xCE', b'\xCE\xFA\xED\xFE',
  58. b'\xFE\xED\xFA\xCF', b'\xCF\xFA\xED\xFE',
  59. b'\xCA\xFE\xBA\xBE', b'\xBE\xBA\xFE\xCA',
  60. b'\xCA\xFE\xBA\xBF', b'\xBF\xBA\xFE\xCA')
  61. def is_fat_file(path):
  62. return os.path.isfile(path) and \
  63. open(path, 'rb').read(4) in (b'\xCA\xFE\xBA\xBE', b'\xBE\xBA\xFE\xCA',
  64. b'\xCA\xFE\xBA\xBF', b'\xBF\xBA\xFE\xCA')
  65. def get_python_ext_module_dir():
  66. import _ctypes
  67. return os.path.dirname(_ctypes.__file__)
  68. if sys.platform in ('win32', 'cygwin'):
  69. is_executable = is_exe_file
  70. elif sys.platform == 'darwin':
  71. is_executable = is_macho_or_fat_file
  72. else:
  73. is_executable = is_elf_file
  74. # Other global parameters
  75. PY_VERSION = "cp{0}{1}".format(*sys.version_info)
  76. ABI_TAG = get_abi_tag()
  77. EXCLUDE_EXT = [".pyc", ".pyo", ".N", ".prebuilt", ".xcf", ".plist", ".vcproj", ".sln"]
  78. # Plug-ins to install.
  79. PLUGIN_LIBS = ["pandagl", "pandagles", "pandagles2", "pandadx9", "p3tinydisplay", "p3ptloader", "p3assimp", "p3ffmpeg", "p3openal_audio", "p3fmod_audio", "p3headlessgl"]
  80. # Libraries included in manylinux ABI that should be ignored. See PEP 513/571/599.
  81. MANYLINUX_LIBS = [
  82. "libgcc_s.so.1", "libstdc++.so.6", "libm.so.6", "libdl.so.2", "librt.so.1",
  83. "libcrypt.so.1", "libc.so.6", "libnsl.so.1", "libutil.so.1",
  84. "libpthread.so.0", "libresolv.so.2", "libX11.so.6", "libXext.so.6",
  85. "libXrender.so.1", "libICE.so.6", "libSM.so.6", "libGL.so.1",
  86. "libgobject-2.0.so.0", "libgthread-2.0.so.0", "libglib-2.0.so.0",
  87. # These are not mentioned in manylinux1 spec but should nonetheless always
  88. # be excluded.
  89. "linux-vdso.so.1", "linux-gate.so.1", "ld-linux.so.2", "libdrm.so.2",
  90. "libEGL.so.1", "libOpenGL.so.0", "libGLX.so.0", "libGLdispatch.so.0",
  91. ]
  92. # Binaries to never scan for dependencies on non-Windows systems.
  93. IGNORE_UNIX_DEPS_OF = [
  94. "panda3d_tools/pstats",
  95. ]
  96. WHEEL_DATA = """Wheel-Version: 1.0
  97. Generator: makepanda
  98. Root-Is-Purelib: false
  99. Tag: {0}-{1}-{2}
  100. """
  101. PROJECT_URLS = dict([line.split('=', 1) for line in GetMetadataValue('project_urls').strip().splitlines()])
  102. METADATA = {
  103. "license": GetMetadataValue('license'),
  104. "name": GetMetadataValue('name'),
  105. "metadata_version": "2.1",
  106. "generator": "makepanda",
  107. "summary": GetMetadataValue('description'),
  108. "extensions": {
  109. "python.details": {
  110. "project_urls": dict(PROJECT_URLS, Home=GetMetadataValue('url')),
  111. "document_names": {
  112. "license": "LICENSE.txt"
  113. },
  114. "contacts": [
  115. {
  116. "role": "author",
  117. "name": GetMetadataValue('author'),
  118. "email": GetMetadataValue('author_email'),
  119. }
  120. ]
  121. }
  122. },
  123. "classifiers": GetMetadataValue('classifiers'),
  124. }
  125. DESCRIPTION = """
  126. The Panda3D free 3D game engine
  127. ===============================
  128. Panda3D is a powerful 3D engine written in C++, with a complete set of Python
  129. bindings. Unlike other engines, these bindings are automatically generated,
  130. meaning that they are always up-to-date and complete: all functions of the
  131. engine can be controlled from Python. All major Panda3D applications have been
  132. written in Python, this is the intended way of using the engine.
  133. Panda3D now supports automatic shader generation, which now means you can use
  134. normal maps, gloss maps, glow maps, HDR, cartoon shading, and the like without
  135. having to write any shaders.
  136. Panda3D is a modern engine supporting advanced features such as shaders,
  137. stencil, and render-to-texture. Panda3D is unusual in that it emphasizes a
  138. short learning curve, rapid development, and extreme stability and robustness.
  139. Panda3D is free software that runs under Windows, Linux, or macOS.
  140. The Panda3D team is very concerned with making the engine accessible to new
  141. users. We provide a detailed manual, a complete API reference, and a large
  142. collection of sample programs to help you get started. We have active forums,
  143. with many helpful users, and the developers are regularly online to answer
  144. questions.
  145. """
  146. PANDA3D_TOOLS_INIT = """import os, sys
  147. import panda3d
  148. dir = os.path.dirname(panda3d.__file__)
  149. del panda3d
  150. if sys.platform in ('win32', 'cygwin'):
  151. path_var = 'PATH'
  152. if hasattr(os, 'add_dll_directory'):
  153. os.add_dll_directory(dir)
  154. elif sys.platform == 'darwin':
  155. path_var = 'DYLD_LIBRARY_PATH'
  156. else:
  157. path_var = 'LD_LIBRARY_PATH'
  158. if not os.environ.get(path_var):
  159. os.environ[path_var] = dir
  160. else:
  161. os.environ[path_var] = dir + os.pathsep + os.environ[path_var]
  162. del os, sys, path_var, dir
  163. def _exec_tool(tool):
  164. import os, sys
  165. from subprocess import Popen
  166. tools_dir = os.path.dirname(__file__)
  167. handle = Popen(sys.argv, executable=os.path.join(tools_dir, tool))
  168. try:
  169. try:
  170. return handle.wait()
  171. except KeyboardInterrupt:
  172. # Give the program a chance to handle the signal gracefully.
  173. return handle.wait()
  174. except:
  175. handle.kill()
  176. handle.wait()
  177. raise
  178. # Register all the executables in this directory as global functions.
  179. {0}
  180. """
  181. def parse_dependencies_windows(data):
  182. """ Parses the given output from dumpbin /dependents to determine the list
  183. of dll's this executable file depends on. """
  184. lines = data.splitlines()
  185. li = 0
  186. while li < len(lines):
  187. line = lines[li]
  188. li += 1
  189. if line.find(' has the following dependencies') != -1:
  190. break
  191. if li < len(lines):
  192. line = lines[li]
  193. if line.strip() == '':
  194. # Skip a blank line.
  195. li += 1
  196. # Now we're finding filenames, until the next blank line.
  197. filenames = []
  198. while li < len(lines):
  199. line = lines[li]
  200. li += 1
  201. line = line.strip()
  202. if line == '':
  203. # We're done.
  204. return filenames
  205. filenames.append(line)
  206. # At least we got some data.
  207. return filenames
  208. def parse_dependencies_unix(data):
  209. """ Parses the given output from otool -XL or ldd to determine the list of
  210. libraries this executable file depends on. """
  211. lines = data.splitlines()
  212. filenames = []
  213. for l in lines:
  214. l = l.strip()
  215. if l != "statically linked":
  216. filenames.append(l.split(' ', 1)[0])
  217. return filenames
  218. def scan_dependencies(pathname):
  219. """ Checks the named file for DLL dependencies, and adds any appropriate
  220. dependencies found into pluginDependencies and dependentFiles. """
  221. if sys.platform == "darwin":
  222. command = ['otool', '-XL', pathname]
  223. elif sys.platform in ("win32", "cygwin"):
  224. command = ['dumpbin', '/dependents', pathname]
  225. else:
  226. command = ['ldd', pathname]
  227. process = subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True)
  228. output, unused_err = process.communicate()
  229. retcode = process.poll()
  230. if retcode:
  231. raise subprocess.CalledProcessError(retcode, command[0], output=output)
  232. filenames = None
  233. if sys.platform in ("win32", "cygwin"):
  234. filenames = parse_dependencies_windows(output)
  235. else:
  236. filenames = parse_dependencies_unix(output)
  237. if filenames is None:
  238. sys.exit("Unable to determine dependencies from %s" % (pathname))
  239. if sys.platform == "darwin" and len(filenames) > 0:
  240. # Filter out the library ID.
  241. if os.path.basename(filenames[0]).split('.', 1)[0] == os.path.basename(pathname).split('.', 1)[0]:
  242. del filenames[0]
  243. return filenames
  244. class WheelFile(object):
  245. def __init__(self, name, version, platform):
  246. self.name = name
  247. self.version = version
  248. self.platform = platform
  249. wheel_name = "{0}-{1}-{2}-{3}-{4}.whl".format(
  250. name, version, PY_VERSION, ABI_TAG, platform)
  251. print("Writing %s" % (wheel_name))
  252. self.zip_file = zipfile.ZipFile(wheel_name, 'w', zipfile.ZIP_DEFLATED)
  253. self.records = []
  254. # Used to locate dependency libraries.
  255. self.lib_path = []
  256. self.dep_paths = {}
  257. self.ignore_deps = set()
  258. def consider_add_dependency(self, target_path, dep, search_path=None):
  259. """Considers adding a dependency library.
  260. Returns the target_path if it was added, which may be different from
  261. target_path if it was already added earlier, or None if it wasn't."""
  262. if dep in self.dep_paths:
  263. # Already considered this.
  264. return self.dep_paths[dep]
  265. self.dep_paths[dep] = None
  266. if dep in self.ignore_deps or dep.lower().startswith("python") or os.path.basename(dep).startswith("libpython"):
  267. # Don't include the Python library, or any other explicit ignore.
  268. if GetVerbose():
  269. print("Ignoring {0} (explicitly ignored)".format(dep))
  270. return
  271. if sys.platform == "darwin" and dep.endswith(".so"):
  272. # Temporary hack for 1.9, which had link deps on modules.
  273. return
  274. if sys.platform == "darwin" and dep.startswith("/System/"):
  275. return
  276. if dep.startswith('/'):
  277. source_path = dep
  278. else:
  279. source_path = None
  280. if search_path is None:
  281. search_path = self.lib_path
  282. for lib_dir in search_path:
  283. # Ignore static stuff.
  284. path = os.path.join(lib_dir, dep)
  285. if os.path.isfile(path):
  286. source_path = os.path.normpath(path)
  287. break
  288. if not source_path:
  289. # Couldn't find library in the panda3d lib dir.
  290. if GetVerbose():
  291. print("Ignoring {0} (not in search path)".format(dep))
  292. return
  293. self.dep_paths[dep] = target_path
  294. self.write_file(target_path, source_path)
  295. return target_path
  296. def write_file(self, target_path, source_path):
  297. """Adds the given file to the .whl file."""
  298. orig_source_path = source_path
  299. # If this is a .so file, we should set the rpath appropriately.
  300. temp = None
  301. basename, ext = os.path.splitext(source_path)
  302. if ext in ('.so', '.dylib') or '.so.' in os.path.basename(source_path) or \
  303. (not ext and is_executable(source_path)):
  304. # Scan Unix dependencies.
  305. if target_path not in IGNORE_UNIX_DEPS_OF:
  306. deps = scan_dependencies(source_path)
  307. else:
  308. deps = []
  309. suffix = ''
  310. if '.so' in os.path.basename(source_path):
  311. suffix = '.so'
  312. elif ext == '.dylib':
  313. suffix = '.dylib'
  314. temp = tempfile.NamedTemporaryFile(suffix=suffix, prefix='whl', delete=False)
  315. # On macOS, if no fat wheel was requested, extract the right architecture.
  316. if sys.platform == "darwin" and is_fat_file(source_path) \
  317. and not self.platform.endswith("_intel") \
  318. and "_fat" not in self.platform \
  319. and "_universal" not in self.platform:
  320. if self.platform.endswith("_x86_64"):
  321. arch = 'x86_64'
  322. else:
  323. arch = self.platform.split('_')[-1]
  324. subprocess.call(['lipo', source_path, '-extract', arch, '-output', temp.name])
  325. else:
  326. # Otherwise, just copy it over.
  327. temp.write(open(source_path, 'rb').read())
  328. temp.close()
  329. os.chmod(temp.name, os.stat(temp.name).st_mode | 0o711)
  330. # Now add dependencies. On macOS, fix @loader_path references.
  331. if sys.platform == "darwin":
  332. if sys.version_info >= (3, 3):
  333. devnull = subprocess.DEVNULL
  334. else:
  335. devnull = open(os.devnull, 'wb')
  336. is_unsigned = subprocess.call(['codesign', '-d', temp.name], stdout=devnull, stderr=devnull)
  337. if source_path.endswith('deploy-stubw'):
  338. deps_path = '@executable_path/../Frameworks'
  339. else:
  340. deps_path = '@loader_path'
  341. remove_signature = False
  342. loader_path = [os.path.dirname(source_path)]
  343. for dep in deps:
  344. if dep.endswith('/Python'):
  345. # If this references the Python framework, change it
  346. # to reference libpython instead.
  347. new_dep = deps_path + '/libpython{0}.{1}.dylib'.format(*sys.version_info)
  348. elif '@loader_path' in dep:
  349. dep_path = dep.replace('@loader_path', '.')
  350. target_dep = os.path.dirname(target_path) + '/' + os.path.basename(dep)
  351. target_dep = self.consider_add_dependency(target_dep, dep_path, loader_path)
  352. if not target_dep:
  353. # It won't be included, so no use adjusting the path.
  354. continue
  355. new_dep = os.path.join(deps_path, os.path.relpath(target_dep, os.path.dirname(target_path)))
  356. elif dep.startswith('/Library/Frameworks/Python.framework/') or \
  357. dep.startswith('/Library/Frameworks/PythonT.framework/'):
  358. # Add this dependency if it's in the Python directory.
  359. target_dep = os.path.dirname(target_path) + '/' + os.path.basename(dep)
  360. target_dep = self.consider_add_dependency(target_dep, dep, loader_path)
  361. if not target_dep:
  362. # It won't be included, so no use adjusting the path.
  363. continue
  364. new_dep = os.path.join(deps_path, os.path.relpath(target_dep, os.path.dirname(target_path)))
  365. else:
  366. if '/' in dep:
  367. if GetVerbose():
  368. print("Ignoring dependency %s" % (dep))
  369. continue
  370. subprocess.call(["install_name_tool", "-change", dep, new_dep, temp.name])
  371. remove_signature = True
  372. # Replace the codesign signature if we modified the library.
  373. if self.platform.endswith("_arm64") and (is_unsigned or remove_signature):
  374. subprocess.call(["codesign", "-f", "-s", "-", temp.name])
  375. elif remove_signature and not is_unsigned:
  376. if GetVerbose():
  377. print("Removing code signature from {0}".format(source_path))
  378. subprocess.call(["codesign", "--remove-signature", temp.name])
  379. if self.platform.endswith("_universal2"):
  380. subprocess.call(["codesign", "-a", "arm64", "-s", "-", temp.name])
  381. else:
  382. # On other unixes, we just add dependencies normally.
  383. for dep in deps:
  384. # Only include dependencies with relative path, for now.
  385. if '/' not in dep:
  386. target_dep = os.path.dirname(target_path) + '/' + dep
  387. self.consider_add_dependency(target_dep, dep)
  388. subprocess.call(["strip", "-s", temp.name])
  389. subprocess.call(["patchelf", "--force-rpath", "--set-rpath", "$ORIGIN", temp.name])
  390. source_path = temp.name
  391. ext = ext.lower()
  392. if ext in ('.dll', '.pyd', '.exe'):
  393. # Scan and add Win32 dependencies.
  394. for dep in scan_dependencies(source_path):
  395. target_dep = os.path.dirname(target_path) + '/' + dep
  396. self.consider_add_dependency(target_dep, dep)
  397. # Calculate the SHA-256 hash and size.
  398. sha = hashlib.sha256()
  399. fp = open(source_path, 'rb')
  400. size = 0
  401. data = fp.read(1024 * 1024)
  402. while data:
  403. size += len(data)
  404. sha.update(data)
  405. data = fp.read(1024 * 1024)
  406. fp.close()
  407. # Save it in PEP-0376 format for writing out later.
  408. digest = urlsafe_b64encode(sha.digest()).decode('ascii')
  409. digest = digest.rstrip('=')
  410. self.records.append("{0},sha256={1},{2}\n".format(target_path, digest, size))
  411. if GetVerbose():
  412. print("Adding {0} from {1}".format(target_path, orig_source_path))
  413. self.zip_file.write(source_path, target_path)
  414. #if temp:
  415. # os.unlink(temp.name)
  416. def write_file_data(self, target_path, source_data):
  417. """Adds the given file from a string."""
  418. sha = hashlib.sha256()
  419. sha.update(source_data.encode())
  420. digest = urlsafe_b64encode(sha.digest()).decode('ascii')
  421. digest = digest.rstrip('=')
  422. self.records.append("{0},sha256={1},{2}\n".format(target_path, digest, len(source_data)))
  423. if GetVerbose():
  424. print("Adding %s from data" % target_path)
  425. self.zip_file.writestr(target_path, source_data)
  426. def write_directory(self, target_dir, source_dir):
  427. """Adds the given directory recursively to the .whl file."""
  428. for root, dirs, files in os.walk(source_dir):
  429. for file in files:
  430. if os.path.splitext(file)[1] in EXCLUDE_EXT:
  431. continue
  432. source_path = os.path.join(root, file)
  433. target_path = os.path.join(target_dir, os.path.relpath(source_path, source_dir))
  434. target_path = target_path.replace('\\', '/')
  435. self.write_file(target_path, source_path)
  436. def close(self):
  437. # Write the RECORD file.
  438. record_file = "{0}-{1}.dist-info/RECORD".format(self.name, self.version)
  439. self.records.append(record_file + ",,\n")
  440. self.zip_file.writestr(record_file, "".join(self.records))
  441. self.zip_file.close()
  442. def makewheel(version, output_dir, platform=None):
  443. if sys.platform not in ("win32", "darwin") and not sys.platform.startswith("cygwin"):
  444. if not LocateBinary("patchelf"):
  445. raise Exception("patchelf is required when building a Linux wheel.")
  446. if platform is None:
  447. # Determine the platform from the build.
  448. platform_dat = os.path.join(output_dir, 'tmp', 'platform.dat')
  449. if os.path.isfile(platform_dat):
  450. platform = open(platform_dat, 'r').read().strip()
  451. else:
  452. print("Could not find platform.dat in build directory")
  453. platform = get_platform()
  454. if platform.startswith("linux-") and os.path.isdir("/opt/python"):
  455. # Is this manylinux?
  456. if os.path.isfile("/lib/libc-2.5.so") or os.path.isfile("/lib64/libc-2.5.so"):
  457. platform = platform.replace("linux", "manylinux1")
  458. elif os.path.isfile("/lib/libc-2.12.so") or os.path.isfile("/lib64/libc-2.12.so"):
  459. platform = platform.replace("linux", "manylinux2010")
  460. elif os.path.isfile("/lib/libc-2.17.so") or os.path.isfile("/lib64/libc-2.17.so"):
  461. platform = platform.replace("linux", "manylinux2014")
  462. elif os.path.isfile("/lib/i386-linux-gnu/libc-2.24.so") or os.path.isfile("/lib/x86_64-linux-gnu/libc-2.24.so"):
  463. platform = platform.replace("linux", "manylinux_2_24")
  464. elif os.path.isfile("/lib64/libc-2.28.so") and os.path.isfile('/etc/almalinux-release'):
  465. platform = platform.replace("linux", "manylinux_2_28")
  466. platform = platform.replace('-', '_').replace('.', '_')
  467. # Global filepaths
  468. panda3d_dir = join(output_dir, "panda3d")
  469. pandac_dir = join(output_dir, "pandac")
  470. direct_dir = join(output_dir, "direct")
  471. models_dir = join(output_dir, "models")
  472. etc_dir = join(output_dir, "etc")
  473. bin_dir = join(output_dir, "bin")
  474. if sys.platform == "win32":
  475. libs_dir = join(output_dir, "bin")
  476. else:
  477. libs_dir = join(output_dir, "lib")
  478. ext_mod_dir = get_python_ext_module_dir()
  479. license_src = "LICENSE"
  480. readme_src = "README.md"
  481. # Update relevant METADATA entries
  482. METADATA['version'] = version
  483. # Build out the metadata
  484. details = METADATA["extensions"]["python.details"]
  485. homepage = details["project_urls"]["Home"]
  486. author = details["contacts"][0]["name"]
  487. email = details["contacts"][0]["email"]
  488. metadata = ''.join([
  489. "Metadata-Version: {metadata_version}\n" \
  490. "Name: {name}\n" \
  491. "Version: {version}\n" \
  492. "Summary: {summary}\n" \
  493. "License: {license}\n".format(**METADATA),
  494. "Home-page: {0}\n".format(homepage),
  495. ] + ["Project-URL: {0}, {1}\n".format(*url) for url in PROJECT_URLS.items()] + [
  496. "Author: {0}\n".format(author),
  497. "Author-email: {0}\n".format(email),
  498. "Platform: {0}\n".format(platform),
  499. ] + ["Classifier: {0}\n".format(c) for c in METADATA['classifiers']])
  500. metadata += '\n' + DESCRIPTION.strip() + '\n'
  501. # Zip it up and name it the right thing
  502. whl = WheelFile('panda3d', version, platform)
  503. whl.lib_path = [libs_dir]
  504. if sys.platform == "win32":
  505. whl.lib_path.append(ext_mod_dir)
  506. if platform.startswith("manylinux"):
  507. # On manylinux1, we pick up all libraries except for the ones specified
  508. # by the manylinux1 ABI.
  509. whl.lib_path.append("/usr/local/lib")
  510. if platform.endswith("_x86_64"):
  511. whl.lib_path += ["/lib64", "/usr/lib64"]
  512. else:
  513. whl.lib_path += ["/lib", "/usr/lib"]
  514. whl.ignore_deps.update(MANYLINUX_LIBS)
  515. # Add libpython for deployment.
  516. suffix = ''
  517. gil_disabled = get_config_var("Py_GIL_DISABLED")
  518. if gil_disabled and int(gil_disabled):
  519. suffix = 't'
  520. if sys.platform in ('win32', 'cygwin'):
  521. pylib_name = 'python{0}{1}{2}.dll'.format(sys.version_info[0], sys.version_info[1], suffix)
  522. pylib_path = os.path.join(get_config_var('BINDIR'), pylib_name)
  523. elif sys.platform == 'darwin':
  524. pylib_name = 'libpython{0}.{1}{2}.dylib'.format(sys.version_info[0], sys.version_info[1], suffix)
  525. pylib_path = os.path.join(get_config_var('LIBDIR'), pylib_name)
  526. else:
  527. pylib_name = get_config_var('LDLIBRARY')
  528. pylib_arch = get_config_var('MULTIARCH')
  529. libdir = get_config_var('LIBDIR')
  530. if pylib_arch and os.path.exists(os.path.join(libdir, pylib_arch, pylib_name)):
  531. pylib_path = os.path.join(libdir, pylib_arch, pylib_name)
  532. else:
  533. pylib_path = os.path.join(libdir, pylib_name)
  534. # If Python was linked statically, we don't need to include this.
  535. if not pylib_name.endswith('.a'):
  536. whl.write_file('deploy_libs/' + pylib_name, pylib_path)
  537. # Add the trees with Python modules.
  538. whl.write_directory('direct', direct_dir)
  539. # Write the panda3d tree. We use a custom empty __init__ since the
  540. # default one adds the bin directory to the PATH, which we don't have.
  541. whl.write_file_data('panda3d/__init__.py', """"Python bindings for the Panda3D libraries"
  542. __version__ = '{0}'
  543. """.format(version))
  544. # Copy the extension modules from the panda3d directory.
  545. ext_suffix = GetExtensionSuffix()
  546. for file in os.listdir(panda3d_dir):
  547. if file == '__init__.py':
  548. pass
  549. elif file.endswith('.py') or (file.endswith(ext_suffix) and '.' not in file[:-len(ext_suffix)]):
  550. source_path = os.path.join(panda3d_dir, file)
  551. if file.endswith('.pyd') and platform.startswith('cygwin'):
  552. # Rename it to .dll for cygwin Python to be able to load it.
  553. target_path = 'panda3d/' + os.path.splitext(file)[0] + '.dll'
  554. else:
  555. target_path = 'panda3d/' + file
  556. whl.write_file(target_path, source_path)
  557. # And copy the extension modules from the Python installation into the
  558. # deploy_libs directory, for use by deploy-ng.
  559. ext_suffix = '.pyd' if sys.platform in ('win32', 'cygwin') else '.so'
  560. for file in os.listdir(ext_mod_dir):
  561. if file.endswith(ext_suffix):
  562. if file.startswith('_tkinter.') and sys.platform not in ('win32', 'cygwin'):
  563. # Tkinter is supplied in a separate wheel.
  564. continue
  565. source_path = os.path.join(ext_mod_dir, file)
  566. if file.endswith('.pyd') and platform.startswith('cygwin'):
  567. # Rename it to .dll for cygwin Python to be able to load it.
  568. target_path = 'deploy_libs/' + os.path.splitext(file)[0] + '.dll'
  569. else:
  570. target_path = 'deploy_libs/' + file
  571. whl.write_file(target_path, source_path)
  572. # Include the special sysconfigdata module.
  573. if os.name == 'posix':
  574. import sysconfig
  575. if hasattr(sysconfig, '_get_sysconfigdata_name'):
  576. modname = sysconfig._get_sysconfigdata_name() + '.py'
  577. else:
  578. modname = '_sysconfigdata.py'
  579. for entry in sys.path:
  580. source_path = os.path.join(entry, modname)
  581. if os.path.isfile(source_path):
  582. whl.write_file('deploy_libs/' + modname, source_path)
  583. break
  584. # Add plug-ins.
  585. for lib in PLUGIN_LIBS:
  586. plugin_name = 'lib' + lib
  587. if sys.platform in ('win32', 'cygwin'):
  588. plugin_name += '.dll'
  589. elif sys.platform == 'darwin':
  590. plugin_name += '.dylib'
  591. else:
  592. plugin_name += '.so'
  593. plugin_path = os.path.join(libs_dir, plugin_name)
  594. if os.path.isfile(plugin_path):
  595. whl.write_file('panda3d/' + plugin_name, plugin_path)
  596. # Add the .data directory, containing additional files.
  597. data_dir = 'panda3d-{0}.data'.format(version)
  598. #whl.write_directory(data_dir + '/data/etc', etc_dir)
  599. #whl.write_directory(data_dir + '/data/models', models_dir)
  600. # Actually, let's not. That seems to install the files to the strangest
  601. # places in the user's filesystem. Let's instead put them in panda3d.
  602. whl.write_directory('panda3d/etc', etc_dir)
  603. whl.write_directory('panda3d/models', models_dir)
  604. # Add the pandac tree for backward compatibility.
  605. for file in os.listdir(pandac_dir):
  606. if file.endswith('.py'):
  607. whl.write_file('pandac/' + file, os.path.join(pandac_dir, file))
  608. # Let's also add the interrogate databases.
  609. input_dir = os.path.join(pandac_dir, 'input')
  610. if os.path.isdir(input_dir):
  611. for file in os.listdir(input_dir):
  612. if file.endswith('.in'):
  613. whl.write_file('pandac/input/' + file, os.path.join(input_dir, file))
  614. # Add a panda3d-tools directory containing the executables.
  615. entry_points = '[console_scripts]\n'
  616. entry_points += 'eggcacher = direct.directscripts.eggcacher:main\n'
  617. entry_points += 'pfreeze = direct.dist.pfreeze:main\n'
  618. tools_init = ''
  619. for file in os.listdir(bin_dir):
  620. basename = os.path.splitext(file)[0]
  621. if basename in ('eggcacher', 'packpanda'):
  622. continue
  623. source_path = os.path.join(bin_dir, file)
  624. if is_executable(source_path):
  625. # Put the .exe files inside the panda3d-tools directory.
  626. whl.write_file('panda3d_tools/' + file, source_path)
  627. if basename.endswith('_bin'):
  628. # These tools won't be invoked by the user directly.
  629. continue
  630. # Tell pip to create a wrapper script.
  631. funcname = basename.replace('-', '_')
  632. entry_points += '{0} = panda3d_tools:{1}\n'.format(basename, funcname)
  633. tools_init += '{0} = lambda: _exec_tool({1!r})\n'.format(funcname, file)
  634. entry_points += '[distutils.commands]\n'
  635. entry_points += 'build_apps = direct.dist.commands:build_apps\n'
  636. entry_points += 'bdist_apps = direct.dist.commands:bdist_apps\n'
  637. entry_points += '[setuptools.finalize_distribution_options]\n'
  638. entry_points += 'build_apps = direct.dist._dist_hooks:finalize_distribution_options\n'
  639. whl.write_file_data('panda3d_tools/__init__.py', PANDA3D_TOOLS_INIT.format(tools_init))
  640. # Add the dist-info directory last.
  641. info_dir = 'panda3d-{0}.dist-info'.format(version)
  642. whl.write_file_data(info_dir + '/entry_points.txt', entry_points)
  643. whl.write_file_data(info_dir + '/metadata.json', json.dumps(METADATA, indent=4, separators=(',', ': ')))
  644. whl.write_file_data(info_dir + '/METADATA', metadata)
  645. whl.write_file_data(info_dir + '/WHEEL', WHEEL_DATA.format(PY_VERSION, ABI_TAG, platform))
  646. whl.write_file(info_dir + '/LICENSE.txt', license_src)
  647. whl.write_file(info_dir + '/README.md', readme_src)
  648. whl.write_file_data(info_dir + '/top_level.txt', 'direct\npanda3d\npandac\npanda3d_tools\n')
  649. whl.close()
  650. if __name__ == "__main__":
  651. version = GetMetadataValue('version')
  652. parser = OptionParser()
  653. parser.add_option('', '--version', dest = 'version', help = 'Panda3D version number (default: %s)' % (version), default = version)
  654. parser.add_option('', '--outputdir', dest = 'outputdir', help = 'Makepanda\'s output directory (default: built)', default = 'built')
  655. parser.add_option('', '--verbose', dest = 'verbose', help = 'Enable verbose output', action = 'store_true', default = False)
  656. parser.add_option('', '--platform', dest = 'platform', help = 'Override platform tag', default = None)
  657. (options, args) = parser.parse_args()
  658. SetVerbose(options.verbose)
  659. makewheel(options.version, options.outputdir, options.platform)