relocate.py 11 KB

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