1
0

relocate.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import glob
  2. import os
  3. import re
  4. import shutil
  5. import sys
  6. from ..utils.deps import EXCLUDELIST, PATCHELF, PREFIX, ensure_excludelist, \
  7. ensure_patchelf
  8. from ..utils.fs import make_tree, copy_file, copy_tree, remove_file, remove_tree
  9. from ..utils.log import debug, log
  10. from ..utils.system import ldd, system
  11. from ..utils.template import copy_template
  12. __all__ = ["patch_binary", "relocate_python"]
  13. def _copy_template(name, destination, **kwargs):
  14. path = os.path.join(PREFIX, 'data', name)
  15. copy_template(path, destination, **kwargs)
  16. _excluded_libs = None
  17. '''Appimage excluded libraries, i.e. assumed to be installed on the host
  18. '''
  19. def patch_binary(path, libdir, recursive=True):
  20. '''Patch the RPATH of a binary and and fetch its dependencies
  21. '''
  22. global _excluded_libs
  23. if _excluded_libs is None:
  24. ensure_excludelist()
  25. excluded = []
  26. with open(EXCLUDELIST) as f:
  27. for line in f:
  28. line = line.strip()
  29. if (not line) or line.startswith('#'):
  30. continue
  31. excluded.append(line.split(' ', 1)[0])
  32. _excluded_libs = excluded
  33. else:
  34. excluded = _excluded_libs
  35. ensure_patchelf()
  36. rpath = '\'' + system((PATCHELF, '--print-rpath', path)) + '\''
  37. relpath = os.path.relpath(libdir, os.path.dirname(path))
  38. relpath = '' if relpath == '.' else '/' + relpath
  39. expected = '\'$ORIGIN' + relpath + '\''
  40. if rpath != expected:
  41. system((PATCHELF, '--set-rpath', expected, path))
  42. deps = ldd(path)
  43. for dep in deps:
  44. name = os.path.basename(dep)
  45. if name in excluded:
  46. continue
  47. target = libdir + '/' + name
  48. if not os.path.exists(target):
  49. libname = os.path.basename(dep)
  50. copy_file(dep, target)
  51. if recursive:
  52. patch_binary(target, libdir, recursive=True)
  53. def relocate_python(python=None, appdir=None):
  54. '''Bundle a Python install inside an AppDir
  55. '''
  56. if python is not None:
  57. if not os.path.exists(python):
  58. raise ValueError('could not access ' + python)
  59. if appdir is None:
  60. appdir = 'AppDir'
  61. # Set some key variables & paths
  62. if python:
  63. FULLVERSION = system((python, '-c',
  64. '"import sys; print(\'{:}.{:}.{:}\'.format(*sys.version_info[:3]))"'))
  65. FULLVERSION = FULLVERSION.strip()
  66. else:
  67. FULLVERSION = '{:}.{:}.{:}'.format(*sys.version_info[:3])
  68. VERSION = '.'.join(FULLVERSION.split('.')[:2])
  69. PYTHON_X_Y = 'python' + VERSION
  70. APPDIR = os.path.abspath(appdir)
  71. APPDIR_BIN = APPDIR + '/usr/bin'
  72. APPDIR_LIB = APPDIR + '/usr/lib'
  73. APPDIR_SHARE = APPDIR + '/usr/share'
  74. if python:
  75. HOST_PREFIX = system((
  76. python, '-c', '"import sys; print(sys.prefix)"')).strip()
  77. else:
  78. HOST_PREFIX = sys.prefix
  79. HOST_BIN = HOST_PREFIX + '/bin'
  80. HOST_INC = HOST_PREFIX + '/include/' + PYTHON_X_Y
  81. if not os.path.exists(HOST_INC):
  82. HOST_INC += 'm'
  83. HOST_LIB = HOST_PREFIX + '/lib'
  84. HOST_PKG = HOST_LIB + '/' + PYTHON_X_Y
  85. PYTHON_PREFIX = APPDIR + '/opt/' + PYTHON_X_Y
  86. PYTHON_BIN = PYTHON_PREFIX + '/bin'
  87. PYTHON_INC = PYTHON_PREFIX + '/include/' + PYTHON_X_Y
  88. PYTHON_LIB = PYTHON_PREFIX + '/lib'
  89. PYTHON_PKG = PYTHON_LIB + '/' + PYTHON_X_Y
  90. # Copy the running Python's install
  91. log('CLONE', '%s from %s', PYTHON_X_Y, HOST_PREFIX)
  92. source = HOST_BIN + '/' + PYTHON_X_Y
  93. if not os.path.exists(source):
  94. raise ValueError('could not find {0:} executable'.format(PYTHON_X_Y))
  95. make_tree(PYTHON_BIN)
  96. target = PYTHON_BIN + '/' + PYTHON_X_Y
  97. copy_file(source, target, update=True)
  98. copy_tree(HOST_PKG, PYTHON_PKG)
  99. copy_tree(HOST_INC, PYTHON_INC)
  100. # Remove unrelevant files
  101. log('PRUNE', '%s packages', PYTHON_X_Y)
  102. remove_file(PYTHON_LIB + '/lib' + PYTHON_X_Y + '.a')
  103. remove_tree(PYTHON_PKG + '/test')
  104. remove_file(PYTHON_PKG + '/dist-packages')
  105. matches = glob.glob(PYTHON_PKG + '/config-*-linux-*')
  106. for path in matches:
  107. remove_tree(path)
  108. # Wrap the Python executable
  109. log('WRAP', '%s executable', PYTHON_X_Y)
  110. with open(PREFIX + '/data/python-wrapper.sh') as f:
  111. text = f.read()
  112. text = text.replace('{{PYTHON}}', PYTHON_X_Y)
  113. make_tree(APPDIR_BIN)
  114. target = APPDIR_BIN + '/' + PYTHON_X_Y
  115. with open(target, 'w') as f:
  116. f.write(text)
  117. shutil.copymode(PYTHON_BIN + '/' + PYTHON_X_Y, target)
  118. # Set or update symlinks to python
  119. pythons = glob.glob(APPDIR_BIN + '/python?.*')
  120. versions = [os.path.basename(python)[6:] for python in pythons]
  121. latest2, latest3 = '0.0', '0.0'
  122. for version in versions:
  123. if version.startswith('2') and version >= latest2:
  124. latest2 = version
  125. elif version.startswith('3') and version >= latest3:
  126. latest3 = version
  127. if latest2 == VERSION:
  128. remove_file(APPDIR_BIN + '/python2')
  129. os.symlink(PYTHON_X_Y, APPDIR_BIN + '/python2')
  130. if latest3 == '0.0':
  131. log('SYMLINK', 'python, python2 to ' + PYTHON_X_Y)
  132. remove_file(APPDIR_BIN + '/python')
  133. os.symlink('python2', APPDIR_BIN + '/python')
  134. else:
  135. log('SYMLINK', 'python2 to ' + PYTHON_X_Y)
  136. elif latest3 == VERSION:
  137. log('SYMLINK', 'python, python3 to ' + PYTHON_X_Y)
  138. remove_file(APPDIR_BIN + '/python3')
  139. os.symlink(PYTHON_X_Y, APPDIR_BIN + '/python3')
  140. remove_file(APPDIR_BIN + '/python')
  141. os.symlink('python3', APPDIR_BIN + '/python')
  142. # Set a hook in Python for cleaning the path detection
  143. log('HOOK', '%s site packages', PYTHON_X_Y)
  144. sitepkgs = PYTHON_PKG + '/site-packages'
  145. make_tree(sitepkgs)
  146. copy_file(PREFIX + '/data/sitecustomize.py', sitepkgs)
  147. # Set RPATHs and bundle external libraries
  148. log('LINK', '%s C-extensions', PYTHON_X_Y)
  149. make_tree(APPDIR_LIB)
  150. patch_binary(PYTHON_BIN + '/' + PYTHON_X_Y, APPDIR_LIB, recursive=False)
  151. for root, dirs, files in os.walk(PYTHON_PKG + '/lib-dynload'):
  152. for file_ in files:
  153. if not file_.endswith('.so'):
  154. continue
  155. patch_binary(os.path.join(root, file_), APPDIR_LIB, recursive=False)
  156. for file_ in glob.iglob(APPDIR_LIB + '/lib*.so*'):
  157. patch_binary(file_, APPDIR_LIB, recursive=True)
  158. # Copy shared data for TCl/Tk
  159. tkinter = glob.glob(PYTHON_PKG + '/lib-dynload/_tkinter*.so')
  160. if tkinter:
  161. tkinter = tkinter[0]
  162. for dep in ldd(tkinter):
  163. name = os.path.basename(dep)
  164. if name.startswith('libtk'):
  165. match = re.search('libtk([0-9]+[.][0-9]+)', name)
  166. tk_version = match.group(1)
  167. break
  168. else:
  169. raise RuntimeError('could not guess Tcl/Tk version')
  170. tcltkdir = APPDIR_SHARE + '/tcltk'
  171. if (not os.path.exists(tcltkdir + '/tcl' + tk_version)) or \
  172. (not os.path.exists(tcltkdir + '/tk' + tk_version)):
  173. hostdir = '/usr/share/tcltk'
  174. if os.path.exists(hostdir):
  175. make_tree(APPDIR_SHARE)
  176. copy_tree(hostdir, tcltkdir)
  177. else:
  178. make_tree(tcltkdir)
  179. tclpath = '/usr/share/tcl' + tk_version
  180. if not tclpath:
  181. raise ValueError('could not find ' + tclpath)
  182. copy_tree(tclpath, tcltkdir + '/tcl' + tk_version)
  183. tkpath = '/usr/share/tk' + tk_version
  184. if not tkpath:
  185. raise ValueError('could not find ' + tkpath)
  186. copy_tree(tkpath, tcltkdir + '/tk' + tk_version)
  187. # Bundle the entry point
  188. apprun = APPDIR + '/AppRun'
  189. if not os.path.exists(apprun):
  190. log('INSTALL', 'AppRun')
  191. entrypoint = '"${{APPDIR}}/usr/bin/python{:}" "$@"'.format(VERSION)
  192. _copy_template('apprun.sh', apprun, entrypoint=entrypoint)
  193. # Bundle the desktop file
  194. desktop_name = 'python{:}.desktop'.format(FULLVERSION)
  195. desktop = os.path.join(APPDIR, desktop_name)
  196. if not os.path.exists(desktop):
  197. log('INSTALL', desktop_name)
  198. apps = 'usr/share/applications'
  199. appfile = '{:}/{:}/python{:}.desktop'.format(APPDIR, apps, FULLVERSION)
  200. if not os.path.exists(appfile):
  201. make_tree(os.path.join(APPDIR, apps))
  202. _copy_template('python.desktop', appfile, version=VERSION,
  203. fullversion=FULLVERSION)
  204. os.symlink(os.path.join(apps, desktop_name), desktop)
  205. # Bundle icons
  206. icons = 'usr/share/icons/hicolor/256x256/apps'
  207. icon = os.path.join(APPDIR, 'python.png')
  208. if not os.path.exists(icon):
  209. log('INSTALL', 'python.png')
  210. make_tree(os.path.join(APPDIR, icons))
  211. copy_file(PREFIX + '/data/python.png',
  212. os.path.join(APPDIR, icons, 'python.png'))
  213. os.symlink(os.path.join(icons, 'python.png'), icon)
  214. diricon = os.path.join(APPDIR, '.DirIcon')
  215. if not os.path.exists(diricon):
  216. os.symlink('python.png', diricon)
  217. # Bundle metadata
  218. meta_name = 'python{:}.appdata.xml'.format(FULLVERSION)
  219. meta_dir = os.path.join(APPDIR, 'usr/share/metainfo')
  220. meta_file = os.path.join(meta_dir, meta_name)
  221. if not os.path.exists(meta_file):
  222. log('INSTALL', meta_name)
  223. make_tree(meta_dir)
  224. _copy_template('python.appdata.xml', meta_file, version=VERSION,
  225. fullversion=FULLVERSION)