relocate.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. PIP_X_Y = 'pip' + VERSION
  71. PIP_X = 'pip' + VERSION[0]
  72. APPDIR = os.path.abspath(appdir)
  73. APPDIR_BIN = APPDIR + '/usr/bin'
  74. APPDIR_LIB = APPDIR + '/usr/lib'
  75. APPDIR_SHARE = APPDIR + '/usr/share'
  76. if python:
  77. HOST_PREFIX = system((
  78. python, '-c', '"import sys; print(sys.prefix)"')).strip()
  79. else:
  80. HOST_PREFIX = sys.prefix
  81. HOST_BIN = HOST_PREFIX + '/bin'
  82. HOST_INC = HOST_PREFIX + '/include/' + PYTHON_X_Y
  83. if not os.path.exists(HOST_INC):
  84. HOST_INC += 'm'
  85. HOST_LIB = HOST_PREFIX + '/lib'
  86. HOST_PKG = HOST_LIB + '/' + PYTHON_X_Y
  87. PYTHON_PREFIX = APPDIR + '/opt/' + PYTHON_X_Y
  88. PYTHON_BIN = PYTHON_PREFIX + '/bin'
  89. PYTHON_INC = PYTHON_PREFIX + '/include/' + PYTHON_X_Y
  90. PYTHON_LIB = PYTHON_PREFIX + '/lib'
  91. PYTHON_PKG = PYTHON_LIB + '/' + PYTHON_X_Y
  92. # Copy the running Python's install
  93. log('CLONE', '%s from %s', PYTHON_X_Y, HOST_PREFIX)
  94. source = HOST_BIN + '/' + PYTHON_X_Y
  95. if not os.path.exists(source):
  96. raise ValueError('could not find {0:} executable'.format(PYTHON_X_Y))
  97. make_tree(PYTHON_BIN)
  98. target = PYTHON_BIN + '/' + PYTHON_X_Y
  99. copy_file(source, target, update=True)
  100. copy_tree(HOST_PKG, PYTHON_PKG)
  101. copy_tree(HOST_INC, PYTHON_INC)
  102. pip_source = HOST_BIN + '/' + PIP_X_Y
  103. if not os.path.exists(pip_source):
  104. pip_source = HOST_BIN + '/' + PIP_X
  105. if os.path.exists(pip_source):
  106. with open(pip_source) as f:
  107. f.readline()
  108. body = f.read()
  109. target = PYTHON_BIN + '/' + PIP_X_Y
  110. with open(target, 'w') as f:
  111. f.write('#! /bin/sh\n')
  112. f.write(' '.join((
  113. '"exec"',
  114. '"$(dirname $(readlink -f ${0}))/' + PYTHON_X_Y + '"',
  115. '"$0"',
  116. '"$@"\n'
  117. )))
  118. f.write(body)
  119. shutil.copymode(pip_source, target)
  120. relpath = os.path.relpath(target, APPDIR_BIN)
  121. make_tree(APPDIR_BIN)
  122. os.symlink(relpath, APPDIR_BIN + '/' + PIP_X_Y)
  123. # Remove unrelevant files
  124. log('PRUNE', '%s packages', PYTHON_X_Y)
  125. remove_file(PYTHON_LIB + '/lib' + PYTHON_X_Y + '.a')
  126. remove_tree(PYTHON_PKG + '/test')
  127. remove_file(PYTHON_PKG + '/dist-packages')
  128. matches = glob.glob(PYTHON_PKG + '/config-*-linux-*')
  129. for path in matches:
  130. remove_tree(path)
  131. # Wrap the Python executable
  132. log('WRAP', '%s executable', PYTHON_X_Y)
  133. with open(PREFIX + '/data/python-wrapper.sh') as f:
  134. text = f.read()
  135. text = text.replace('{{PYTHON}}', PYTHON_X_Y)
  136. make_tree(APPDIR_BIN)
  137. target = APPDIR_BIN + '/' + PYTHON_X_Y
  138. with open(target, 'w') as f:
  139. f.write(text)
  140. shutil.copymode(PYTHON_BIN + '/' + PYTHON_X_Y, target)
  141. # Set or update symlinks to python
  142. pythons = glob.glob(APPDIR_BIN + '/python?.*')
  143. versions = [os.path.basename(python)[6:] for python in pythons]
  144. latest2, latest3 = '0.0', '0.0'
  145. for version in versions:
  146. if version.startswith('2') and version >= latest2:
  147. latest2 = version
  148. elif version.startswith('3') and version >= latest3:
  149. latest3 = version
  150. if latest2 == VERSION:
  151. python2 = APPDIR_BIN + '/python2'
  152. remove_file(python2)
  153. os.symlink(PYTHON_X_Y, python2)
  154. has_pip = os.path.exists(APPDIR_BIN + '/' + PIP_X_Y)
  155. if has_pip:
  156. pip2 = APPDIR_BIN + '/pip2'
  157. remove_file(pip2)
  158. os.symlink(PIP_X_Y, pip2)
  159. if latest3 == '0.0':
  160. log('SYMLINK', 'python, python2 to ' + PYTHON_X_Y)
  161. python = APPDIR_BIN + '/python'
  162. remove_file(python)
  163. os.symlink('python2', python)
  164. if has_pip:
  165. log('SYMLINK', 'pip, pip2 to ' + PIP_X_Y)
  166. pip = APPDIR_BIN + '/pip'
  167. remove_file(pip)
  168. os.symlink('pip2', pip)
  169. else:
  170. log('SYMLINK', 'python2 to ' + PYTHON_X_Y)
  171. if has_pip:
  172. log('SYMLINK', 'pip2 to ' + PIP_X_Y)
  173. elif latest3 == VERSION:
  174. log('SYMLINK', 'python, python3 to ' + PYTHON_X_Y)
  175. python3 = APPDIR_BIN + '/python3'
  176. remove_file(python3)
  177. os.symlink(PYTHON_X_Y, python3)
  178. python = APPDIR_BIN + '/python'
  179. remove_file(python)
  180. os.symlink('python3', python)
  181. if os.path.exists(APPDIR_BIN + '/' + PIP_X_Y):
  182. log('SYMLINK', 'pip, pip3 to ' + PIP_X_Y)
  183. pip3 = APPDIR_BIN + '/pip3'
  184. remove_file(pip3)
  185. os.symlink(PIP_X_Y, pip3)
  186. pip = APPDIR_BIN + '/pip'
  187. remove_file(pip)
  188. os.symlink('pip3', pip)
  189. # Set a hook in Python for cleaning the path detection
  190. log('HOOK', '%s site packages', PYTHON_X_Y)
  191. sitepkgs = PYTHON_PKG + '/site-packages'
  192. make_tree(sitepkgs)
  193. copy_file(PREFIX + '/data/sitecustomize.py', sitepkgs)
  194. # Set RPATHs and bundle external libraries
  195. log('LINK', '%s C-extensions', PYTHON_X_Y)
  196. make_tree(APPDIR_LIB)
  197. patch_binary(PYTHON_BIN + '/' + PYTHON_X_Y, APPDIR_LIB, recursive=False)
  198. for root, dirs, files in os.walk(PYTHON_PKG + '/lib-dynload'):
  199. for file_ in files:
  200. if not file_.endswith('.so'):
  201. continue
  202. patch_binary(os.path.join(root, file_), APPDIR_LIB, recursive=False)
  203. for file_ in glob.iglob(APPDIR_LIB + '/lib*.so*'):
  204. patch_binary(file_, APPDIR_LIB, recursive=True)
  205. # Copy shared data for TCl/Tk
  206. tkinter = glob.glob(PYTHON_PKG + '/lib-dynload/_tkinter*.so')
  207. if tkinter:
  208. tkinter = tkinter[0]
  209. for dep in ldd(tkinter):
  210. name = os.path.basename(dep)
  211. if name.startswith('libtk'):
  212. match = re.search('libtk([0-9]+[.][0-9]+)', name)
  213. tk_version = match.group(1)
  214. break
  215. else:
  216. raise RuntimeError('could not guess Tcl/Tk version')
  217. tcltkdir = APPDIR_SHARE + '/tcltk'
  218. if (not os.path.exists(tcltkdir + '/tcl' + tk_version)) or \
  219. (not os.path.exists(tcltkdir + '/tk' + tk_version)):
  220. hostdir = '/usr/share/tcltk'
  221. if os.path.exists(hostdir):
  222. make_tree(APPDIR_SHARE)
  223. copy_tree(hostdir, tcltkdir)
  224. else:
  225. make_tree(tcltkdir)
  226. tclpath = '/usr/share/tcl' + tk_version
  227. if not tclpath:
  228. raise ValueError('could not find ' + tclpath)
  229. copy_tree(tclpath, tcltkdir + '/tcl' + tk_version)
  230. tkpath = '/usr/share/tk' + tk_version
  231. if not tkpath:
  232. raise ValueError('could not find ' + tkpath)
  233. copy_tree(tkpath, tcltkdir + '/tk' + tk_version)
  234. # Bundle the entry point
  235. apprun = APPDIR + '/AppRun'
  236. if not os.path.exists(apprun):
  237. log('INSTALL', 'AppRun')
  238. entrypoint = '"${{APPDIR}}/usr/bin/python{:}" "$@"'.format(VERSION)
  239. _copy_template('apprun.sh', apprun, entrypoint=entrypoint)
  240. # Bundle the desktop file
  241. desktop_name = 'python{:}.desktop'.format(FULLVERSION)
  242. desktop = os.path.join(APPDIR, desktop_name)
  243. if not os.path.exists(desktop):
  244. log('INSTALL', desktop_name)
  245. apps = 'usr/share/applications'
  246. appfile = '{:}/{:}/python{:}.desktop'.format(APPDIR, apps, FULLVERSION)
  247. if not os.path.exists(appfile):
  248. make_tree(os.path.join(APPDIR, apps))
  249. _copy_template('python.desktop', appfile, version=VERSION,
  250. fullversion=FULLVERSION)
  251. os.symlink(os.path.join(apps, desktop_name), desktop)
  252. # Bundle icons
  253. icons = 'usr/share/icons/hicolor/256x256/apps'
  254. icon = os.path.join(APPDIR, 'python.png')
  255. if not os.path.exists(icon):
  256. log('INSTALL', 'python.png')
  257. make_tree(os.path.join(APPDIR, icons))
  258. copy_file(PREFIX + '/data/python.png',
  259. os.path.join(APPDIR, icons, 'python.png'))
  260. os.symlink(os.path.join(icons, 'python.png'), icon)
  261. diricon = os.path.join(APPDIR, '.DirIcon')
  262. if not os.path.exists(diricon):
  263. os.symlink('python.png', diricon)
  264. # Bundle metadata
  265. meta_name = 'python{:}.appdata.xml'.format(FULLVERSION)
  266. meta_dir = os.path.join(APPDIR, 'usr/share/metainfo')
  267. meta_file = os.path.join(meta_dir, meta_name)
  268. if not os.path.exists(meta_file):
  269. log('INSTALL', meta_name)
  270. make_tree(meta_dir)
  271. _copy_template('python.appdata.xml', meta_file, version=VERSION,
  272. fullversion=FULLVERSION)