makewheel.py 30 KB

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