makewheel.py 35 KB

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