makewheel.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. default_platform = get_platform()
  23. if default_platform.startswith("linux-"):
  24. # Is this manylinux1?
  25. if os.path.isfile("/lib/libc-2.5.so") and os.path.isdir("/opt/python"):
  26. default_platform = default_platform.replace("linux", "manylinux1")
  27. def get_abi_tag():
  28. if sys.version_info >= (3, 0):
  29. soabi = get_config_var('SOABI')
  30. if soabi and soabi.startswith('cpython-'):
  31. return 'cp' + soabi.split('-')[1]
  32. elif soabi:
  33. return soabi.replace('.', '_').replace('-', '_')
  34. soabi = 'cp%d%d' % (sys.version_info[:2])
  35. debug_flag = get_config_var('Py_DEBUG')
  36. if (debug_flag is None and hasattr(sys, 'gettotalrefcount')) or debug_flag:
  37. soabi += 'd'
  38. malloc_flag = get_config_var('WITH_PYMALLOC')
  39. if malloc_flag is None or malloc_flag:
  40. soabi += 'm'
  41. if sys.version_info < (3, 3):
  42. usize = get_config_var('Py_UNICODE_SIZE')
  43. if (usize is None and sys.maxunicode == 0x10ffff) or usize == 4:
  44. soabi += 'u'
  45. return soabi
  46. def is_exe_file(path):
  47. return os.path.isfile(path) and path.lower().endswith('.exe')
  48. def is_elf_file(path):
  49. base = os.path.basename(path)
  50. return os.path.isfile(path) and '.' not in base and \
  51. open(path, 'rb').read(4) == b'\x7FELF'
  52. def is_mach_o_file(path):
  53. base = os.path.basename(path)
  54. return os.path.isfile(path) and '.' not in base and \
  55. open(path, 'rb').read(4) in (b'\xCA\xFE\xBA\xBE', b'\xBE\xBA\xFE\bCA',
  56. b'\xFE\xED\xFA\xCE', b'\xCE\xFA\xED\xFE',
  57. b'\xFE\xED\xFA\xCF', b'\xCF\xFA\xED\xFE')
  58. def is_fat_file(path):
  59. return os.path.isfile(path) and \
  60. open(path, 'rb').read(4) in (b'\xCA\xFE\xBA\xBE', b'\xBE\xBA\xFE\bCA')
  61. if sys.platform in ('win32', 'cygwin'):
  62. is_executable = is_exe_file
  63. elif sys.platform == 'darwin':
  64. is_executable = is_mach_o_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. WHEEL_DATA = """Wheel-Version: 1.0
  74. Generator: makepanda
  75. Root-Is-Purelib: false
  76. Tag: {0}-{1}-{2}
  77. """
  78. METADATA = {
  79. "license": GetMetadataValue('license'),
  80. "name": GetMetadataValue('name'),
  81. "metadata_version": "2.0",
  82. "generator": "makepanda",
  83. "summary": GetMetadataValue('description'),
  84. "extensions": {
  85. "python.details": {
  86. "project_urls": {
  87. "Home": GetMetadataValue('url'),
  88. },
  89. "document_names": {
  90. "license": "LICENSE.txt"
  91. },
  92. "contacts": [
  93. {
  94. "role": "author",
  95. "name": GetMetadataValue('author'),
  96. "email": GetMetadataValue('author_email'),
  97. }
  98. ]
  99. }
  100. },
  101. "classifiers": GetMetadataValue('classifiers'),
  102. }
  103. PANDA3D_TOOLS_INIT = """import os, sys
  104. import panda3d
  105. if sys.platform in ('win32', 'cygwin'):
  106. path_var = 'PATH'
  107. elif sys.platform == 'darwin':
  108. path_var = 'DYLD_LIBRARY_PATH'
  109. else:
  110. path_var = 'LD_LIBRARY_PATH'
  111. dir = os.path.dirname(panda3d.__file__)
  112. del panda3d
  113. if not os.environ.get(path_var):
  114. os.environ[path_var] = dir
  115. else:
  116. os.environ[path_var] = dir + os.pathsep + os.environ[path_var]
  117. del os, sys, path_var, dir
  118. def _exec_tool(tool):
  119. import os, sys
  120. from subprocess import Popen
  121. tools_dir = os.path.dirname(__file__)
  122. handle = Popen(sys.argv, executable=os.path.join(tools_dir, tool))
  123. try:
  124. try:
  125. return handle.wait()
  126. except KeyboardInterrupt:
  127. # Give the program a chance to handle the signal gracefully.
  128. return handle.wait()
  129. except:
  130. handle.kill()
  131. handle.wait()
  132. raise
  133. # Register all the executables in this directory as global functions.
  134. {0}
  135. """
  136. def parse_dependencies_windows(data):
  137. """ Parses the given output from dumpbin /dependents to determine the list
  138. of dll's this executable file depends on. """
  139. lines = data.splitlines()
  140. li = 0
  141. while li < len(lines):
  142. line = lines[li]
  143. li += 1
  144. if line.find(' has the following dependencies') != -1:
  145. break
  146. if li < len(lines):
  147. line = lines[li]
  148. if line.strip() == '':
  149. # Skip a blank line.
  150. li += 1
  151. # Now we're finding filenames, until the next blank line.
  152. filenames = []
  153. while li < len(lines):
  154. line = lines[li]
  155. li += 1
  156. line = line.strip()
  157. if line == '':
  158. # We're done.
  159. return filenames
  160. filenames.append(line)
  161. # At least we got some data.
  162. return filenames
  163. def parse_dependencies_unix(data):
  164. """ Parses the given output from otool -XL or ldd to determine the list of
  165. libraries this executable file depends on. """
  166. lines = data.splitlines()
  167. filenames = []
  168. for l in lines:
  169. l = l.strip()
  170. if l != "statically linked":
  171. filenames.append(l.split(' ', 1)[0])
  172. return filenames
  173. def scan_dependencies(pathname):
  174. """ Checks the named file for DLL dependencies, and adds any appropriate
  175. dependencies found into pluginDependencies and dependentFiles. """
  176. if sys.platform == "darwin":
  177. command = ['otool', '-XL', pathname]
  178. elif sys.platform in ("win32", "cygwin"):
  179. command = ['dumpbin', '/dependents', pathname]
  180. else:
  181. command = ['ldd', pathname]
  182. process = subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True)
  183. output, unused_err = process.communicate()
  184. retcode = process.poll()
  185. if retcode:
  186. raise subprocess.CalledProcessError(retcode, command[0], output=output)
  187. filenames = None
  188. if sys.platform in ("win32", "cygwin"):
  189. filenames = parse_dependencies_windows(output)
  190. else:
  191. filenames = parse_dependencies_unix(output)
  192. if filenames is None:
  193. sys.exit("Unable to determine dependencies from %s" % (pathname))
  194. if sys.platform == "darwin" and len(filenames) > 0:
  195. # Filter out the library ID.
  196. if os.path.basename(filenames[0]).split('.', 1)[0] == os.path.basename(pathname).split('.', 1)[0]:
  197. del filenames[0]
  198. return filenames
  199. class WheelFile(object):
  200. def __init__(self, name, version, platform):
  201. self.name = name
  202. self.version = version
  203. self.platform = platform
  204. wheel_name = "{0}-{1}-{2}-{3}-{4}.whl".format(
  205. name, version, PY_VERSION, ABI_TAG, platform)
  206. print("Writing %s" % (wheel_name))
  207. self.zip_file = zipfile.ZipFile(wheel_name, 'w', zipfile.ZIP_DEFLATED)
  208. self.records = []
  209. # Used to locate dependency libraries.
  210. self.lib_path = []
  211. self.dep_paths = {}
  212. def consider_add_dependency(self, target_path, dep, search_path=None):
  213. """Considers adding a dependency library.
  214. Returns the target_path if it was added, which may be different from
  215. target_path if it was already added earlier, or None if it wasn't."""
  216. if dep in self.dep_paths:
  217. # Already considered this.
  218. return self.dep_paths[dep]
  219. self.dep_paths[dep] = None
  220. if dep.lower().startswith("python") or os.path.basename(dep).startswith("libpython"):
  221. # Don't include the Python library.
  222. return
  223. if sys.platform == "darwin" and dep.endswith(".so"):
  224. # Temporary hack for 1.9, which had link deps on modules.
  225. return
  226. source_path = None
  227. if search_path is None:
  228. search_path = self.lib_path
  229. for lib_dir in search_path:
  230. # Ignore static stuff.
  231. path = os.path.join(lib_dir, dep)
  232. if os.path.isfile(path):
  233. source_path = os.path.normpath(path)
  234. break
  235. if not source_path:
  236. # Couldn't find library in the panda3d lib dir.
  237. #print("Ignoring %s" % (dep))
  238. return
  239. self.dep_paths[dep] = target_path
  240. self.write_file(target_path, source_path)
  241. return target_path
  242. def write_file(self, target_path, source_path):
  243. """Adds the given file to the .whl file."""
  244. # If this is a .so file, we should set the rpath appropriately.
  245. temp = None
  246. ext = os.path.splitext(source_path)[1]
  247. if ext in ('.so', '.dylib') or '.so.' in os.path.basename(source_path) or \
  248. (not ext and is_executable(source_path)):
  249. # Scan and add Unix dependencies.
  250. deps = scan_dependencies(source_path)
  251. for dep in deps:
  252. # Only include dependencies with relative path. Otherwise we
  253. # end up overwriting system files like /lib/ld-linux.so.2!
  254. # Yes, it happened to me.
  255. if '/' not in dep:
  256. target_dep = os.path.dirname(target_path) + '/' + dep
  257. self.consider_add_dependency(target_dep, dep)
  258. suffix = ''
  259. if '.so' in os.path.basename(source_path):
  260. suffix = '.so'
  261. elif ext == '.dylib':
  262. suffix = '.dylib'
  263. temp = tempfile.NamedTemporaryFile(suffix=suffix, prefix='whl', delete=False)
  264. # On macOS, if no fat wheel was requested, extract the right architecture.
  265. if sys.platform == "darwin" and is_fat_file(source_path) and not self.platform.endswith("_intel"):
  266. if self.platform.endswith("_x86_64"):
  267. arch = 'x86_64'
  268. else:
  269. arch = self.platform.split('_')[-1]
  270. subprocess.call(['lipo', source_path, '-extract', arch, '-output', temp.name])
  271. else:
  272. # Otherwise, just copy it over.
  273. temp.write(open(source_path, 'rb').read())
  274. os.fchmod(temp.fileno(), os.fstat(temp.fileno()).st_mode | 0o111)
  275. temp.close()
  276. # Fix things like @loader_path/../lib references
  277. if sys.platform == "darwin":
  278. loader_path = [os.path.dirname(source_path)]
  279. for dep in deps:
  280. if '@loader_path' not in dep:
  281. continue
  282. dep_path = dep.replace('@loader_path', '.')
  283. target_dep = os.path.dirname(target_path) + '/' + os.path.basename(dep)
  284. target_dep = self.consider_add_dependency(target_dep, dep_path, loader_path)
  285. if not target_dep:
  286. # It won't be included, so no use adjusting the path.
  287. continue
  288. new_dep = os.path.join('@loader_path', os.path.relpath(target_dep, os.path.dirname(target_path)))
  289. subprocess.call(["install_name_tool", "-change", dep, new_dep, temp.name])
  290. else:
  291. subprocess.call(["strip", "-s", temp.name])
  292. subprocess.call(["patchelf", "--set-rpath", "$ORIGIN", temp.name])
  293. source_path = temp.name
  294. ext = ext.lower()
  295. if ext in ('.dll', '.pyd', '.exe'):
  296. # Scan and add Win32 dependencies.
  297. for dep in scan_dependencies(source_path):
  298. target_dep = os.path.dirname(target_path) + '/' + dep
  299. self.consider_add_dependency(target_dep, dep)
  300. # Calculate the SHA-256 hash and size.
  301. sha = hashlib.sha256()
  302. fp = open(source_path, 'rb')
  303. size = 0
  304. data = fp.read(1024 * 1024)
  305. while data:
  306. size += len(data)
  307. sha.update(data)
  308. data = fp.read(1024 * 1024)
  309. fp.close()
  310. # Save it in PEP-0376 format for writing out later.
  311. digest = urlsafe_b64encode(sha.digest()).decode('ascii')
  312. digest = digest.rstrip('=')
  313. self.records.append("{0},sha256={1},{2}\n".format(target_path, digest, size))
  314. if GetVerbose():
  315. print("Adding %s from %s" % (target_path, source_path))
  316. self.zip_file.write(source_path, target_path)
  317. #if temp:
  318. # os.unlink(temp.name)
  319. def write_file_data(self, target_path, source_data):
  320. """Adds the given file from a string."""
  321. sha = hashlib.sha256()
  322. sha.update(source_data.encode())
  323. digest = urlsafe_b64encode(sha.digest()).decode('ascii')
  324. digest = digest.rstrip('=')
  325. self.records.append("{0},sha256={1},{2}\n".format(target_path, digest, len(source_data)))
  326. if GetVerbose():
  327. print("Adding %s from data" % target_path)
  328. self.zip_file.writestr(target_path, source_data)
  329. def write_directory(self, target_dir, source_dir):
  330. """Adds the given directory recursively to the .whl file."""
  331. for root, dirs, files in os.walk(source_dir):
  332. for file in files:
  333. if os.path.splitext(file)[1] in EXCLUDE_EXT:
  334. continue
  335. source_path = os.path.join(root, file)
  336. target_path = os.path.join(target_dir, os.path.relpath(source_path, source_dir))
  337. target_path = target_path.replace('\\', '/')
  338. self.write_file(target_path, source_path)
  339. def close(self):
  340. # Write the RECORD file.
  341. record_file = "{0}-{1}.dist-info/RECORD".format(self.name, self.version)
  342. self.records.append(record_file + ",,\n")
  343. self.zip_file.writestr(record_file, "".join(self.records))
  344. self.zip_file.close()
  345. def makewheel(version, output_dir, platform=default_platform):
  346. if sys.platform not in ("win32", "darwin") and not sys.platform.startswith("cygwin"):
  347. if not LocateBinary("patchelf"):
  348. raise Exception("patchelf is required when building a Linux wheel.")
  349. platform = platform.replace('-', '_').replace('.', '_')
  350. # Global filepaths
  351. panda3d_dir = join(output_dir, "panda3d")
  352. pandac_dir = join(output_dir, "pandac")
  353. direct_dir = join(output_dir, "direct")
  354. models_dir = join(output_dir, "models")
  355. etc_dir = join(output_dir, "etc")
  356. bin_dir = join(output_dir, "bin")
  357. if sys.platform == "win32":
  358. libs_dir = join(output_dir, "bin")
  359. else:
  360. libs_dir = join(output_dir, "lib")
  361. license_src = "LICENSE"
  362. readme_src = "README.md"
  363. # Update relevant METADATA entries
  364. METADATA['version'] = version
  365. version_classifiers = [
  366. "Programming Language :: Python :: {0}".format(*sys.version_info),
  367. "Programming Language :: Python :: {0}.{1}".format(*sys.version_info),
  368. ]
  369. METADATA['classifiers'].extend(version_classifiers)
  370. # Build out the metadata
  371. details = METADATA["extensions"]["python.details"]
  372. homepage = details["project_urls"]["Home"]
  373. author = details["contacts"][0]["name"]
  374. email = details["contacts"][0]["email"]
  375. metadata = ''.join([
  376. "Metadata-Version: {metadata_version}\n" \
  377. "Name: {name}\n" \
  378. "Version: {version}\n" \
  379. "Summary: {summary}\n" \
  380. "License: {license}\n".format(**METADATA),
  381. "Home-page: {0}\n".format(homepage),
  382. "Author: {0}\n".format(author),
  383. "Author-email: {0}\n".format(email),
  384. "Platform: {0}\n".format(platform),
  385. ] + ["Classifier: {0}\n".format(c) for c in METADATA['classifiers']])
  386. # Zip it up and name it the right thing
  387. whl = WheelFile('panda3d', version, platform)
  388. whl.lib_path = [libs_dir]
  389. # Add the trees with Python modules.
  390. whl.write_directory('direct', direct_dir)
  391. # Write the panda3d tree. We use a custom empty __init__ since the
  392. # default one adds the bin directory to the PATH, which we don't have.
  393. whl.write_file_data('panda3d/__init__.py', '')
  394. ext_suffix = GetExtensionSuffix()
  395. for file in os.listdir(panda3d_dir):
  396. if file == '__init__.py':
  397. pass
  398. elif file.endswith(ext_suffix) or file.endswith('.py'):
  399. source_path = os.path.join(panda3d_dir, file)
  400. if file.endswith('.pyd') and platform.startswith('cygwin'):
  401. # Rename it to .dll for cygwin Python to be able to load it.
  402. target_path = 'panda3d/' + os.path.splitext(file)[0] + '.dll'
  403. else:
  404. target_path = 'panda3d/' + file
  405. whl.write_file(target_path, source_path)
  406. # Add plug-ins.
  407. for lib in PLUGIN_LIBS:
  408. plugin_name = 'lib' + lib
  409. if sys.platform in ('win32', 'cygwin'):
  410. plugin_name += '.dll'
  411. elif sys.platform == 'darwin':
  412. plugin_name += '.dylib'
  413. else:
  414. plugin_name += '.so'
  415. plugin_path = os.path.join(libs_dir, plugin_name)
  416. if os.path.isfile(plugin_path):
  417. whl.write_file('panda3d/' + plugin_name, plugin_path)
  418. # Add the .data directory, containing additional files.
  419. data_dir = 'panda3d-{0}.data'.format(version)
  420. #whl.write_directory(data_dir + '/data/etc', etc_dir)
  421. #whl.write_directory(data_dir + '/data/models', models_dir)
  422. # Actually, let's not. That seems to install the files to the strangest
  423. # places in the user's filesystem. Let's instead put them in panda3d.
  424. whl.write_directory('panda3d/etc', etc_dir)
  425. whl.write_directory('panda3d/models', models_dir)
  426. # Add the pandac tree for backward compatibility.
  427. for file in os.listdir(pandac_dir):
  428. if file.endswith('.py'):
  429. whl.write_file('pandac/' + file, os.path.join(pandac_dir, file))
  430. # Add a panda3d-tools directory containing the executables.
  431. entry_points = '[console_scripts]\n'
  432. entry_points += 'eggcacher = direct.directscripts.eggcacher:main\n'
  433. entry_points += 'pfreeze = direct.showutil.pfreeze:main\n'
  434. tools_init = ''
  435. for file in os.listdir(bin_dir):
  436. basename = os.path.splitext(file)[0]
  437. if basename in ('eggcacher', 'packpanda'):
  438. continue
  439. source_path = os.path.join(bin_dir, file)
  440. if is_executable(source_path):
  441. # Put the .exe files inside the panda3d-tools directory.
  442. whl.write_file('panda3d_tools/' + file, source_path)
  443. # Tell pip to create a wrapper script.
  444. funcname = basename.replace('-', '_')
  445. entry_points += '{0} = panda3d_tools:{1}\n'.format(basename, funcname)
  446. tools_init += '{0} = lambda: _exec_tool({1!r})\n'.format(funcname, file)
  447. whl.write_file_data('panda3d_tools/__init__.py', PANDA3D_TOOLS_INIT.format(tools_init))
  448. # Add the dist-info directory last.
  449. info_dir = 'panda3d-{0}.dist-info'.format(version)
  450. whl.write_file_data(info_dir + '/entry_points.txt', entry_points)
  451. whl.write_file_data(info_dir + '/metadata.json', json.dumps(METADATA, indent=4, separators=(',', ': ')))
  452. whl.write_file_data(info_dir + '/METADATA', metadata)
  453. whl.write_file_data(info_dir + '/WHEEL', WHEEL_DATA.format(PY_VERSION, ABI_TAG, platform))
  454. whl.write_file(info_dir + '/LICENSE.txt', license_src)
  455. whl.write_file(info_dir + '/README.md', readme_src)
  456. whl.write_file_data(info_dir + '/top_level.txt', 'direct\npanda3d\npandac\npanda3d_tools\n')
  457. whl.close()
  458. if __name__ == "__main__":
  459. version = ParsePandaVersion("dtool/PandaVersion.pp")
  460. parser = OptionParser()
  461. parser.add_option('', '--version', dest = 'version', help = 'Panda3D version number (default: %s)' % (version), default = version)
  462. parser.add_option('', '--outputdir', dest = 'outputdir', help = 'Makepanda\'s output directory (default: built)', default = 'built')
  463. parser.add_option('', '--verbose', dest = 'verbose', help = 'Enable verbose output', action = 'store_true', default = False)
  464. parser.add_option('', '--platform', dest = 'platform', help = 'Override platform tag (default: %s)' % (default_platform), default = get_platform())
  465. (options, args) = parser.parse_args()
  466. SetVerbose(options.verbose)
  467. makewheel(options.version, options.outputdir, options.platform)