makewheel.py 28 KB

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