relocate.py 11 KB

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