makewheel.py 30 KB

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