makewheel.py 26 KB

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